text:
Q: Weak convergence of a sequence $(f_n) \subset L^2(\mathbb{R})$ and convergence of $\chi_n f_n$ I am asked to solve the following problem.
Let $(f_n)_n \subset L^2(\mathbb{R})$ be such that $f_n \rightharpoonup f$ in $L^2(\mathbb{R})$. Let $I_n = (-n, n)$ and denote with $\chi_n$ the characteristic function of $I_n$.

*

*Prove that for all $\psi \in L^1(\mathbb{R})$, $\int_{\mathbb{R} \setminus I_n} |\psi(x)| dx \rightarrow 0$.

This follows from the absolute continuity of the integral. In fact, $I_n$ is Lebesgue measurable thus $\mathbb{R} \setminus I_n$, being the complement of $I_n$, is Lebesgue measurable, that is $\mu (\mathbb{R} \setminus I_n) = \mu ( (-\infty, -n] \cup [n, \infty)) = \mu ( (-\infty, -n]) + \mu ( [n, \infty]) \rightarrow 0$ as $n$ approaches $\infty$ (I believe that an alternative way to see it is from the fact that $\mu(I_n) \rightarrow \infty$). Hence the thesis.

*Prove that for all $\phi \in L^2(\mathbb{R})$, $\int_{\mathbb{R} \setminus I_n} |f_n(x) \phi(x)| dx \rightarrow 0$
My idea was to use both the result of point 1. and the weak convergence of $(f_n)_n$. However, I am struggling to conclude since here the set on which I am integrating depends on $n$ as well. By rewriting the integral in this way
$\int_{\mathbb{R}\setminus I_n} |f_n(x) \phi(x)| dx = \int_{\mathbb{R}} f_n(x) \chi_n(x) \phi(x) dx$
my attempt was to prove that also $\chi_n f_n \rightharpoonup f$. Then, I could conclude from the weak convergence of $\chi_n f_n$. Nevertheless, I cannot formalize this reasoning.

*Exhibit an example of a sequence $h_n = f_n - \chi_n f_n$ which converges weakly to $0$ but not strongly.

I was thinking about a sequence with norm equal to $1$ for all $n$ which converges weakly to zero, but I have few ideas.
Any hint on how to proceed would be greatly appreciated.

A: For the first part, your argument works if you define $\mu(B)=\int_B \lvert \psi\rvert d\lambda$, where $\lambda$ denotes the Lebesgue  measure.
Alternatively, you can approximate in $\mathbb L^1$ by a linear combination of indicator functions of Borel sets of finite measure to get the result.

*Denote  $$\left\langle u,v \right\rangle := \int_{\mathbb R}u(x)v(x) dx$$
and $g_n(x):=\operatorname{sgn}\left(f_n(x)\right)\mathbf{1}_{\mathbb R\setminus I_n}(x)\lvert \psi(x)\rvert $, where $\operatorname{sgn}(y)=1$ if $y>0$, $\operatorname{sgn}(y)=-1$ if $y<0$ and $\operatorname{sgn}(0)=0$.
Then $$\int_{\mathbb R \setminus I_n} |f_n(x) \phi(x)| dx=\left\langle f_n,g_n \right\rangle $$ and since $g_n\to 0$ strongly in $\mathbb L^2$ (by the first question), we get the wanted result.


text:
Q: Use Java to get resource on diff computer  private static final String FILE_PATH = "MessageCompare\\src\\main\\resources\\json\\test.json";`

 File file = new File(FILE_PATH);

 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath())));`

In my computer, file.getAbsolutePath() return
D:\Dev\Tool\MessageCompare\MessageCompare\src\main\resources\json\test.json
In other computer, file.getAbsolutePath() return
D:\Dev\Tool\MessageCompare\src\main\resources\json\test.json
Why does absolute path of file return one more node than others' computer?

A: It could be better to use relative path to guarantee cross-platform.
Usually, two ways to get resource:

*

*getClass().getResourceAsStream()<Non static method> & xxx.Class.getResourceAsStream()<static method>

*getClass().getClassLoader().getResourceAsStream()<Non static method> & xxx.Class.getClassLoader().getResourceAsStream()<static method>

What's the difference?
Please notice this structure

*

*About #1, it use:
InputStream in = getClass().getResourceAsStream("/json/rti.json");

*For #2, it use: InputStream in = getClass().getClassLoader().getResourceAsStream("json/rti.json");

A: You shouldn't rely on the Absolute path of a file for this very reason, it all depends on the location from which the other person is running the code.  In your case there is an additional MessageCompare directory.
Instead, use the class loader to load the file:
MyClass.class.getResourceAsStream("/myFile.txt");
That way your code will be more portable.

A: File file = new File(FILE_PATH);

This line creates a file. The path of the file depends on your project folder and setup. If your workstation includes another folder inside named "MessageCompare" and your project is set up in that folder, that may be the reason you are getting an extra node.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SharePoint view with 2900 records throwing 5000 limit error I have a list that resides on SharePoint 2013 and we manage the records in The list using MS Access 2016.  Basic add, remove, update to match stuff to an excel file we are provided twice per month.
I am running into the 5000 record error on list views with active filters that only have say 2900 records meeting the criteria.
If I query for the same filters in access I get the 2900 and the list only has 5200 total records.
I am looking for any direction of things to look for or articles to read that may help point me in the right direction of what may be causing this.
Thank you very n advance for any assistance you can provide.

A: What i have experienced with this is that if you have multiple conditions in your filter, and one of them returns over 4999 items you will get that error. What i have done in my case is to add conditions to my filter that use indexed columns to help initially limit the number of items result based on the indexed column.
For example, in my scenario, I had a filter that was based on the workflow status and the current user. But my filter initially did not use an indexed column and the condition "Status eq 'Approved'" returned over 5000 items.
https://tenant.sharepoint.com/sites/dev/_api/web/lists/getByTitle('Approvals')/items?$filter=Status eq 'Completed' and Author/EMail eq 'user@contoso.com'

Changing the query to use the indexed AuthorId column, resolved my issue.
https://tenant.sharepoint.com/sites/dev/_api/web/lists/getByTitle('Approvals')/items?$filter=AuthorId eq 1234 and Status eq 'Completed'


text:
Q: Should the arraylist passed to an ArrayAdapter of a List be thread-safe? The array list we pass to a custom array adapter are we supposed to modify it in a thread safe way?
I mean if I have   private class MyAdapter extends ArrayAdapter<CustomObject> and I  instantiate it with my ArrayList of CustomObjects if I later want to modify that array list or objects in the array list in order to then notify the adapter that the UI should be updated should I do it in a thread safe way? E.g. passing a synchronized array list?

A: If you modify the list on the main/UI thread, then go ahead. The ListView itself operates also on the UI thread.
If you change the list from another thread, you may have to handle synchronization issues. Though it should not cause any problems when the ListView is not scrolling, i.e. does not access the Adapter.
To change the list anytime from another thread, you have to post all changes to the UI thread.
// this code is executed in another thread
// e.g. download some data
// determine which list elements get changed

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // change th actual list here and notifyDataSetChanged()
    }
});

If it's too complicated to determine what elements need to change, you also could create a new list and a new adapter:
// this code is executed in another thread
// e.g. download some data
// create a new list and/or a new adapter
final MyAdapter adapter = new MyAdapter(...);

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // set the new adapter to the ListView
        listview.setAdapter(adapter);
    }
});

A: No, the UI is updated in the UI thread when you call notifyDataSetChanged(). Its handled by android properly

A: Since it is a custom adapter,what if you were to maintain 2 array lists.
public ArrayList<CustomObject> modifiableList;
private ArrayList<CustomObject> adapterList;

and you do all your changes to the modifiableList,
Then when you can determine the user is not scrolling your UI, you can call notifyDatasetChangedCustom()
EDIT: if you are doing it from another thread,you could maintain a WeakReference to your adapter and then call the changes.
 public notifyDatasetChangedCustom(){
    this.adapterList=this.modifiableList;
    this.notifyDatasetChanged();
 }

You could also try looking into AsyncTaskLoader.This would take care addition of items and view updating automatically,although the implementation would be more complicated.


text:
Q: When the word period is used after a sentence, what does it mean?
Possible Duplicate:
What does 'period' mean when someone says "something, period"?

When the word period is used after a sentence, like so:

Bacon is awesome. Period.

What does it mean?


text:
Q: JQuery prevent Doubleclick and unexpected behavior on Carousel I have the following JQuery driven carousel - the code for that is:
$('#carousel_ul:not(:animated)').animate({'left' : left_indent, opacity:0},600,function(){
            /* when the animation finishes use the if statement again, and  make an illusion
            of infinity by changing place of last or first item*/
            if(where == 'left'){
                //...and if it slided to left we put the last item before  the first item
                $('#carousel_ul li:first').before($('#carousel_ul  li:last'));
            }else{
                //...and if it slided to right we put the first item after the last item
                $('#carousel_ul li:last').after($('#carousel_ul li:first'));
            }

            //...and then just get back the default left indent
            $('#carousel_ul').css({'left' : '-300px'});
 });

I'd like to prevent the ability to doubleclick the button and also, disable clicking all together while the #carousel_ul is animating and then re-enable the button on completion of the animation. Here is a roughed together codepen with all of the code:  http://codepen.io/anon/pen/epVObx (please excuse the placeholder images) Also, the relevant code begins at the comment in the JQuery: //FUNCTIONS BELOW
Thanks in advance for any guidance -


text:
Q: How to solve this boundary value problem (2 coupled odes) with NDSolve I am solving a boundary value problem which is consisted of two odes.
Mathematica prompts that SolveDelayed -> True should be considered. However, the problem can not be solved even if this option was used.
I have read this post and this post, but none of them helps.
Thanks for any suggestions.
Below is my code.
g = 15/10000;
Ri = 38/1000;
Ro = Ri + g;
m = 1/1000;
ηpos = 1/10;
τy = 2;
ϵ = 0.1;
λ = 1;
dpdz = 10^3;

η = τy/(Sqrt[u'[r]^2] + 10^-10) (1 - Exp[-m Sqrt[u'[r]^2]]) + ηpos;
τzz = τrz[r]^2 (2 λ)/η;
ode = {τrz[r] == η/(1 + (ϵ λ/η) τzz) u'[r], 1/r D[r τrz[r], r]== dpdz,
       u[Ri] == 0, u[Ro] == 0};
sol = NDSolve[ode, {u, τrz}, {r, Ri, Ro}]

A: You can regard the trz separetly.
First I rationalize all parameters and rewrite equation for simple testing later.
ode = {0 == -τrz[
  r] + η/(1 + (ϵ λ/η) τzz) u'[r],
  1/r D[r τrz[r], r] == dpdz, u[Ri] == 0, u[Ro] == 0}

Since trz does not depend on u, treat it separatly.
dsol = DSolve[τrz[r]/r + Derivative[1][τrz][r] ==
          1000, τrz, r]

{*  {{τrz -> Function[{r}, 500 r + C[1]/r]}    *}

Insert the result and apply a starting condition instead of boundary condition, since NDSolve can not find an explicit equation for u'[r] and therefore switches to differential-algbraic equation.
ode2 = Join[Most[ode] /. First@dsol /. C[1] -> c, {u'[Ri] == aa}]

Omitt the trz part
ode3 = ode2[[{1, 3, 4}]]

Find a solution for the c parameter in dependance of aa with a little trick, since Solve does not find a solution for undefined aa.
cc2[aa_] =
   c /. First@
 Solve[ode3[[1]] /. r -> Ri /. u'[Ri] -> -Pi, c, Reals] /.
      Pi -> -aa;

Since shooting method did not work with Version 8.0, I guessed a value for aa. Find the exact aa with FindRoot.
ndsol = NDSolve[ode3 /. c -> cc2[aa] /. aa -> -88.1, u, {r, Ri, Ro}]

The solution satisfies ode.
u[Ri] /. ndsol
u[Ro] /. ndsol
Plot[u[r] /. ndsol, {r, Ri, Ro},
    Epilog -> {Red, Point[{Ro, u[Ro] /. First@ndsol}]}]

and the error (would be lower with aa found by FindRoot)
Plot[Evaluate[
   ode3[[1, 2]] /. c -> cc2[aa] /. aa -> -88.1 /. First@ndsol], {r, Ri,
    Ro}, PlotRange -> All]

A: Hint.
Solve it as an initial value problem, and then use a shooting method. The following formulation
g = 15/10000;
Ri = 38/1000;
Ro = Ri + g;
m = 1/1000;
ηpos = 1/10;
τy = 2;
ϵ = 1/10;
λ = 1;
dpdz = 10^3;

η = τy/(u'[r] + 10^-10) (1 - Exp[-m u'[r]]) +ηpos;
τzz = τrz[r]^2 (2 λ)/η;
ode = {τrz[r] == η/(1 + (ϵ λ/η) τzz) u'[r], 1/r D[r τrz[r], r] == dpdz,
       u[Ri] == 0, τrz[Ri] == -0.75};
sol = NDSolve[ode, {u, τrz}, {r, Ri, Ro}, Method->{"EquationSimplification" -> "Residual"}];
Plot[Evaluate[u[r] /. sol], {r, Ri, Ro}, PlotStyle -> {Thick, Blue}]

Practically solves the boundary issue. Use then the shooting method.


text:
Q: Get IndexPath.Row from TableView Objective C Before asking this question, I searched a lot on Google and Stackoverflow. Tried also some examples, but I can't make the function work.
Since the hierarchy of the tableview is changed since iOS 7, is it kind of hard to find a solution.
I got a standard tableview with a couple items and one button on the screen.
I need to get the indexPath.row number when selecting an item from the tableview and clicking on the button.
This is my code
- (IBAction)buttonGetNumber:(id)sender {

    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[(UIView *)[button superview] superview]];
    NSLog(@"%i", indexPath.row);
}

This keeps returning a '0', no matter which item I select from the tableview.
I also tried this (2):
- (IBAction)buttonGetNumber:(id)sender {
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    NSLog(@"%i", index.row);
}

This also returns a '0'.
I also tried this (3):
- (IBAction)buttonGetNumber:(id)sender {
    UIButton *senderButton = (UIButton *)sender;
    UITableViewCell *buttonCell = (UITableViewCell *)[[senderButton superview] superview];
    UITableView* table = (UITableView *)[buttonCell superview];
    NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
    NSInteger rowOfTheCell = [pathOfTheCell row];
    NSLog(@"%i", rowOfTheCell);
}

And this makes the application crash.
Any clue how I can solve this?

A: Create an instance variable _lastClickedRow Set it with tableview delegate like below. And when you click the to "Get Row" button use _lastClickedRow.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    _lastClickedRow = indexPath.row;
}

- (IBAction)buttonGetNumber:(id)sender {

    NSLog(@"%d" , _lastClickedRow);
}

A: If for some reason selected cell doesn't work for you (e.g. for a multiple selection case), you could get row from sender's frame:
- (IBAction)buttonGetNumber:(id)sender
{
    CGPoint buttonOrigin = sender.frame.origin;
    CGPoint pointInTableview = [self.tableView convertPoint:buttonOrigin fromView:sender.superview];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTableview];
    if (indexPath) {
        // Do your work
    }
}

A: You simply set the tag of the UIButton same as the indexPath.row using:
yourButton.tag = indexPath.row;

in didSelectRowForIndexPath:.
Then in buttonGetNumber: method, you get the row number using:
int rowNum = [(UIButton*)sender tag];

Here, you have the advantage of not using any third variable.


text:
Q: SSRS Count Distinct Expression into a Yes or No I'm wondering if there's a way or an expression I could use in SSRS to show a Yes or No based on a Distinct Count function?
Example of what I'm currently using - RM_Name is the group
=CountDistinct(iif(Fields!qtrtradecnt.Value >= 15, 1, Nothing), "RM_Name")

I also would like to show if the qtrtradecnt is >= 15 to show a Y or N based on the RM_Name group, and maybe countdistinct is not the correct function to use...I've messed with this for days.
Thank you!

A: One way to do this is to the calculation in your your dataset.. with a case expression..
select
...
,case when your_table.qtrtradecnt >= 15 then 1 else 0 end as rm_count

from your_table

Then in your report just do a

=iif(sum(Fields!rm_count.value) >15 then 'Y','N')


text:
Q: Sorting problems with charts in C# I'm using System.Windows.Forms.DataVisualization.Charting.Chart() to create a chart png file. I have the following code:
string t = @"<Chart>
            <ChartAreas>
                <ChartArea Name=""Default"" _Template_=""All"">
                    <AxisX Interval=""1""></AxisX>
                </ChartArea>
            </ChartAreas>
        </Chart>";

var chart = new System.Windows.Forms.DataVisualization.Charting.Chart()
{
    Size = new Size(x, y),
    Titles = { chartName },
};

var series = new Series("Savings");
series.ChartType = SeriesChartType.Line;
series.Points.DataBindXY(preparedGraphCollection.Keys, preparedGraphCollection.Values);

chart.ChartAreas.Add(new ChartArea());
chart.ChartAreas[0].AxisX.Interval = 1;

chart.Series.Add(series);

System.IO.Directory.CreateDirectory(graphTempFilePath);
chart.SaveImage(graphTempFilePath + filename + ".png", ChartImageFormat.Png);

preparedGraphCollection contains a KayValuePair list, where the keys represent week numbers and the values is an incrementing number for each week, like so
50 => 310
51 => 335
52 => 340
1 => 350
2 => 375

My problem is that even though i havent sent any sorting or so in the chart, the chart comes out where the week numbers are sorted in a way so that the smallest number is plotted in first. This gives a wierd looking chart. Even though the keys and values are not sorted this way, the Chart is created with that kind of sorting. To show it like above, its like the chart has recieved the data like so:
1 => 350
2 => 375
50 => 310
51 => 335
52 => 340

Do you have any suggestions?

A: Since your x-values are numbers they are added in place.
To make them show in the order you add them instead, you can

*

*either set Series.IsXValueIndexed = true

*or add them as DateTime and set the individual Labels to the week numbers.

*Or you could add them add strings.
A few notes:

*

*The former is really simple but will not create proportional spacing. As you probably don't want/need that, I suggest setting the series to be indexed.

*The second option is tricky as week numbers do not easily convert to the correct dates.

*Adding x-values as strings is not recommended as it will lose the actual values! (Even though the labels will still look ok..)
IsXValueIndexed is also often used to avoid gaps in the data like weekends etc..
Note that now all other Series in the same ChartArea must also be indexed.


text:
Q: How I can use the Intranetwebapplication in mvc3 I want use asp.net mvc 3 and use intranet application but I don't have this option :( How I get the intranet application

and how I get mvc4 or it don't work on vs2010?

A: According to my knowledge, you just develop a web aplication and then usually
it's important to have structure where customers vain access a server-capable network traffic


text:
Q: Linux: MPC current song output I try to make custom output on my internet Radio. (mpd/mpc)
getInfo.py:
#!/bin/bash
opt=$@
mpc $opt &> /dev/null

station="`mpc --format \"[%name%]\" | head -n 1`"
title="`mpc --format \"[%title%]\" | head -n 1`"
vol="`mpc | head -n 2 | tail -n 1 | awk {'print $4'}`"

echo $station
echo $title
echo "Volume: "${vol//[()_]/}

And save output witch wach -n getInfo.py > radio.log
Output format is here:
Amazing Smooth and Jazz
Koop - Koop Island Blues
Volume: 100%

So i need each time when output changes show output on shell.
How to do that?

A: If you're only looking for the song output to update when changed, mpc has the command current that has a --wait option that tells mpc to block until the next song before displaying the result, this allows you to loop on it.  From there you can update whatever software you want with it.
For example:
while :; do notify-send --urgency=low -i "audio-headphones" "$(mpc current --wait)"; done &

A: To get you started:
#!/usr/bin/python3
from subprocess import Popen, PIPE

last_output = ""
while(1):
    proc = Popen(["mpc"], stdout=PIPE)
    output, retval = proc.communicate()
    if not output == last_output:
        print(output.decode('ascii'))
    last_output = output

I will leave fine-tuning the output to you.


text:
Q: Unable to define a custom loss function in keras Using:

*

*Keras 2.1.5

*ipython 6.2.1

*ipython_genutils 0.2.0

*Python 3

*Windows 7(x64) - 8GB ram - only CPU

I am trying to make a neural network on jupyter notebook and it was working fine until I decided to code a custom loss function. For a starter, I decided to code a simple mean square loss function.
The loss function is:
def msqeloss(y_true, y_pred):
     return K.sum(K.square(y_true-y_pred),0)

And I input this function into the model as:
...
model.add(Dropout(0.1))
model.add(Flatten())
model.add(Dense(120,activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(3,activation='softmax'))
model.compile(optimizer='RMSprop',loss=msqeloss,metrics=['accuracy'])
...

The full-stack error comes out to be this:
 AttributeError                            Traceback (most recent call last)
<ipython-input-10-86f0a38b9a14> in <module>()
     42         model.add(Dropout(0.1))
     43         model.add(Dense(3,activation='softmax'))
---> 44         model.compile(optimizer='RMSprop',loss=msqeloss,metrics=['accuracy'])
     45         csv_logger = CSVLogger('meanlog_loss_log'+str(index)+'.csv', append=True, separator=';')
     46         model.fit(Xtrain,one_hot_labels,batch_size=10,epochs=Epochs,validation_data=(Xtest,np_utils.to_categorical(ytest, num_classes=3)),callbacks=[csv_logger])

~\Anaconda3\lib\site-packages\keras\models.py in compile(self, optimizer, loss, metrics, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    822                            weighted_metrics=weighted_metrics,
    823                            target_tensors=target_tensors,
--> 824                            **kwargs)
    825         self.optimizer = self.model.optimizer
    826         self.loss = self.model.loss

~\Anaconda3\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    828                 with K.name_scope(self.output_names[i] + '_loss'):
    829                     output_loss = weighted_loss(y_true, y_pred,
--> 830                                                 sample_weight, mask)
    831                 if len(self.outputs) > 1:
    832                     self.metrics_tensors.append(output_loss)

~\Anaconda3\lib\site-packages\keras\engine\training.py in weighted(y_true, y_pred, weights, mask)
    427         """
    428         # score_array has ndim >= 2
--> 429         score_array = fn(y_true, y_pred)
    430         if mask is not None:
    431             # Cast the mask to floatX to avoid float64 upcasting in Theano

<ipython-input-9-d8157a575c41> in msqeloss(y_true, y_pred)
      1 def msqeloss(y_true, y_pred):
----> 2     return K.sum(K.square(y_true-y_pred),0)

AttributeError: 'int' object has no attribute 'sum'

I am pretty new to Keras and any help would be highly appreciated. Please, help me out on this one since it has been bothering me for 2 days now.
Thanks in advance.


text:
Q: groupby.aggregate and modification then cast / reindex I look for applying some deviation to a monthly granularity structure of a dataframe and then recast it in the initial dataframe. I firstly do a groupby and aggregate. This part works well. Then I reindex and take NaN. I want the reindexation will be done by matching month of the groupby element with the initial dataframe.
I want be able to due this operation on different granularity (yearly -> month & year, ...)
Has someone the solution of this problem ?
>>> df['profile']
date
2015-01-01 00:00:00    3.000000
2015-01-01 01:00:00    3.000143
2015-01-01 02:00:00    3.000287
2015-01-01 03:00:00    3.000430
2015-01-01 04:00:00    3.000574
...
2015-12-31 20:00:00    2.999426
2015-12-31 21:00:00    2.999570
2015-12-31 22:00:00    2.999713
2015-12-31 23:00:00    2.999857
Freq: H, Name: profile, Length: 8760

### Deviation on monthly basis
>>> dev_monthly = np.random.uniform(0.5, 1.5, len(df['profile'].groupby(df.index.month).aggregate(np.sum)))

>>> df['profile_monthly'] = (df['profile'].groupby(df.index.month).aggregate(np.sum) * dev_monthly).reindex(df)

>>> df['profile_monthly']
date
2015-01-01 00:00:00   NaN
2015-01-01 01:00:00   NaN
2015-01-01 02:00:00   NaN
...
2015-12-31 22:00:00   NaN
2015-12-31 23:00:00   NaN
Freq: H, Name: profile_monthly, Length: 8760

A: Check out the documentation for resampling.
You're looking for resample followed by fillna with method='bfill':
In [105]: df = DataFrame({'profile': normal(3, 0.1, size=10000)}, pd.date_range(start='2015-01-
01', freq='H', periods=10000))

In [106]: df['profile_monthly'] = df.profile.resample('M', how='sum')

In [107]: df
Out[107]:
                     profile  profile_monthly
2015-01-01 00:00:00   2.8328              NaN
2015-01-01 01:00:00   3.0607              NaN
2015-01-01 02:00:00   3.0138              NaN
2015-01-01 03:00:00   3.0402              NaN
2015-01-01 04:00:00   3.0335              NaN
2015-01-01 05:00:00   3.0087              NaN
2015-01-01 06:00:00   3.0557              NaN
2015-01-01 07:00:00   2.9280              NaN
2015-01-01 08:00:00   3.1359              NaN
2015-01-01 09:00:00   2.9681              NaN
2015-01-01 10:00:00   3.1240              NaN
2015-01-01 11:00:00   3.0635              NaN
2015-01-01 12:00:00   2.9206              NaN
2015-01-01 13:00:00   3.0714              NaN
2015-01-01 14:00:00   3.0688              NaN
2015-01-01 15:00:00   3.0703              NaN
2015-01-01 16:00:00   2.9102              NaN
2015-01-01 17:00:00   2.9368              NaN
2015-01-01 18:00:00   3.0864              NaN
2015-01-01 19:00:00   3.2124              NaN
2015-01-01 20:00:00   2.8988              NaN
2015-01-01 21:00:00   3.0659              NaN
2015-01-01 22:00:00   2.7973              NaN
2015-01-01 23:00:00   3.0824              NaN
2015-01-02 00:00:00   3.0199              NaN
                         ...              ...

[10000 rows x 2 columns]

In [108]: df.dropna()
Out[108]:
            profile  profile_monthly
2015-01-31   2.9769        2230.9931
2015-02-28   2.9930        2016.1045
2015-03-31   2.7817        2232.4096
2015-04-30   3.1695        2158.7834
2015-05-31   2.9040        2236.5962
2015-06-30   2.8697        2162.7784
2015-07-31   2.9278        2231.7232
2015-08-31   2.8289        2236.4603
2015-09-30   3.0368        2163.5916
2015-10-31   3.1517        2233.2285
2015-11-30   3.0450        2158.6998
2015-12-31   2.8261        2228.5550
2016-01-31   3.0264        2229.2221

[13 rows x 2 columns]

In [110]: df.fillna(method='bfill')
Out[110]:
                     profile  profile_monthly
2015-01-01 00:00:00   2.8328        2230.9931
2015-01-01 01:00:00   3.0607        2230.9931
2015-01-01 02:00:00   3.0138        2230.9931
2015-01-01 03:00:00   3.0402        2230.9931
2015-01-01 04:00:00   3.0335        2230.9931
2015-01-01 05:00:00   3.0087        2230.9931
2015-01-01 06:00:00   3.0557        2230.9931
2015-01-01 07:00:00   2.9280        2230.9931
2015-01-01 08:00:00   3.1359        2230.9931
2015-01-01 09:00:00   2.9681        2230.9931
2015-01-01 10:00:00   3.1240        2230.9931
2015-01-01 11:00:00   3.0635        2230.9931
2015-01-01 12:00:00   2.9206        2230.9931
2015-01-01 13:00:00   3.0714        2230.9931
2015-01-01 14:00:00   3.0688        2230.9931
2015-01-01 15:00:00   3.0703        2230.9931
2015-01-01 16:00:00   2.9102        2230.9931
2015-01-01 17:00:00   2.9368        2230.9931
2015-01-01 18:00:00   3.0864        2230.9931
2015-01-01 19:00:00   3.2124        2230.9931
2015-01-01 20:00:00   2.8988        2230.9931
2015-01-01 21:00:00   3.0659        2230.9931
2015-01-01 22:00:00   2.7973        2230.9931
2015-01-01 23:00:00   3.0824        2230.9931
2015-01-02 00:00:00   3.0199        2230.9931
                         ...              ...

[10000 rows x 2 columns]

A: When I use your code, I haven't same value for 2015-12-31 00:00:00 and 2015-12-31 01:00:00 as you can see below :
>>> df.fillna(method='bfill')[np.logical_and(df.index.month==12, df.index.day==31)]
                    profile  profile_monthly
2015-12-31 00:00:00  2.926504      2232.288997
2015-12-31 01:00:00  3.008543      2234.470731
2015-12-31 02:00:00  2.930133      2234.470731
2015-12-31 03:00:00  3.078552      2234.470731
2015-12-31 04:00:00  3.141578      2234.470731
2015-12-31 05:00:00  3.061820      2234.470731
2015-12-31 06:00:00  2.981626      2234.470731
2015-12-31 07:00:00  3.010749      2234.470731
2015-12-31 08:00:00  2.878577      2234.470731
2015-12-31 09:00:00  2.915487      2234.470731
2015-12-31 10:00:00  3.072721      2234.470731
2015-12-31 11:00:00  3.087866      2234.470731
2015-12-31 12:00:00  3.089208      2234.470731
2015-12-31 13:00:00  2.957047      2234.470731
2015-12-31 14:00:00  3.002072      2234.470731
2015-12-31 15:00:00  3.106656      2234.470731
2015-12-31 16:00:00  3.100891      2234.470731
2015-12-31 17:00:00  3.077835      2234.470731
2015-12-31 18:00:00  3.032497      2234.470731
2015-12-31 19:00:00  2.959838      2234.470731
2015-12-31 20:00:00  2.878819      2234.470731
2015-12-31 21:00:00  3.041171      2234.470731
2015-12-31 22:00:00  3.061970      2234.470731
2015-12-31 23:00:00  3.019011      2234.470731

[24 rows x 2 columns]

So I finally found the following solution :
>>> AA  = df.groupby((df.index.year, df.index.month)).aggregate(np.mean)
>>> AA['dev'] = np.random.randn(0,1,len(AA))
>>> df['dev'] = AA.ix[zip(df.index.year, df.index.month)]['dev'].values

Short and rapid. The only question is :
=> How to deal with other granularity (half year, quarter, week, ...) ?


text:
Q: Doctrine Entity looping through another Entity I currently have a Property entity which has a relationship with PropertyRates. I need to find out the latest a PropertyRate has been updated. Currently I have a function in the Property entity to loop the associated PropertyRates and return the latest PropertyRate->dateModified. This runs out of memory very quickly looping through thousands of Properties.
public function getRatesDateModified()
{
    $retval = new \DateTime("2000-01-01T06:00:00Z");
    foreach($this->propertyRates as $rate) {
        if($retval < $rate->getDateModified()) {
            $retval = $rate->getDateModified();
        }
    }

    return $retval;
}

Is this where this function should sit? It didn't seem right to put it in the repository as it is specific to a single entity, but without access to the EntityManager so I can detach the PropertyRates I run out of memory.

A: If you're using doctrine, might I suggest using the filtering api. Maybe something like this.
<?php

use Doctrine\Common\Collections\Criteria;

$entity = $entityManager->find('Entity', $id);
$propertyRates = $entity->getPropertyRates();

$criteria = Criteria::create()
    ->where(Criteria::expr()->orderBy(["dateModified"]))
    ->setFirstResult(0)
    ->setMaxResults(20);

$result = $userCollection->matching($criteria)[0];


text:
Q: Seeking developer-friendly web GIS? I'm a recent Computer Science graduate who prides himself on his knowledge of software development and problem solving, but has no idea how GIS systems work. (Read: I'm a programmer.)
I've been charged with developing (ie. coding) a new webmap from scratch.
I can program in any language that has bindings to COM (Microsoft Component Object Model), so I've been writing in PHP.

A: If you are interested in Open Source projects, you'll find the answers to this question helpful: What are the FOSS equivalents to these ArcGIS products?
There are quite a lot of different options how to build an OS web mapping stack. Without knowing your use case it's a little difficult to suggest one over the other.

A: I use GeoServer and connect to an Oracle Database (plugin required for geoserver) this happens to be old Geomedia Datastore that was reprojected into a better coordinate system.
Then use Openlayers to be the map interface of that data (data is pulled from Geoserver by WMS (Web Mapping Service)
Good documentation for this is
http://workshops.opengeo.org/stack-intro/openlayers.html
(you have greater control on this and can customise it as much as as you wish so.)

A: I would recommend checking out the OpenGeo Suite.

A: If a Java solution is an option, have a look at Geomajas. This is a framework for integrating GIS data which gives you a uniform way to handle and display GIS data. Geomajas excels especially in the integration aspects giving powerful end-to-end security, good performance etc.
For the client side development it helps by allowing you to work in Java only thanks to GWT.
For non-java shops there is a JavaScript API in process, but I fear this is not yet sufficiently mature to use at this moment. That should get better in a month or two.

A: Fortunately for you (and all of us!), there are plenty of available (and mature!) options in the FOSS4G world!
Following your technology preferences here's some examples:

*

*Python

*

*Mapfish (not updated since 2011)

*GeoDjango

*PHP

*

*PMapper

*pure Javascript

*

*OpenLayers

*LeafLet

*OpenLayers + ExtJS

*OpenLayers + Jquery Mapquery, jeobrowser
For a more complete reference please visit OSGeo.org. It's an umbrella organization for the most popular FOSS geospatial projects out there.
Maybe if you're in the neighborhood you can visit the annual FOSS4G conference. Here's a list of workshops that happened in 2011 regarding web mapping technologies:

*

*MapFish in Production

*Introduction to Geomajas

*The Moose is loose, Mapping with GeoMoose

*OpenLayers Application Development

*Web Mapping with GeoServer

*Developing OGC Compliant Web Applications With GeoExt

*Interactive space-time dynamics: A hands-on introduction to i2maps

*A complete open source web mapping stack

*There's JavaScript in your backend: Front to Back JavaScript with NodeJS and Polymaps
As for my personal experience developing web mapping applications based on pure javascript/html/css frameworks (OpenLayers/jQuery) can be really straightforward.


text:
Q: Javascript - Dynamic grid fancy delete option I have an AJAX dynamic grid and when i want to delete an item i click a link (href='javascript:void(0)') and the item's gone. That's no problem. What the problem is I don't want the item to simply disappear, I want to add a kind of special effect, like to make the item shrink, and those items around it to gradually take its place. Maybe like Digg, when you bury stuff there. I would really appreciate your help!

A: try:
$("selector").slideUp("slow", function () {
    $(this).remove();
});

A: Lookup jquery effects:
http://api.jquery.com/category/effects/


text:
Q: changing app-ID I have an iPhone app (Show of Hands) that has been a freebie for nearly two years, with about 100,000 downloads. Now I want to enable in-app purchases to let users turn off iAds, but I cannot do so because I originally used a wildcard App-ID. Wildcard IDs can't support in-app-purchases...
Is it possible to change my existing App-ID without creating a new app, and not break the upgrade path etc. for all of my existing users?
Thanks!

A: Changing the App-ID of your provisioning profile doesn't change anything about your app. Just use the new App-ID without changing your bundle ID and you're good to go.


text:
Q: Beginning storyboard in XAML in wp7 I have an application in windows phone 7 where I require to have images' opacity change from 0 to 1 gradually on loading the application. I thought of using storyboard but I have to begin each and every storyboard on page loaded.
This becomes a problem whenever I have many storyboards. How can i indicate it in the XAML itself that I need to begin the storyboard? Also How can I bind multiple items to a common storyboard?


text:
Q: How do I get custom variable, billing address, shipping address in Invoice using SOAP API of magento1.7? I am using SOAP API in Magento 1.7
Its easy pretty to fetch Invoice details using invoice id.
But it provide billing_address_id and shipping_address_id only
How I can fetch corresponding addresses using above ids using SOAP API?
And one more question
I have tracking number from vendor saved in database associated to invoice id
How I can access this tracking number from SOAP API?

A: When retrieving an invoice you already receive the id of the order in the member parent_id. Do an other call to the server and retrieve the order details using salesOrderInfo.
On the order object you should have the billing and shipping addresses as objects with type salesOrderAddressEntity.
For tracking numbers call the method salesOrderShipmentList and get a list of all order shipments (again using as parameter the parent_id field of the invoice). The result should be an array with objects of type salesOrderShipmentEntity. Each of these objects should have a member called tracks that is an array with elements with type salesOrderShipmentTrackEntity that contain the tracking number in the member number.


text:
Q: Why would Evaluate[] in Plot give me warning about precision? I have a code:-
Plot[Evaluate@PDF[NormalDistribution[1.6, 0.2], x], {x, -6, 6}]

And then I got the warning: General::munfl: Exp[-721.953] is too small to represent as a normalized machine number; precision may be lost. However, if I removed Evaluate, the warning disappears. Why would that? Would that matter?
I need to keep the Evaluate, since I am drawing various distributions.
Thanks in advance!

A: When you use Evaluate, the PDF evaluates to an exponential:
pdf = PDF[NormalDistribution[1.6, .2], x]

1.99471 E^(-12.5 (-1.6 + x)^2)

When you evaluate this object with a large enough number x (on the order of 10), the resulting object is too small to represent as a machine number:
pdf /. x -> 10

General::munfl: Exp[-882.] is too small to represent as a normalized machine number; precision may be lost.
0.

Let's check. The smallest machine number is:
$MinMachineNumber

2.22507*10^-308

If we convert the pdf expression to one using extended precision numbers:
epdf = SetPrecision[pdf, 20];

and then evaluate epdf at 10:
epdf /. x->10

1.7870924971057366*10^-383

We see that the result is much smaller than the smallest possible machine number. This is why evaluating pdf at 10 produces an error message and Mathematica returns 0.
Now, when you remove the Evaluate, then Plot only evaluates the PDF object when it is numerical, and this doesn't produce any messages:
PDF[NormalDistribution[1.6, .2], 10]

1.787092497106*10^-383

Of course, the above output is not a machine number:
Precision @ PDF[NormalDistribution[1.6, .2], 10]

13.0095

If you are multiplying extremely small numbers with extremely large numbers, then setting the small numbers to zero can be an issue. In that case, it makes sense to work with extended precision numbers instead.


text:
Q: How i can get value from radio button form in php? Question.php
<?php
include 'Pre-function.php'

?>
<!DOCTYPE html>

   <link rel="stylesheet" href="CSS/Start.css">

    Home
    News
    Contact

        <form action="Answer.php" method="post">
            <?php getQuestion($conn);  ?>
            <input type="submit" name="Submit" value="Submit">
        </form>

Its html page to ask question
Pre-function.php
<?php
include 'conn.php';

function getQuestion($conn) {

$query = "SELECT * FROM question ";
$result = mysqli_query($conn, $query);

if($result){

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
       $question_id = $row['question_id'];
       $question_body = $row['question_body'];
       $option_a = $row['option_a'];
       $option_b = $row['option_b'];

        echo '

'.$question_body.'

        Yes
            <input type="radio" name="'.$question_id.'" value="Yes">
            <input type="hidden" name="option_a" value="'.$option_a.'">

        No
            <input type="radio" name="'.$question_id.'" value="No">
            <input type="hidden" name="option_b" value="'.$option_b.'">

        <input type="hidden" name="submitted" value="submitted">
';

        }

}

}

?>

Basically this form asked question whether yes or no using radio button. $option_a == 'Yes' and $option_b == 'No'. The question is like this "Are you have fever ?". So when i submit the value did not pass to the 'Answer.php' page.
'Answer.php' page.
<?php
include 'conn.php';

if(isset($_POST['Submit']) && !empty($_POST['Submit'])){

      echo $_POST['option_a'];
      echo 'succeed';
}
else{

     echo 'no data';
}

?>

In this page have error undefined_index value but still echo succeed.

A: Your HTML code should look like the following:
<input type="radio" name="whatevername" value="Yes">
<input type="hidden" name="whatevername" value="No">

You can use PHP to insert whatever values you want but you need the radio button name to be the same.
Then if you want to echo that in PHP you'd use:
echo $_POST['whatevername']; //same name you used in the form

A: You are passing value as name for radio buttons
 name="'.$option_a.'"

This will result you in name ="Yes"
And you are trying to fetch echo $_POST['option_a']; where option_a is not defined.
Try this
<input type="radio" name="'.$question_id.'" value="Yes">
<input type="hidden" name="option_a" value="'.$option_a.'">

Same for other radio button

A:     Try this one :

    <?php
include 'conn.php';

function getQuestion($conn) {

$query = "SELECT * FROM question ";
$result = mysqli_query($conn, $query);

if($result){
    echo '
';
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
        $question_id = $row['question_id'];
        $question_body = $row['question_body'];
        $option_a = $row['option_a'];
        $option_b = $row['option_b'];

        echo '

'.$question_body.'

        <form action="Answer.php" method="post">
            Yes
            <input type="radio" name="radioQuestions[]" value="'.$question_id.'-'.$option_a.'">

            No
            <input type="radio" name="radioQuestions[]" value="'.$question_id.'-'.$option_b.'">

            <input type="hidden" name="submitted" value="submitted">
';

    }
    echo'
        <input type="submit" name="Submit" value="Submit">
        </form>

';
}

}

?>

<?php
include 'conn.php';

if(isset($_POST['submitted']) && !empty($_POST['submitted'])){
     $questionAndOptions = $_POST['radioQuestions'];

     foreach ($questionAndOptions as $questionAndOption) {
        $arrQuestionAndOption =  explode("-", $questionAndOption);
         echo $arrQuestionAndOption[0]; //question
         echo $arrQuestionAndOption[1]; //option
     }

      echo 'succeed';
}
else{

     echo 'no data';
}

?>


text: Q: What is the source of origin of the creation of the Warehouse building in Warehouse 13? Where does the concept of the warehouse creation come from? Alexander started it, but where did the origin of its organic existence form? Warehouse 1? Warehouse 2 had the beginnings of sentience. Was it given life then, or in the beginning? And from what?


text:
Q: Unable to display a serialized image in PHP from MySQL table I've uploaded some images to a MySQL database table, using the 'serialize' function so I have the possibility to save multiple images to one location in the table. This function is working fine, however, this is now where I'm stuck as a newbie!!
I have my serialised value in my database table (shown below), and the image has been saved to my server.
a:1:{i:0;s:19:"1431013957.9861.JPG";}

This is as far as I can get. I want to display the image on the front end of the site. I can call the stored information from the table using the echo function to display the whole value as text. However, I don't need all this information, I only need part of the value - the file name... (1431013957.9861.JPG).
That way I can simply enter into some code like this to display the image:
<img src="img/<?php echo $config->photo_a ?>"/>

Is there a way to unserialize or select part to my value when I echo it so I can easily display the image saved? I've tried quite a few things and looked everywhere for an answer but can't find the solution.
Thank you for you help in advance!!


text:
Q: PHP Why does the DateTime diff function always return zero? I have the following code that tries to calculate hours worked. I'm having a bit of an issue in that hours and minutes always returns zero. My best guess is it has something to do with the new DateTime, but I have no idea how to remedy this.
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'functions.php';

$error_msg = "";

sec_session_start();

//Get Username from session id
$username =  htmlentities($_SESSION['username']);

//get time date stamp
date_default_timezone_set('America/Chicago'); //set default timezone, just to be sure

//GET Last Clockin from timesheet table
$result = $mysqli->query("SELECT lastclockin FROM timesheet WHERE username = '$username'");
$number_of_rows =  $result->num_rows;

while ($row = mysqli_fetch_assoc($result)) {
        $lastclockin = $row["lastclockin"];
    }
    echo $lastclockin;
    echo "
";

    $now = new DateTime();

    $diff = $now->diff(new DateTime($lastclockin));

$hours = $diff->h;
$minutes = $diff->m;
$hours = $hours + ($diff->days*24);

echo $now->format('Y-m-d H:i:s');
echo "
";

echo $hours;
echo "
";
echo $minutes;
echo "
";
?>

The results are as follows:
2014-09-11 13:02:15
2014-09-11 13:47:34
0
0

A: There is zero hours difference between the two times so that makes sense. You'll need to test using two times that are further apart to see a value greater than zero here.
Your minutes are incorrect because m is the month identifier. i is for minutes.
$minutes = $diff->i;


text:
Q: Table command in Latex I have this table
I want writ it in latex, Unfortunately I do not know how to do, please help me
Thanks

A: Here's some code to get you started. Note that because the first table mostly consists of math material, I suggest using an array environment instead of a tabular environment. I also recommend aligning the numbers in the second table on their decimal markers; one way to do so is to load the siunitx package and use its S column type. The formatting of the captions is handled most easily by loading the caption package.

\documentclass{article}
\usepackage{amsmath,array,booktabs,siunitx,caption}
\captionsetup{labelsep=period,
              justification=raggedright,
              singlelinecheck=false,
              skip=0pt}
\usepackage[margin=1in]{geometry} %choose margins appropriately
\newenvironment{smalltab}%
    {\begin{tabular}[t]{@{}>{\bfseries}c@{}}}%
    {\end{tabular}}
\newcommand\mysim{{\sim}}
\begin{document}
\begin{table}
\caption{Value and distribution of input parameters}
$
\begin{array}{@{} *{7}{c} @{}}
\toprule
\smash[b]{\begin{smalltab} Value \& \\ Distribution \\ \end{smalltab}}
& \multicolumn{6}{c@{}}{\textbf{Parameter}}\\
\cmidrule{2-7}
& n & w_{ij}^c & C_{ij}^c & f_k^q & \mathrm{cap}_{k}^q & t_{kl}^m \\
\midrule
& 30\#8 & p\mysim(20) & U\mysim(1,10) & U\mysim(1000,2000) & U\mysim(100,1000) & U\mysim(10,20)\\
\bottomrule
\end{array}
$
\end{table}

\begin{table}[ht!]
\caption{Comparison metrics for small-sized problems}
\begin{tabular}{@{} >{\bfseries}c *{6}{S[table-format=1.3]} @{}}
\toprule
Problem No. & \multicolumn{3}{c}{\bfseries Quality Metric (QM)}
& \multicolumn{3}{c@{}}{\bfseries Spacing Metric (SM)} \\
\cmidrule(lr){2-4} \cmidrule(l){5-7}
& {PAES} & {NSGA-II} & {MOPSA} & {PAES} & {NSGA-II} & {MOPSA} \\
\midrule
10\#3 & 0 & 0.115 & 0.695 & 0.545 & 0.657 & 0.741 \\
\vdots\\
30\#8 & 0 & 0 & 1 & 0.327 & 0.296 & 0.745 \\
\bottomrule
\end{tabular}
\end{table}
\end{document}


text:
Q: How do I enable Ebean Enhancement in Maven? I've been using Avaje.org ebean ORM layer for a while, but I don't understand how to enable the byte-code enhancement functionality described in the "Ebean v2.6.0 User Guide" with Maven.
I found a configuration example on the Avaje.org homepage, but it doesn't work. Neither does the demo Maven boilerplate on GitHub.
Help!

A: EBeans now has its own Maven Plugin, but I can't find any documentation online, so here is an example of how to use it:
<plugin>
    <groupId>org.avaje.ebeanorm</groupId>
    <artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
    <version>${ebean.version}</version>
    <executions>
        <execution>
            <id>main</id>
            <phase>process-classes</phase>
            <goals>
                <goal>enhance</goal>
            </goals>
            <configuration>
                <packages>com.package1.**,com.package2.**</packages>
                <transformArgs>debug=1</transformArgs>
                <classSource>${project.build.outputDirectory}</classSource>
                <classDestination>${project.build.outputDirectory}</classDestination>
            </configuration>
        </execution>
    </executions>
</plugin>

With Eclipse
If you use Eclipse, you will want to make sure it runs the plugin when needed, like this:
<build>
    <plugins>
        <!-- plugins here -->
    </plugins>
    <pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.avaje.ebeanorm</groupId>
                                    <artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
                                    <versionRange>[3.3.2,)</versionRange>
                                    <goals>
                                        <goal>enhance</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <execute>
                                        <runOnConfiguration>true</runOnConfiguration>
                                        <runOnIncremental>true</runOnIncremental>
                                    </execute>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

A: OBSOLETE ANSWER
This answer is for a very old version of EBeans, please disregard it.
Original Content
The example on the Avaje page has some mistakes.

*

*The  tag is incorrect: 'process-ebean-enhancement' is not a
Maven lifecycle, so the plugin in the example configuration won't
run correctly. The correct phase is 'process-classes'.

*The 'classSource' parameter is incorrect. As configured, the ebean plugin would enhance @Entity clases in your test code, rather than you production code. The correct value is '${project.build.outputDirectory}'.

*Make sure to update the package-space for your project. This is 'com.mycompany.**' in the example below.

The complete config should be:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>process-ebean-enhancement</id>
                    <phase>process-classes</phase>
                    <configuration>
                        <tasks>
                            <property name="compile_classpath" refid="maven.compile.classpath" />
                            <echo
                                message="Ebean enhancing test classes debug level -----------------------------------" />
                            <echo message="Classpath: ${compile_classpath}" />
                            <taskdef name="ebeanEnhance" classname="com.avaje.ebean.enhance.ant.AntEnhanceTask"
                                classpath="${compile_classpath}" />
                            <ebeanEnhance classSource="${project.build.outputDirectory}"
                                packages="com.mycompany.**" transformArgs="debug=1" />
                        </tasks>
                        <encoding>UTF-8</encoding>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

This will enhance all of the @Entity classes in the "src/main/java/com/mycompany" and below.
You can improve execution time by being more restrictive on the packages to examine.
Also, you may need to duplicate this config if you do need to enhance test classes. In that case, use the 'proces-test-classes' phase for a second  block.

A: JBCP's answer is for old ebean version (org.avaje.ebeanorm). For newer version (io.ebean) you need to change to ebean-maven-plugin.
<plugin>
    <groupId>io.ebean</groupId>
    <artifactId>ebean-maven-plugin</artifactId>
    <version>${ebean.version}</version>
    <executions>
        <execution>
            <id>main</id>
            <phase>process-classes</phase>
            <goals>
                <goal>enhance</goal>
            </goals>
            <configuration>
                <packages>com.package1.**,com.package2.**</packages>
                <transformArgs>debug=1</transformArgs>
                <classSource>${project.build.outputDirectory}</classSource>
                <classDestination>${project.build.outputDirectory}</classDestination>
            </configuration>
        </execution>
    </executions>
</plugin>

Note: ebean plugin version should be the same as ebean version.
Reference: Maven Repo, Github


text:
Q: name 'pythoncom' is not defined I had read this and installed pywin32 from this place, both Python27 and Python36.
However I got the error. I don't know why. I tried both Python27 and Python36. The errors are identical.

To be more detailed, I put my sample code below:
 import win32com.client
 from win32com.client import constants, DispatchBaseClass, CastTo, VARIANT
 import sys

 mode = win32com.client.VARIANT(pythoncom.VT_BSTR | pythoncom.VT_BYREF, "")

Result after delete the old Python, reinstalled both ActivePython 3.6 and pywin32com package. Screen shot like below:

Is there any workaround which needn't use the pythoncom?

A: Install pywin32.
Copy the files from pywin32_system32 path to win32


text:
Q: Resize Image Maps on Fluid Carousel Images
*

*I have a carousel with fluid images and image maps.

*With David Bradshaw's image-map-resizer code, the 1st slide's image map always nicely adjusts to the screen size.

*Other slides' image maps only resize if I first have the browser screen maximized & then make the screen smaller. If I load the page on a non-maximized browser screen, the image maps (besides the 1st one) don't adjust.

What can I tweak so that the images maps for all slides adjust based on screen size?
See CodePen <---

/*! Image Map Resizer (imageMapResizer.min.js ) - v1.0.10 - 2019-04-10
 *  Desc: Resize HTML imageMap to scaled image.
 *  Copyright: (c) 2019 David J. Bradshaw - dave@bradshaw.net
 *  License: MIT
 */
! function() {
  "use strict";

  function r() {
    function e() {
      var r = {
          width: u.width / u.naturalWidth,
          height: u.height / u.naturalHeight
        },
        a = {
          width: parseInt(window.getComputedStyle(u, null).getPropertyValue("padding-left"), 10),
          height: parseInt(window.getComputedStyle(u, null).getPropertyValue("padding-top"), 10)
        };
      i.forEach(function(e, t) {
        var n = 0;
        o[t].coords = e.split(",").map(function(e) {
          var t = 1 == (n = 1 - n) ? "width" : "height";
          return a[t] + Math.floor(Number(e) * r[t])
        }).join(",")
      })
    }

    function t(e) {
      return e.coords.replace(/ *, */g, ",").replace(/ +/g, ",")
    }

    function n() {
      clearTimeout(d), d = setTimeout(e, 250)
    }

    function r(e) {
      return document.querySelector('img[usemap="' + e + '"]')
    }
    var a = this,
      o = null,
      i = null,
      u = null,
      d = null;
    "function" != typeof a._resize ? (o = a.getElementsByTagName("area"),
      i = Array.prototype.map.call(o, t),
      u = r("#" + a.name) || r(a.name),
      a._resize = e,
      u.addEventListener("load", e, !1),
      window.addEventListener("focus", e, !1),
      window.addEventListener("resize", n, !1),
      window.addEventListener("readystatechange", e, !1),
      document.addEventListener("fullscreenchange", e, !1),
      u.width === u.naturalWidth && u.height === u.naturalHeight || e()) : a._resize()
  }

  function e() {
    function t(e) {
      e && (! function(e) {
        if (!e.tagName) throw new TypeError("Object is not a valid DOM element");
        if ("MAP" !== e.tagName.toUpperCase()) throw new TypeError("Expected <MAP> tag, found <" + e.tagName + ">.")
      }(e), r.call(e), n.push(e))
    }
    var n;
    return function(e) {
      switch (n = [], typeof e) {
        case "undefined":
        case "string":
          Array.prototype.forEach.call(document.querySelectorAll(e || "map"), t);
          break;
        case "object":
          t(e);
          break;
        default:
          throw new TypeError("Unexpected data type (" + typeof e + ").")
      }
      return n
    }
  }
  "function" == typeof define && define.amd ? define([], e) : "object" == typeof module && "object" == typeof module.exports ? module.exports = e() : window
    .imageMapResize = e(), "jQuery" in window && (window.jQuery.fn.imageMapResize = function() {
      return this.filter("map").each(r).end()
    })
}();
//# sourceMappingURL=imageMapResizer.map

See CodePen <---


text:
Q: Get and Set Value in drop downdown in MVC4 I am a beginer ...I don't know how to use dropdown in MVC this....I have used it like this
In ItemMaster.cshtml
 @Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)

In Controller.cs
public ActionResult ItemMaster(Item model)
{
 ObservableCollection<Item> ItemList = new ObservableCollection<Item>();
 Item Item = new Models.Item();
 ItemList = Item.GetItemList();

 Item Product = new Item();
 DataTable dtProduct = new DataTable();
 dtProduct = Item.GetProductList();

 IList<Item> MyList = new List<Item>();
 foreach (DataRow mydataRow in dtProduct.Rows)
 {
     MyList.Add(new Item()
     {
         Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
         Product_Name = mydataRow["Name"].ToString().Trim()
     });
 }
 var ProductName = new SelectList(MyList, "Id", "Product_Name");
 ViewData["ProductName"] = ProductName;

     return View(ItemList);
}

I am using Item list to fill grid view.... And I am using view data to fill drop down list....It is working fine.... I don't know how to get selected value when Button is clicked.

A: Try this,
 @Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)

<input type="button" id="btnasd"  value="Click"/>

Script
<script type="text/javascript">
    $(document).ready(function () {

        $("#btnasd").click(function () {
            var Id = $("#ProductName").val();
             $.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: "Post",
            data: { ProductNameId: Id },
            success: function (result) {

                $("#mygrid").html('');
                $("#mygrid").append(result.Data);
            }
        });
        });
});
</script>

A: Do following(for onchange event of DropDownList):
@Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
 "-Select Product-", new { onchange = "doFunction();" })

javascript:
<script type="text/javascript">
$(document).ready(function () {
        doFunction();
    });
function doFunction() {
   var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
   if (PassVal != '') {
           //Do Ajax operations to load data in GridView(On Same Page).
      $.ajax({
        url: '<CONTROLLER/ACTIONANME>',  //Specify Actionname in controller from which you will get data.
        type: "POST",
        data: {
            ProductName: PassVal
        },
        dataType: "html",
        success: function (data) {
          $("#GridView").empty(data);  //empty gridview
          $("#GridView").html(data); //Load data to gridview
        },
        error: function () {
          alert("No Records Found");
         }
      });
   }
}
</script>

Or On button click
@Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
     "-Select Product-")
<input type="button" id="btnSubmit"  value="Submit"/>

script:
    $('#btnSubmit').click(function(){
     var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
       if (PassVal != '') {
               //Do Ajax operations to load data in GridView(On Same Page).
          $.ajax({
            url: '<CONTROLLER/ACTIONANME>',  //Specify Actionname in controller from which you will get data.
            type: "POST",
            data: {
                ProductName: PassVal
            },
            dataType: "html",
            success: function (data) {
              $("#GridView").empty(data);  //empty gridview
              $("#GridView").html(data); //Load data to gridview
            },
            error: function () {
              alert("No Records Found");
             }
          });
       }
});

Ask me if you have any query.
Note: You can also use DropDownListFor for model binded dropdown.


text:
Q: Getting state updated very late and console error value was evaluated just now. How to resolve I am totally confused about what's happening here. I am setting the state in React but it's updating very late. Here is the function:
fetchTimesheets() {
    const userId = cryptInfo.decrypt(localStorage.getItem('user_id'))
    var userArray = []
    var timeSheets = []
    fetchManagerProject(userId)
      .then(async (res) => {
        const projects = await res.json()
        projects.forEach(project => {
          project.teammember && project.teammember.forEach(member => {
            if (userArray.indexOf(member.user) === -1) {
              userArray.push(member.user)
              fetchUserTimelogs(member.user)
                .then(async (res) => {
                  const timesheet = await res.json()
                  if (timesheet)
                    timesheet.forEach(sheet => {
                      timeSheets.push(sheet)
                    });
                })
            }
          })
        })

        this.setState({
          timesheets: timeSheets
        })
      })

  }

I am calling this function on componentDidMount method
componentDidMount() {
    this.fetchTimesheets()
}

But I am getting that my value is evaluated just now and state is not updated. I have seen many questions related to this but didn't get a good solution.

A: Have you checked to see whether it is the requests that you are making that are taking a long time or whether it's the setState itself?
Your fetchTimesheets contains multiple http requests on a loop (forEach) which could take some time to complete depending on the request. Because the forEach loop is a blocking function it means that your setState function will not be called until the forEach functions execution has completed.
To speed this up, you could consider setting the timesheet in-state each time you get a new timesheet. For example
fetchManagerProject(userId)
    .then(async (res) => {
    const projects = await res.json()
    projects.forEach(project => {
        project.teammember && project.teammember.forEach(member => {
        if (userArray.indexOf(member.user) === -1) {
            userArray.push(member.user)
            fetchUserTimelogs(member.user)
            .then(async (res) => {
                const timesheet = await res.json()
                if (timesheet)
                timesheet.forEach(sheet => {
                    timeSheets.push(sheet)
                });
                const newTimesheet = this.state.timesheets.concat(timesheet);
                this.setState({timesheets: newTimesheet});
            })
        }
        })
    })
})

A: I believe that the function fetchTimesheets() is acting synchronously, you can change the function definition to be async and then call the method to be await fetchTimesheets().


text:
Q: How detect platform send to firebase I have a web, an android, and an iPhone app using the same firebase database how I can know which of them send to firebase
there is a solution "send type platform" are there another solution?


text:
Q: PHP preg_replace \ Really simple question: how can I preg_replace the backslash character?

A: You need to escape the backslash: \\
From the manual on preg_replace:

To use backslash in replacement, it must be doubled ("\\\\" PHP string).

Alternatively, use preg_quote to prepare a string for a preg_* operation.

A: You could try
$a = "\\\\";
$a = preg_replace('/\\\\/','/',$a);

Output:
'//'

A: This code works for me
  $text = "replace \ backslash";
  $rep = "";
  $replace_text = preg_replace( '/\\\\{1}/',$rep,$text);
  echo $replace_text;

Output :
replace backslash

A: Yes, but you need to escape it. When using it in the regexp use \\ to use it in the replacement, use \\\\ (that will turn into \\ that will be interpreted as a single backslash).

A: Escape \ with \: \\
preg_replace('/\\/', 'REMOVED BACKSLASH', 'sometest\othertest');

A: Use it twice eg \\

A: If you want to remove backslash from text and don't want to see it anymore. then use this php function. But if it is a double backslash it will only remove one. stripslashes ($string)


text:
Q: Keyboard is working but not typing in any app including terminal I tested the OS before installing on my laptop (Lenovo IdealPad L340 Gaming) on a USB stick. Everything seems to work fine and I managed to connect to my home WiFi network and typed the password.
However, after opening Firefox I noticed that it doesn't write or even press Enter, even in other apps and notepads and terminal have the same issue, the shortcuts however, like Alt+Tab, are working fine - even the function keys like volume up/down.
I tried to open the on screen keyboard, but it didn't show up. And I tried to.

A: I found a solution, but i don't understand how it worked yet...
I have re flashed Ubuntu to the USB stick as GPT this time not as MBR. Now I'm typing this on Ubuntu :) i hope this helps anyone in the future


text:
Q: How do you use vertify_pass to login to a system? I have a registration system code with a table of (user_id, user_name user_email, user_pass).
I am trying to login to this system by checking an email and password.
The code is not giving any errors, but return, under all circumstances, that the password does not match.
<?php

class Login
 {
   private $db;
   private $userEmail;
   private $userPass;

  function __construct($db)
  {
    $this->db = $db;
  }

  function vertifyPass($userEmail, $userPass)
  {

    $sqlStatement = "SELECT user_pass FROM user WHERE user_email = :userEmail";
    $preparedStatement = $this->db->prepare($sqlStatement);
    $preparedStatement->bindParam(':userEmail', $userEmail);
    if($preparedStatement->execute())
    {
      $userData = $preparedStatement->fetchObject();
      $userData = $userData->user_pass;
      if(password_verify($userPass, $userData))
      {
        session_start();
        $_SESSION['user_email'] = $userEmail;
        header('Location: /profile.php');
      }
      else
      {
        echo "your username and password combinations was incorrect.";

      }
    }

}
}

?>


text:
Q: PHP 7 version is not working in Ubuntu 12.04 I have recently updated by php. My php -v command show following result:
PHP 7.0.6-6+donate.sury.org~precise+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

But still phpinfo() function shows php 5.3.10 version
What should I do to start using it.

A: You need to install SAPI for your webserver, f.e. either libapache2-mod-php for Apache2 or php-fpm for NGINX.  CLI version of PHP could be different from web SAPI.
For Ubuntu 12.04 LTS you need to also add ppa:ondrej/apache2 if you intend to use Apache 2.x PHP module:
sudo add-apt-repository ppa:ondrej/apache2
sudo apt-get update
sudo apt-get install libapache2-mod-php

If you had apache2 2.2.x installed previously, you need to remove it with:
apt-get purge 'apache2*'

This will remove all apache2 configuration files, so don't forget to backup your configuration (if you made any changes).


text:
Q: Total count filtered by parameters - bash Is there a way to get the total number of lines that filters by certain parameters? For example, I have a log file that contains:
COMPLETED: location: DEN brand: A
COMPLETED: location: LHR brand: A
COMPLETED: location: EWR brand: C

COMPLETED: location: DEN brand: A
COMPLETED: location: LHR brand: B
COMPLETED: location: JFK brand: C

Is there a way to write the grep command that can return the total number of lines for each location and brand. For example, the command executed would return
DEN    A     3
LHR    A     1
LHR    B     1

This would have to be dynamic since the locations can be different. So we can't just do something like grep 'location: DEN' | grep 'brand: A' | wc -l >> file.log
Any suggestions would be helpful. Thanks.

A: You can do this also with Bash commands:
cat input_file | sed '/^$/d' | sort | uniq -c | sed 's/^ \+//' | cut -d' ' -f1,4,6

in this situation output will be as follow:
2 DEN A
1 EWR C
1 JFK C
1 LHR A
1 LHR B

A: 1st solution: With GNU awk please try following, written and tested with shown samples. Simple explanation would be, setting RS(record separator) to match DEN brand: A kind of values in each line. Then using split function to split RS values into arr1 array then creating final array which has values in it to be printed as per shown samples.
awk -v RS='[a-zA-Z]+[[:space:]]+brand:[[:space:]]+[a-zA-Z]+' '
RT{
  split(RT,arr1," brand: ")
  arr[arr1[1] OFS arr1[2]]++
}
END{
  for(key in arr){
    print key,arr[key]
  }
}
' Input_file

2nd solution: Using match function of awk here. Simple explanation would be using match to match DEN brand: A values in line here, then splitting matched values into arr. Finally cnt array which has index as 1st and 2nd value of arr. in END block of awk program printing all values of array ant there.
awk '
match($0,/[a-zA-Z]+ brand: [a-zA-Z]+/){
  split(substr($0,RSTART,RLENGTH),arr," brand: ")
  cnt[arr[1] OFS arr[2]]++
}
END{
  for(key in cnt){
    print key,cnt[key]
  }
}
'  Input_file


text:
Q: Days difference by counting midnights in swift I have an objective-c exsample how to count a days diference as number of midnites, published in Apple's "Date and Time Programming Guide". Is it posible to do the same in Swift?
    @implementation NSCalendar (MySpecialCalculations)
-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
     NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit
          inUnit: NSEraCalendarUnit forDate:startDate];
     NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit
          inUnit: NSEraCalendarUnit forDate:endDate];
     return endDay-startDay;
}
@end

A: Based on basic Objective-C to Swift transformation documentation:
extension NSCalendar {
  public func daysApart (sd: NSDate, ed: NSDate) -> Int {
    return ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: ed) -
           ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: sd)
  }
}

A: I would do something like this:
extension NSCalendar {
    func daysWithinEraFromDate(startDate: NSDate, toDate endDate: NSDate) -> NSInteger {
        let startDay = self.ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: startDate)
        let endDay = self.ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: endDate)
        return endDay - startDay
    }

}


text:
Q: VLC Player wont display sub or srt subtitles I cant have VLC display .sub or .srt subtitles. Neither by naming video and subtitles files the same nor loading the subtitles manually will work. Only if I convert them into ASS or SSA they display with no problem. Why is it that? How can I fix this?
Thank you.


text:
Q: Keep socket opened on Android App I'm developing an App that, for example, It has 4 activities (A,B,C,D). You can navigate from A -> B -> C -> D
So, in the Activity A, I open a socket connection and I want keep it opened when I go to Activity B, then C, then back to B, then C or whatever.
I think that I can open the socket in Application context or a "Domain" context (with a Singleton) that my variale socket is "global", it isn't the problem.
The problem is that I want disconnet the socket when te user leave the app (Home button or Back button in Activity A)
How I can keep the socket opened always but disconnect when the user leave the app. I don't want to open the socket in every onCreate/onStart and close it in every onStop/onDestroy.
Thanks for your responses.

A: I think what you want is a bound Service. You can bind in onStart and unbind in onStop. Your Service can maintain the socket connection.
http://developer.android.com/guide/components/bound-services.html


text:
Q: Jquery set radio button checked, using id and class selectors Is it possible to set a radio button to checked using jquery - by a class and an id?
For example:
$('input:radio[class=test1 id=test2]).attr('checked', true);

I only seem to be able to set it by id OR class but not by both.

A:
"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.


text:
Q: Programa complicado Estou já a um tempo tentando fazer um programa que faça o seguinte: Peça a um usuário para digitar uma quantidade de números e depois para digitar a quantidade de números que ele deseja ter na combinação e depois o programa imprima as combinações  e as quantidades de combinações

A: Esses números podem se repetir?
se sim, o número de combinações e N! (onde N é a quantidade de números que ele quer), caso não se repitam fica N * (N-1) * (N-2) * ... * 1!
 Pelo que entendi você que saber quantas vezes um numero X se repete dentro do intervalo de 0 até N. Acho que você faz (N!)/(N-X)!


text:
Q: Need to ID a chart software Hello im looking for a nice chart software and I remembered one that i really liked the look of.
http://imgur.com/fsXGa
You can see it in that picture but I've searched and I cannot find anything like it. I'm guessing that it at least is in Javascript since it's displayed dynamically Anyone know what it is? Also if you know what software did the bars to come with it.
Thanks in advance for any help!

A: Not exactly the same but FusionCharts can do similar..


text:
Q: Operation not allowed when the object is closed in VBA I am new to this site and also to VBA,
some how I managed to write VBA, but got above error. Please advise me any changes in my code. Thanks
Option Explicit
Const ConStrSql As String = "----"

Sub CopyDataFromDatabase()

Dim DataConn As ADODB.Connection
Dim StaffData As ADODB.Recordset
Dim DataFiels As ADODB.Field

Set DataConn = New ADODB.Connection
Set StaffData = New ADODB.Recordset

DataConn.ConnectionString = ConStrSql
DataConn.Open

On Error GoTo CloseConnection

With StaffData
.ActiveConnection = DataConn
.Source = "select ---"
.LockType = adLockReadOnly
.CursorType = adOpenKeyset

End With

On Error GoTo CloseRecordset

Worksheets.Add

For Each DataFiels In StaffData.Fields
ActiveCell.Value = DataFiels.Name
ActiveCell.Offset(0, 1).Select
Next DataFiels

Range("A1").Select
Range("A2").CopyFromRecordset StaffData
Range("A1").CurrentRegion.EntireColumn.AutoFit

CloseRecordset:
StaffData.Close

CloseConnection:
DataConn.Close

End Sub

when I remove
CloseRecordset:
StaffData.Close
I got columns listed in excel, but not data
Please any advise. Thanks

A: Your code defines Recordset but doesn't open it. Adding:
StaffData.Open

before:
Range("A2").CopyFromRecordset StaffData

should solve the problem.


text:
Q: ModuleNotFoundError: No module named 'sklearn.metrics._pairwise_distances_reduction' This is the error i'm getting for importing metrics from sklearn package
Traceback (most recent call last):
  File "c:\Users\Scorpio\Desktop\lab\ml_lab\logistic_reg.py", line 2, in <module>
    from sklearn import metrics
  File "C:\Users\Scorpio\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\metrics\__init__.py", line 41, in <module>
    from . import cluster
  File "C:\Users\Scorpio\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\metrics\cluster\__init__.py", line 22, in <module>
    from ._unsupervised import silhouette_samples
  File "C:\Users\Scorpio\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\metrics\cluster\_unsupervised.py", line 16, in <module>
    from ..pairwise import pairwise_distances_chunked
  File "C:\Users\Scorpio\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\metrics\pairwise.py", line 33, in <module>
    from ._pairwise_distances_reduction import PairwiseDistancesArgKmin
ModuleNotFoundError: No module named 'sklearn.metrics._pairwise_distances_reduction'

I tried

*

*uninstalling and reinstalling scikit-learn related packages like scipy,numpy...

*also in metrics folder i found the file 'sklearn.metrics._pairwise_distances_reduction.cp310-win_amd64 - Copy.pyd' ...is there something wrong cause when i installed sklearn i got the following warning...is this related?

DEPRECATION: sklearn is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559

A: I actually dunno the exact reason, but my problem's solved just with updating python(which may probably has nothing to do with this though) and just changing the order in which i imported the modules in the program(i.e., pd,np...then sklearn metrics module)


text:
Q: Access native mongoDB collection in Meteor I am using this ShareJS package in my Meteor application. ShareJS uses the collections docs and ops. How can I access these collections from the server?
Do I have to define them as collections as well?

A: You can use MongoInternals. But make sure to wrap it in a Future for it to behave correctly. I like the following IIFE pattern the most:
var connection = MongoInternals.defaultRemoteCollectionDriver().mongo;

var searchResults = (function(collectionName, query) {

    var future = new Future();

    connection._getCollection(collectionName)
      .find(query)
      .toArray(function(error, results) {
        if(error) future.throw(error);
        else future.return(results || []);
      });

    return future.wait();

})(options);


text:
Q: stereo-aware composite manager for Nvidia 3d vision Recently Nvidia released beta (337.12) drivers for NVIDIA graphics card. 3D Stereo with the composite extension on Quadro cards has been released in this driver. I am using compiz in ubuntu 12.04 which is not stereo-aware. What are the available composite managers that are stereo-aware?

A: This is what I got from emailing Andy Ritger of Nvidia. It seems Owen Taylor of Red Hat is updating gnome/mutter to be stereo-aware.
https://git.gnome.org/browse/clutter/log/?h=wip/quadbuffer-stereo
https://git.gnome.org/browse/mutter/log/?h=wip/quadbuffer-stereo

"    https://git.gnome.org/browse/cogl/log/?h=wip/quadbuffer-stereo"
"    https://git.gnome.org/browse/gnome-shell/log/?h=wip/quadbuffer-stereo"
BR


text:
Q: Search elements object with specific key value in firebase database I am trying to search with specific value with of userkey in firebase database but i am getting below issues.
I want to fetch like if i pass user key 11112 then two records will come when i pass 11113 then one record will come.

Even though I have tried with below code but getting error.
firebase script :-
 <script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.15/firebase.js'></script>

Code:
var ref = new Firebase('fire-base-url');
ref.orderBy("userkey").equalTo("11112").once("value", function(snapshot) {
  console.log(snapshot.key);
});

Console Error:
Uncaught TypeError: ref.orderBy is not a function

A: There is two problems with your code.

*

*As @theblindprophet already mentioned, you should be using orderByChild instead of orderBy.

*You are using the old firebase SDK. It won't work with applications created in the new firebase console.
Please make sure to use the new 3.1 firebase sdk with
<script type='text/javascript' src='https://www.gstatic.com/firebasejs/3.1.0/firebase.js'></script>

Then you should initialize your app using
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    storageBucket: "",
  };
  firebase.initializeApp(config);

You will be able to get your config details by going to the console, clicking in your application name and pressing Add Firebase to your Web app.
Then to get your ref object you will need the code bellow.
var ref = firebase.database().ref();
Take a look in this jsFiddle to see a full working example.

A: Your error:

Uncaught TypeError: ref.orderBy is not a function

is telling it can't find the function orderBy and that is because it doesn't exist.
You are looking for orderByChild.
var ref = new Firebase('fire-base-url');
ref.orderByChild("userkey").equalTo("11112").once("value", function(snapshot) {
    console.log(snapshot.key);
});

Reference: orderByChild and equalTo

A: Grab a snapshot of the uid values.  Then compare userkey with the search parameter you pass in.
var rootRef = new Firebase('fire-base-url');
var userRef = rootRef.child(user.uid);
userRef.on('value', function(snapshot){
  var myDbKey = snapshot.child("userkey");
  if (mySearchKey === myDbKey) {
    ...
  }
});


text:
Q: How to get the cursor position relative to ANY form of UIElement I'm trying to find the cursor position related to the red line in the image below.
I tried these topics:
Using atan2 to find angle between two vectors
And How to calculate the angle between a line and the horizontal axis? but using
    Math.Atan2
But there is a problem, P1 and P2 have not same values if I use these methods.
Is there any method to get any position of any points on a UIElement (e.g. Ellipse) using the red vector such as every point with the same angle (here P1 and P2) has the same value ?

A: Yes, and atan2 is perfectly the needed method. We can use cross- and dot-product to achieve result:
 bx = redline_end.x - center.x
 by = redline_end.y - center.y
 // here bx=0 and by=75
 px = p1.x - center.x
 py = p1.y - center.y
 angle = atan2(px * by - py * bx, px * bx + py * by)  //and similar for P2


text:
Q: AsyncTask: doInbackground() not called with executeOnExecutor and execute The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
  public void startBlat(String tosearch) {
    AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
        asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
    }
    else {
        asynctaskMovie.execute(tosearch);
    }

The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {

    JSONParser jsonParser = new JSONParser();
    private static final String SEARCH_URL = "http://www.omdbapi.com/?";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        movieArrayList = new ArrayList();
        Log.i(getActivity().getCallingPackage(), "onPreExecute");
    }

    @Override
    protected ArrayList<Movie> doInBackground(String... args) {
        Log.i(getActivity().getCallingPackage(),"doInBackground");

        HashMap<String, String> params = new HashMap<>();
        params.put("s", args[0]);
        params.put("r", "json");
        JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
        Log.i(getActivity().getCallingPackage(), json.toString());
        if (json != null) {
            try {
                if (json.getString("Response").equals("False")) {
                    return movieArrayList;
                }
            } catch (JSONException e) {
            }
            try {
                JSONArray jsonArray = json.getJSONArray("Search");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
                    if (!movieid.equals("null")) {
                        Movie movie = new Movie(movieid);
                        movieArrayList.add(movie);
                    }
                }
                jsonArray = new JSONArray();

                for (Movie movie : movieArrayList) {
                    params = new HashMap<>();
                    params.put("i", movie.getMovieid());
                    params.put("plot", "short");
                    params.put("r", "json");
                    JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
                    if (jsongetfullinfo != null) {
                        jsonArray.put(jsongetfullinfo);
                        Log.i("", jsongetfullinfo.toString());
                    }
                }
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jObject = jsonArray.getJSONObject(i);
                    movieArrayList.get(i).updateFromIMDB(jObject);
                }
                for (Movie movie : movieArrayList) {
                    movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
                }
                return movieArrayList;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return movieArrayList;
    }

    @Override
    protected void onPostExecute(ArrayList<Movie> movieArrayList) {
        Log.i("ronen", "list size: " + movieArrayList.size());

        if (movieArrayList.size() > 0) {
            listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
            listView.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
        }
    }

    private Bitmap LoadFromUrl(String theurl) {
        URL url = null;
        Bitmap bmp = null;
        try {
            url = new URL(theurl);
            bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
        }
        return bmp;
    }
}

I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.

A: Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!


text:
Q: Is a symplectic submanifold of a Kähler manifold Kähler? Is a symplectic submanifold of a Kähler manifold Kähler?
That is, if $X$ is a Kähler manifold with symplectic form $\omega$ and $i:Y\hookrightarrow X$ is an embedded submanifold such that $i^*\omega$ is symplectic, is $Y$ a Kähler submanifold of $X$?

A: No. In $\mathbf C^2$ with standard 2-form and complex structure, the real span of $U=\left(\begin{smallmatrix}1\\0\end{smallmatrix}\right)$ and $V=\left(\begin{smallmatrix}i\\1\end{smallmatrix}\right)$ is a symplectic but not complex (hence not Kähler) subspace, since
$$
\omega(U,V)=1,
\qquad
JU=\left(\begin{smallmatrix}i\\0\end{smallmatrix}\right)\notin\operatorname{span}_{\mathbf R}(U,V).
$$


text:
Q: Timer1 on low priority doesn't work I am using MPLAB XC8 compiler with PIC18F87J11 and I need to use the internal time1 for counting purposes. I noticed that my code works perfectly fine if the interrupt is set to high priority. However with low priority it doesn't work and I just can't figure it out.
Timer 1 Settings:
       // 1/1 prescalar
       T1CONbits.T1CKPS1 = 1;
       T1CONbits.T1CKPS0 = 1;

       // Use Internal Clock
       T1CONbits.TMR1CS = 0;

       // Timer1 overflow interrupt
       PIE1bits.TMR1IE = 1;

       // Enable Timer 1
       T1CONbits.TMR1ON = 1;

       INTCONbits.PEIE = 1; // Enable Perpherial Interrupt
       INTCONbits.GIE = 1; // Enable Global Interrupt

This works fine
void interrupt high_priority lowISR(void) {
    if (PIR1bits.TMR1IF == 1) {

         Printf("\r\n 1 second");

        PIR1bits.TMR1IF = 0;
    }
    }

However this doesn't and I don't know why.
void interrupt low_priority lowISR(void) {
    if (PIR1bits.TMR1IF == 1) {

         Printf("\r\n 1 second");

        PIR1bits.TMR1IF = 0;
    }

}

What did I miss?

A: Are you actually setting timer 1 to use the low-priority interrupt, and are you enabling interrupt priority control (by default, IIRC, all interrupts use high priority regardless of the individual-interrupt-source priority bit).

A: I was missing the following, adding them fixed my issue. I found them here.
IPR1bits.TMR1IP = 0;            // Timer 1 -> Low priority interrupt group
PIE1bits.TMR1IE = 1;            // Enable Timer1 interrupt

RCONbits.IPEN = 1;              // Enable interrupt system priority feature
INTCONbits.GIEH = 1;            // Enable high priority interrupts
INTCONbits.GIEL = 1;            // Enable low priority interrupts


text:
Q: Insufficient regional quota to satisfy request for resource: "CPUS" I have scripts that build up and tear down clusters on Google Cloud Platform. After running these scripts several times without error, I am now unable to run the script to build up a cluster, receiving the message 'Insufficient regional quota to satisfy request for resource: "CPUS". The request requires '4.0' and is short '12.0'. The regional quota is '8.0' with '-8.0' available.' I do not see in the console any residual VMs that may have not been deleted. Is there a place where I can see my quotas and the VMs that are debited against that quota? Or perhaps there is some other resource that is being identified as "CPUS" other then VM? The line in the script that causes the error is:
$ gcloud container clusters create "server-cluster" \
  --machine-type "n1-standard-1" \
  --scope "https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring" \
  --num-nodes "4" \
  --network $NETWORK \
  --enable-cloud-logging \
  --enable-cloud-monitoring

A: You can check the quota information for a project using the Quota page or through the following gcloud command:
 gcloud compute project-info describe --project myproject

More information can be found this link.


text:
Q: Bijection function from $(0,1]$ to $[1,\infty)$ Someone has an idea to Bijection function from $(0,1]$ to $[1,\infty)$ ?
I have thought about $f(x) = \frac{1}{x}$
Is this correct ?
Thanks.

A: Yes, it is correct. Show that $\frac{1}{x}$ is bijective:

*

*Showing that $\frac{1}{x}$ is injective: Let $x_1$ and $x_2$ be elements of $(0,1]$ such that $\frac{1}{x_1}=\frac{1}{x_2}$. Multiply $x_1 x_2$ on both sides, then we get $x_1=x_2$.

*Showing that $\frac{1}{x}$ is onto: Let $b=\frac{1}{\frac{1}{b}}$ be a element of $[1,\infty)$, then $0<\frac{1}{b}\le \frac{1}{1}=1$. Thus there exists $x^*\in (0,1]$ such that $\frac{1}{x^*}=b$, and so $\frac{1}{x}$ is onto.

A: Your answer is correct, but a proof is missing:

*

*$\forall{x_1},{x_2}\in(0,1]:{x_1}\neq{x_2}\implies\frac{1}{x_1}\neq\frac{1}{x_2}$

*$\forall{y}\in[1,\infty),\exists{x}\in(0,1]:y=\frac{1}{x}$ (given $y$, choose $x=\frac{1}{y}$)


text:
Q: Test action outputs length In my Logic App workflow, I'm trying to evaluate a condition for the previous action outputs array.
My condition expression
@less(action('Get_items').outputs.length, 1)

results in error

action 'Item_found' completed with status 'Failed' and code 'BadRequest'.

The same happens for
@greater(action('Get_items').outputs.length, 1)

as well as
@empty(action('Get_items').outputs)

What am I doing wrong here?

Background: The action('Get_items') is query retrieving items from a SPO site list using a Filter Query.
The action succeeds but the App Run Trace doesn't show any details on the outputs, in this case the expected empty array.

A: I managed to achieve the desired condition evaluation by correctly accessing the array the same way a for-each action does:
@empty(body('Get_items')['value'])

The documentation doesn't give a hint on this.

A: Accepted solution was not working for me for CDS entities, so I have solved it by using such condition:
@length(body('Get_items')['value'])

If I understand correctly it is converting array to string and empty array is converted to [], so you just have to check if the output of query is more than 2, then it means Get_Items is not empty.


text:
Q: How to run hello world in Maemo Do you know any other way to start app than using ./? I've just compiled one in c++ and i can't run it.

A: If you have the application in your user's home directory, then you'll need to call it via a path to it (ie, either ./program or /home/user/program).  Or, you can put it into a component of your path like /usr/bin or something (but that'll eat up precious space on your maemo device).  Or, put it in a new path location like ~user/bin and add that path to your default PATH by putting this in your ~user/profile:
export PATH=$HOME/bin:$PATH

Or, you could create a desktop file (which goes into /usr/share/applications/hildon/) which will allow you to execute the program from the normal list of programs in the application list.


text:
Q: Assigning a delegate to a background job for dropbox upload I am using Dropbox's SDK API V1 to upload files from my iOS app. The files aren't loading in real time, but rather I push them into a queue, and they get uploaded in the background.
I can't figure out for the life of me how to take DB RestClient delegate and make it respond to a completion/failure event that happens in the background. Is that even possible?
It seems (and I am new here), that delegates are meant to respond to live events on screen. Is that even an option to assign them to anything other than a UI element/view?
Update: Adding some description of what the code looks like.
There is a lot of code and it's hard for me to tell what's relevant for this question.
I am using PHPhotoLibrary.sharedPhotoLibrary().performChanges() which has a completion handler.
On success, I send an image upload request via dispatch_async(dispatch_get_main_queue()) method.
Dropbox API has this method dropboxRestClient.uploadFile(filename, toPath: pathOnDropbox, withParentRev: nil, fromPath: localFileUrl)
In all the examples that I've seen, dropboxRestClient.delegate was assigned to a UIViewController of some sort, and never to anything else.
So I am not sure how to assign it correctly, so that it recognizes events that happen in this queue.


text:
Q: How to search for file and file contents in Eclipse? I was using Netbeans and find the search is fairly simple, just right click and click on Find. It searched for file name as well as contents.
Just moved to Eclipse Mars2, there is no find on right click of project.

There is Search on menu (CTRL+H) and when i clicked

In eclipse, I have multiple projects and i tried to search text in single java project but it keep on searching on multiple projects even if my project is selected.
Could anyone provide me direction for easy search in eclipse?

A: select the project you want and do ctrl+H (or Search->Search), select second tab(File search). Make sure "Selected resources" is selected. This searches for the containing text in all files matching the provided file name patterns in the selected project.


text:
Q: TCheckBox in RAD Studio XE5 Mobile App I tried to use a CheckBox in a Firemonkey Mobile App. But when running the App I can't click on the CheckBox, e.g. it doesn't change it's IsSelected value.
Also if I try to handle the OnClick event I never receive this event.
On the same form I also use a TTMSFMXRating component. Most of the time it doesn't react when clicking on it. On an other form that TTMSFMXRating works without problems.
What do I do wrong ? I can't see any difference between these two forms (on both of them I also have some FireDAC DB access).
I also tried to generate a new FireMonkey Mobile App with just a CheckBox. But also there I can't change it's IsChecked value by clicking on it and don't receive any onClick events.
I would be happy for every hint.

A: TCheckBox is not a standard component on mobile platforms so is not supported by RAD Studio.
Use TSwitch instead.