text:
Q: Guard Against Invalid Parameter Input I have a parameter being passed through to a procedure that takes in a list of ints in the form of a varchar as follows:
@sSortFilter    VARCHAR(512) = ''

I want to validate it on the procedure side so if someone puts a comma at the beginning before the int when executing the procedure such as:
, 23, 24

Instead of 23, 24 it will guard against that so the procedure does not blow up.
Is there a way to guard against this using SQL?

A: Look here:  https://msdn.microsoft.com/en-us/library/ms175976.aspx
Example:
 BEGIN TRY

  SELECT 1/0;
  --This is where you would break your list down, if it fails here the catch will fire
END TRY
BEGIN CATCH
 -- how you want to handle the error.
END CATCH;

A: Use Case statement with some string functions to check whether your input has leading comma and override it. Try this.
DECLARE @sSortFilter VARCHAR(512) = ', 23, 24'

SELECT @sSortFilter = CASE
                        WHEN LEFT(Ltrim(@sSortFilter), 1) = ',' THEN Ltrim(Substring(@sSortFilter, 2, Len(@sSortFilter)))
                        ELSE @sSortFilter
                      END

SELECT @sSortFilter


text:
Q: Remember Me - How long should be the duration Just saw a site which said "Remember me for 3 weeks". Some of the email sites like Yahoo or Gmail offer 2 - 3 weeks as this duration. What would be an apt duration for a site which will be predominantly used by children ?

A: It depends on what you are protecting. The tradeoff, as you aware is between security and making life easy for users.
If this site doesn't contain sensitive data, and the user is on a home pc, it may make sense to set it to a very long time to make it easy for the child.
If the site contains sensitive information, say a bullying reporting site, it may make sense to protect the logon a bit more strongly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Same query ran on the same database on two servers returns different order I have a query which I run on two database restores on two SQL Server 2008R2 instances and they return the results with different ordering (on one server they're ordered by ID and on the other they aren't ordered)
SELECT
    C.ID AS CodeID
    , C.Format FormatId
FROM bankCodes C
INNER JOIN bankFormat F ON (C.Format = F.ID)

As you can see there is no ORDER BY clause in the query, but the order the results are being displayed is different.
I have tried to rebuild the indexes for the two tables, but it didn't work.
When running a SELECT * FROM bankCodes on the server where the ordering of the above query is implicitly done by ID, the results are not ordered (by primary key column), but after JOINing with bankFormat table, the results are ordered.
I don't know what else to look for in order to explain this.
Could anyone else suggest what could be the cause of this?
Could it be something related to database collation, indexes or primary/foreign keys?

A: That is because you did not add an order by clause.
A DB is optimised for speed. If you specify an order the data will be delivered that way. But without it it will just grab the records in any order as fast as possible.
That is why you can't rely on any "implicit" ordering. Define one if you need it, otherwise you can't depend on anything.

A: The reason for why data is returned from the database in a particular order, when you don't add an ORDER BY clause contains a multitude of elements:

*

*Indexes

*Data

*The order the data was inserted in (which may impact the way data is stored on disk, separated into pages, etc.)

Then when querying, there's lots of other things:

*

*The order of the joins (both the order they were specified in and the order the database engine decides to consider/execute them)

*How the database engine decides to do joins or WHERE clauses, things like hash tables, hash sets, mergejoins, table lookups, etc. will impact the "natural" order the data is available in

The problem is that these reasons are not exhaustive, and will never be. The database has a "license to reorder" when you don't specify an order, and it will use it, it doesn't have to explain its actions beyond that.
As such, if you want to know the specific reason some data was returned in a particular way, you may look at the execution plan, but it may not tell the whole picture. This picture is also a (possibly contrived) snapshot of the current execution plan. When data or indexes changes, it may change at any time.
As such, you won't find the definitive answer here.
There is only one rule to follow:

If you care about the order of the returned data, add ORDER BY

Corollary to that rule:

If you don't add an ORDER BY clause, you lose all rights to care/complain about the (incorrect) order


text:
Q: VBA Data conversion texte format I'm trying to convert datas:
Date;Employee;Ticket number;Table number
30/09/2016;Josh;005421;17
30/09/2016;Annie;004412;25
30/09/2016;John;001124;12

I need to change the format of my third column, otherwise i'll lose the "zeros".
Expected result :

My code is the following :
 Range("A6:A1048576").TextToColumns Destination:=Range("A6"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Semicolon:=True, Fieldinfo:=Array(Array(3,2))

The problem is that the format changes on the FIRST column with my code, not the third. I don't understand why.
The problem gotta be here :
 Fieldinfo:=Array(Array(3,2))

I recorded the process with the macro editor :

Sub Macro1()
    '
    ' Macro1 Macro
    '

    '
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=True, Comma:=False, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1)), TrailingMinusNumbers:= _
        True
    Range("B6").Select
End Sub

My code looks similar to the macro editor. Therefore, I don't get why I don't get the expected result.
Could you please give me a hand?
Thanks and have a great day

A: As your macro recorder shows you need to specify
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1))

One array for each column.

When the data is delimited, this argument is an array of two-element arrays, with each two-element array specifying the conversion options for a particular column. The first element is the column number (1-based), and the second element is one of the xlColumnDataType constants specifying how the column is parsed.

Here is an example how to generate an array for FieldInfo dynamically:
First we need to determine how many columns we need. We do this by counting the semicolons.
Sub GeneraterFieldInfoArrayExample()
    Const cDelimiter As String = ";"

    Dim str As String
    str = "30/09/2016;Josh;005421;17" 'replace with representative data, something like ThisWorkbook.Worksheets("Sheet1").Range("A6").Value

    Dim countCols As Long
    countCols = Len(str) - Len(Replace(str, cDelimiter, "")) + 1 'determine how many columns are needed by counting semicolons. Afterwards we build the array.

    Dim arrFieldInfo() As Variant
    ReDim arrFieldInfo(countCols - 1) As Variant 'resize array

    Dim iCol As Long
    For iCol = 1 To countCols 'generate array for each column
        Select Case iCol
            Case 3, 10 'format column 3 and 10 as text
                arrFieldInfo(iCol - 1) = Array(iCol, 2)
            Case Else 'format any other columns as default
                arrFieldInfo(iCol - 1) = Array(iCol, 1)
        End Select
    Next iCol

    'use like: Fieldinfo:=arrFieldInfo()
End Sub

In the first case all columns which have to be formatted as text ar listed. All other columns become default format. You can add additional cases on your needs.


text:
Q: Using pthreads and the code doesn't even get to main method I am doing an assignment for school and I am supposed to make the following code (which generates pgm image with a Buddhabrot fractal) parallel.
Thing is the compiler doesn't point any errors and still the code won't even get to main. I have already tried looking it up but didn't find a way to solve it.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define NT 3

int nColumns, nLines, size, ite, proximo;
double dt, x, y;
float **mat;

pthread_mutex_t mutex;
pthread_cond_t condM;
pthread_cond_t condE;

typedef struct {
    int x;
    int y;
} int2;

typedef struct{
    double x;
    double y;
} double2;

int2 coordinatesConversion(double x,double y, int nColumns,int nLines){
    int2 ret;
    int2 retError;
    retError.x=-1;
    retError.y=-1;
    ret.x=round(((2.0+x)/3.5) *((double)(nColumns-1)));
    ret.y=round(((1.5+y)/3.5) *((double)(nLines-1)));
    if(ret.x<0 || ret.x>=nColumns) return retError;
    if(ret.y<0 || ret.y>=nLines) return retError;
    return ret;
}

int printMatrixToFilePGM(float **mat,int tamx, int nLines, char *srcFile){
    FILE *arq=fopen(srcFile,"w");
    int cont, cont2;
    float min,max;
    min=mat[0][0];
    max=mat[0][0];
    for(cont=0;cont<nLines;cont++)
        for(cont2=0;cont2<tamx;cont2++){
            if(min>mat[cont][cont2]) min=mat[cont][cont2];
            if(max<mat[cont][cont2]) max=mat[cont][cont2];
        }

    max=max*0.35;
    float delta = max-min;
    fprintf(arq,"P2 \n");
    fprintf(arq,"%d\n%d \n",tamx,nLines);
    fprintf(arq,"255\n");
    for(cont=0;cont<nLines;cont++)
        for(cont2=0;cont2<tamx;cont2++){
            int valpixel=((mat[cont][cont2]-min)/delta)*255.0f;
            if(valpixel>255) valpixel=255;
            fprintf(arq,"%d \n", valpixel);
        }
    fclose(arq);
}

float** mallocFloatMatrix(int tamx, int nLines, float defaultValueOfTheElementsAtMatrix){
    float **errorCodeReturn=0x0;
    float **mat;
    int i,j;
    int condErrorMalloc=0;
    mat=malloc(sizeof(float *)*nLines);
    if(mat==0x0) return errorCodeReturn;
    for(i=0;i<tamx;i++) mat[i]=malloc(sizeof(float )*tamx);
    for(i=0;i<tamx;i++)
        if(mat[i]==0x0){
            condErrorMalloc=1;
            break;
        }

    if(condErrorMalloc==0) return mat;
    for(i=0;i<nLines;i++) for(j=0;j<tamx;j++) mat[i][j]=defaultValueOfTheElementsAtMatrix;
    for(i=0;i<tamx;i++) if(mat[i]!=0x0) free(mat[i]);
    free(mat);
    return errorCodeReturn;
}

void freeFloatMatrix(float **mat,int tamx, int nLines){
    int i;
    for(i=0;i<nLines;i++) if(mat[i]!=0x0) free(mat[i]);
    free(mat);
}

int iteration(double x,double y, int nColumns,int nLines, int ite,int2 *iterationPath){
    int cont;
    int condInvalidPointer=1;
    double2 z;
    z.x=0.0;
    z.y=0.0;
    double2 c;
    c.x=x;
    c.y=y;
    double2 zt;
    for(cont=0;cont<ite;cont++){
        zt.x=((z.x*z.x)-(z.y*z.y))+c.x;
        zt.y=(2.0*(z.x*z.y))+c.y;
        z=zt;
        if(((z.x*z.x)+(z.y*z.y))>4.0){
            if(cont>100) condInvalidPointer=0;
            break;
        }
        iterationPath[cont]=coordinatesConversion(z.x,z.y,nColumns,nLines);
    }
    if(condInvalidPointer) return 0;
    return cont;
}

void *mestre(void *param) {
    int i;
    for(i=0;i<size;i++){
        x = -2.0+((double)i*dt);
        for(y=-2.0;y<2.0;y=y+dt){
            pthread_mutex_lock(&mutex);
            proximo++;
            pthread_cond_signal(&condE);
            pthread_cond_wait(&condM, &mutex);
            pthread_mutex_unlock(&mutex);
        }
    }
}

void *escravo(void *param) {
    pthread_mutex_lock(&mutex);
    if(proximo==0) pthread_cond_wait(&condE, &mutex);
    double xe = x;
    double ye = y;
    proximo--;
    pthread_cond_signal(&condM);
    pthread_mutex_unlock(&mutex);
    int k;
    int2* iterationPath = (int2 *)malloc(sizeof(int2)*ite);
    if(iterationPath==0x0) return 0x0;
    int completedIterations = iteration(xe, ye, nColumns, nLines, ite, iterationPath);
    for(k=0;k<completedIterations;k++){
        if(iterationPath[k].x!=-1 && iterationPath[k].y!=-1)
            mat[iterationPath[k].x][iterationPath[k].y]=mat[iterationPath[k].x][iterationPath[k].y]+1.0f;
    }
    free(iterationPath);
}

int main(void){

    printf("Main method has started.");

    pthread_mutex_init(&(mutex), NULL);
    pthread_cond_init(&(condM), NULL);
    pthread_cond_init(&(condE), NULL);

    nColumns=2048;
    nLines=2048;
    dt=0.001;
    size=round(4.0/dt);
    ite=600;
    proximo = 0;

    mat=mallocFloatMatrix(nColumns,nLines,0.0f);
    if(mat==0x0) return 0;

    pthread_t m;
    pthread_t escravos[NT-1];
    pthread_create(&m, NULL, mestre, (void*)0);

    int i;
    for(i=0; i<NT-1; i++) pthread_create(&escravos[i], NULL, escravo, (void*)0);

    pthread_exit(NULL);

    printMatrixToFilePGM(mat,nColumns,nLines,"saida5.pgm");
    freeFloatMatrix(mat,nColumns,nLines);
    return 0;
}


text:
Q: Type deduction resullts in ambiguous call of overloaded function While mixing type deduction with overloading, I stumbled upon a behavior of type deduction for lambda functions that I find difficult to understand.
When compiling this program:
#include <functional>
#include <cstdlib>

int case_0(int const& x) {
    return 2*x;
}

int case_1(int& x) {
    x += 2;
    return 2*x;
}

class Test {
    public:
        Test(int const n) : n(n) {}
        int apply_and_increment(std::function<int(int const&)> f) {
            n++;
            return f(n);
        }
        int apply_and_increment(std::function<int(int&)> f) {
            return f(n);
        }
    private:
        int n;
};

int main() {
    Test t(1);

    auto f = [](int const& x) -> int {
        return 3*x;
    };

    t.apply_and_increment(case_0);                                 // Fails compilation
    t.apply_and_increment(std::function<int(int const&)>(case_0)); // Succeeds
    t.apply_and_increment(case_1);                                 // Succeeds
    t.apply_and_increment(f);                                      // Fails compilation

    return EXIT_SUCCESS;
}

The output of the compilation is:
$ g++ -std=c++20 different_coonstness.cpp -o test
different_coonstness.cpp: In function 'int main()':
different_coonstness.cpp:34:30: error: call of overloaded 'apply_and_increment(int (&)(const int&))' is ambiguous
   34 |  t.apply_and_increment(case_0);
      |                              ^
different_coonstness.cpp:16:7: note: candidate: 'int Test::apply_and_increment(std::function<int(const int&)>)'
   16 |   int apply_and_increment(std::function<int(int const&)> f) {
      |       ^~~~~~~~~~~~~~~~~~~
different_coonstness.cpp:20:7: note: candidate: 'int Test::apply_and_increment(std::function<int(int&)>)'
   20 |   int apply_and_increment(std::function<int(int&)> f) {
      |       ^~~~~~~~~~~~~~~~~~~
different_coonstness.cpp:37:25: error: call of overloaded 'apply_and_increment(main()::<lambda(const int&)>&)' is ambiguous
   37 |  t.apply_and_increment(f);
      |                         ^
different_coonstness.cpp:16:7: note: candidate: 'int Test::apply_and_increment(std::function<int(const int&)>)'
   16 |   int apply_and_increment(std::function<int(int const&)> f) {
      |       ^~~~~~~~~~~~~~~~~~~
different_coonstness.cpp:20:7: note: candidate: 'int Test::apply_and_increment(std::function<int(int&)>)'
   20 |   int apply_and_increment(std::function<int(int&)> f) {
      |       ^~~~~~~~~~~~~~~~~~~

As far as I understand:

*

*case_0 is ambiguous because there are 2 valid type conversions, std::function<int(const int&)> and std::function<int(int&)>, and both overloaded functions apply_and_increment() can be applied. This is why the explicit type conversion std::function<int(int const&)>(case_0) is required.

*in case_1, the only valid conversion is std::function<int(int&)>, so there is no ambiguity.
I am not very familiar with type deduction and lambdas, so I am a bit surprised that t.apply_and_increment(f) fails to compile. I would expect that the type of the function would be deduced by the type signature, [](int const& x) -> int, in the lambda function.
Why is not f of type std::function<int(int const&)>?

A: Your understanding of overload resolution for case_0 and case_1 is correct:

*

*A reference-to-non-const can be assigned to a reference-to-const, hence case_0() is callable from both of the std::function types being used, thus overload resolution is ambiguous when an implicit conversion is used, requiring you to specify the desired std::function type explicitly.

*A reference-to-const cannot be assigned to a reference-to-non-const, hence case_1() is not callable from std::function<int(int const&)>, only from std::function<int(int&)>, thus overload resolution is not ambiguous when an implicit conversion is used.
A standalone function is not itself a std::function object, but can be assigned to a compatible std::function object.
Likewise, a lambda is not itself a std::function object, it is an instance of a compiler-defined functor type, which can be assigned to a compatible std::function object.
In both cases, std::function acts as a proxy, passing its own parameters to the function/lambda's parameters, and then returning whatever the function/lambda returns.
So, overload resolution fails for both case_0 and f for the exact same reason.  When the compiler has to implicitly convert case_0/f into a std::function object, the conversion is ambiguous because case_0/f is callable from both of the std::function types being used.


text:
Q: Get set of all existing values in a column in PostgreSQL Have a table with about 500,000 rows. One of the columns is a string field.
Is there a way to get the set of all existing values of that string in PostgreSQL without having to request each row out of the database and add the values to a set manually?
Example:

first_name      last_name
will            i.am
will            smith
britney         spears

The set of all existing values for "first_name" would be ['will', 'britney'].

A: SELECT DISTINCT first_name FROM people;

or
SELECT first_name FROM people GROUP BY first_name;


text:
Q: DoubleRenderError in rails I have a ProjectsController for which all the actions except new and index are restricted to admins. I have added a before_filter in my controller like
before_action :authorize_admin!, except: [:index, :show]

and the before_filter looks like this.
def authorize_admin!
  check_login!

  unless current_user.admin?
    redirect_to root_path, alert: "You're not authorized"
  end
end

check_login! is a method in ApplicationController which redirects to the root_path is the user's not logged in.
def check_login!
  flash[:alert] =  'You need to sign up or sign in before continuing'
  redirect_to login_path unless current_user
end

current_user is a method which returns a user record if a session for user exists.(Its not relevant to the error)
The problem is when I try to access /projects/4/edit without logging in, I am getting an undefined methodadmin?' for nil:NilClasserror. In the before filter,check_login!is executed first and if the user's not logged in, he should be redirected to theroot_path`. This clearly means that even after redirect, the execution is not terminated.
In the web console, I tried to execute check_login! and this time, I got  an AbstractController::DoubleRenderError: Render and/or redirect were called multiple times in this action. error. And it hinted me to use redirect_to(..) and return.
Although I knew it won't work, I tried modifying my check_login? method to
def check_login!
  redirect_to login_path, alert:
    'You need to sign up or sign in before continuing' and return unless current_user
end

And I also tried the following after looking at a SO thread.
return redirect_to login_path, alert:
    'You need to sign up or sign in before continuing` unless current_user

I assume that it fails cause it returns to the callee, the authorize_admin! method and again as the current_user is nil, I get the undefined method error.
How can I solve this issue?
Note: I don't want to repeat the check_login! code in authorize_admin! as it violates DRY.

A: If a filter redirects then subsequent filters and the action itself do not run, but the filter itself continues. In your case, after check_login! is called, the authorize_admin! filter continues executing.
You could change check_login! to return true if the check passed and false if there is no current user. Then authorize_admin could do
check_login! || return

Alternatively, the performed? method tells you if a render or redirect has occurred so you could do
check_login!
return if performed?


text:
Q: Actual physical length vs points/pixels on excel worksheet After reading countless pages of information on the insanely confusing aspect of excel graphics, I feel I have no choice but to ask for help.  My details are as follows:
Applicable system parameters:

*

*Windows 7 - 64 bit

*Screen res:  1280 x 720, 96 DPI

*Office 10 - 64 bit

Aside from checking configuration in the windows settings, I pulled these values also using API calls.
When I remove all the items from my excel window (ie. scroll bars, etc), application.usablewidth returns 960.  Zoom is constantly at 100%, although this does not change the aforementioned value.
From what I understand, given my DPI settings, 72 points is equivalent to 96 pixels and that should equal to 1 inch, or 2.54 cm.
However, when I draw a line on to the excel spreadsheet (ie. activesheet.shapes.addline(100,100,172,100)), and I use a ruler to measure the length of the line on the screen, it is actually longer by a factor of 1.75x.
Although it is very easy to code in a ratio which would provide an appropriate calibration, I'd like to understand why is it the case?  What am I missing/omitting?
Thank you in advance for any suggestions.

A: There are so many variables, it's probably impossible to do what you're trying to do reliably.
The key thing you're missing is the physical characteristics of your monitor, those exact settings on a 4" screen would give you a different result to the same settings on a jumbotron.  Not to mention that many monitors allow you to arbitrarily adjust the scale of the output image and the OS would have no idea what had happened.
I suggest you go with your idea of calibrating it, I think it's the only way you'll get it to work..


text:
Q: Prime number check I'm having some issues with my prime number checker in F#. It doesn't seem to give the right results so I'm guessing I've screwed up the logic somewhere but I can't figure out where. The implementation is a simple brute forcing one so the logic isn't complicated and I've implemented similiar solutions using for loops in imperative languages before.
let rec isPrime iterator (n : int) =
                            match iterator with
                            | 1 -> isPrime (iterator + 1) n
                            | a when a = n -> isPrime (iterator + 1) n
                            | _ -> match n % iterator = 0 with
                                    | true -> false
                                    | false -> isPrime (iterator + 1) n

A: As you already figured out in the comments, the problem is that the function should terminate and say true when the iterator reaches n. You can actually make it faster just by iterating up to square root of n or at least n/2 because by the time you reach n/2, you know it will be a prime.
This kind of logic seems to be easier to write using if rather than match - although you can easily fix it by fixing the case in match, I'd probably write something like:
let rec isPrime iterator (n : int) =
  if iterator = n / 2 then true
  elif iterator = 1 then isPrime (iterator + 1) n
  elif n % iterator = 0 then false
  else isPrime (iterator + 1) n

Also, you might not want to expose the iterator parameter to the user - you can write the code using a nested function which calls the loop starting with iterator = 2 (and then you don't need the iterator = 1 case at all):
let isPrime (n : int) =
  let rec loop iterator =
    if iterator = n/2 then true
    elif n % iterator = 0 then false
    else loop (iterator + 1)
  loop 2


text:
Q: Compiler complains about not being able to deduce type of Maybe when I pass Nothing I am getting an error that I don't understand. The library I am using has this function:
getComputedStyle ::
             (MonadIO m, IsElement element, ToJSString pseudoElement) =>
               Window ->
                 Maybe element ->
                   Maybe pseudoElement -> m (Maybe CSSStyleDeclaration)

When I call it like this:
Window.getComputedStyle window (Just element) Nothing

I get this error:
Could not deduce (GHCJS.DOM.Types.ToJSString pseudoElement0)
  arising from a use of 'getComputedStyle'
from the context (Control.Monad.IO.Class.MonadIO m,
                  IsElement element)
  bound by the inferred type of
           isBold :: (Control.Monad.IO.Class.MonadIO m, IsElement element) =>
                     Window -> element -> m (Maybe CSSStyleDeclaration)
  at src/Main.hs:(39,1)-(40,61)
The type variable 'pseudoElement0' is ambiguous
Note: there are several potential instances:
  instance GHCJS.DOM.Types.ToJSString
             ghcjs-base-0.2.0.0:Data.JSString.Internal.Type.JSString

    -- Defined in 'GHCJS.DOM.Types'
  instance GHCJS.DOM.Types.ToJSString
      ghcjs-base-0.2.0.0:Data.JSString.Internal.Type.JSString
    -- Defined in 'GHCJS.DOM.Types'
  instance GHCJS.DOM.Types.ToJSString
             text-1.2.1.1:Data.Text.Internal.Text
    -- Defined in 'GHCJS.DOM.Types'
  instance GHCJS.DOM.Types.ToJSString [Char]

    -- Defined in 'GHCJS.DOM.Types'
 ...

Why does the compiler care about the type? I passed it a Nothing value so the type of the Just value is not really relevant.


text:
Q: How to specify optional dependencies for a makefile I am recent convert to GNU make use. And I am trying to abuse Makefile for all kind of file manipulations because of the parallelism and checkpoint facilities that Makefile provides. Here is my problem:
I have lot of pdf files that I parse to csv. The pdf files are in hierarchical folder structure:
level1/
   level2_1/
      level3_1_1.pdf
      level3_1_2.pdf
   level2_2/
      level3_2_1.pdf
      level3_2_2.pdf

I have my script with the rule:
%.csv: %.pdf
      python parsepdf.py $< $@

But now I want to concatenate all these files. The easy way is using a simple find script
cat $(find level1/ -name '*.csv') > level1/level1.csv

However, I want to do it in a way that follows a dependency hierarchy with a intermediate csv created at each level of the hierarchy. I assume this approach will exploit the advantage of parallelism with make -j.
level1/level2_1/level_2_1.csv : level1/level2_1/level3_1_1.csv level1/level2_1/level3_1_2.csv
         cat $* > $@
level1/level2_2/level_2_2.csv : level1/level2_2/level3_2_1.csv level1/level2_2/level3_2_2.csv
         cat $* > $@
level1/level1.csv : $(wildcard level1/level2_*.csv)
         cat $* > $@

But the above method as two problems:

*

*Even if one of the csv file is not there, the level up csv file won't be created. My requirement is such that even if one file is there, I should go ahead and create a level up csv file.

*How to automatically generate these rules for both levels (ok to assume only two levels) in the hierarchy. Each level can have different number of pdf files.

Is Makefile a good tool for such tasks? If yes, what is the most Makefile'ish  way to specify this target in makefile?

A: I am going to guess what it is that you want, since it is not really clear from your question.
Using find, wildcards or $(wildcard) to generate lists of prerequsites is a bad practice.  Avoid it.  Just list them explicitly.  If you need to automate this process, you can always have some script initially generate the Makefile for you, and edit it by hand later as necessary.
Then you can have
define CONCATENATE_RULE
$1: $2 Makefile
        cat $2 > $1
endef

$(eval $(call CONCATENATE_RULE, level1/level2_1/level_2_1.csv,\
    level1/level2_1/level3_1_1.csv \
    level1/level2_1/level3_1_2.csv \
))

$(eval $(call CONCATENATE_RULE, level1/level2_2/level_2_2.csv,\
    level1/level2_2/level3_2_1.csv \
    level1/level2_2/level3_2_2.csv \
))


text:
Q: Google DataFlow: Read from BigQuery, combine three string fields, write key/value fields to Google Cloud Spanner None of the provided DataFlow templates match what I need to do, so I'm trying to write my own. I managed to run the example code like word count example without issue, so I tried to butcher together parts separate examples that read from BigQuery and writes to Spanner but there's just so many things in the source code I don't understand and cannot adapt to my own problem.
I'm REALLY lost on this and any help is greatly appreciated!
The goal is to use DataFlow and Apache Beam SDK to read from a BigQuery table with 3 string fields and 1 integer field, then concatenate the content of the 3 string fields into one string and put that new string in a new field called "key", then I want to write the key field and the integer field (which is unchanged) to a Spanner table that already exists, ideally append rows with a new key and update the integer field of rows with a key that already exists.
I'm trying to do this in Java because there is no i/o connector for Python. Any advice on doing this with Python are much appreciated.
For now I would be super happy if I could just read a table from BigQuery and write whatever I get from that table to a table in Spanner, but I can't even make that happen.
Problems:

*

*I'm using Maven and I don't know what dependencies I need to put in the pom file

*I don't know which package and import I need at the beginning of my java file

*I don't know if I should use readTableRows() or read(SerializableFunction) to read from BigQuery

*I have no idea how to access the string fields in the PCollection to concatenate them or how to make the new PCollection with only the key and integer field

*I somehow need to make the PCollection into a Mutation to write to Spanner

*I want to use an INSERT UPDATE query to write to the Spanner table, which doesn't seem to be an option in the Spanner i/o connector.
Honestly, I'm too embarrassed to even show that code I'm trying to run.
public class SimpleTransfer {

    public static void main(String[] args) {
        // Create and set your PipelineOptions.
        DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);

        // For Cloud execution, set the Cloud Platform project, staging location, and specify DataflowRunner.
        options.setProject("myproject");
        options.setStagingLocation("gs://mybucket");
        options.setRunner(DataflowRunner.class);

        // Create the Pipeline with the specified options.
        Pipeline p = Pipeline.create(options);

        String tableSpec = "database.mytable";

        // read whole table from bigquery
        rowsFromBigQuery =
            p.apply(
                BigQueryIO.readTableRows()
                    .from(tableSpec);

        // Hopefully some day add a transform

        // Somehow make a Mutation
        PCollection<Mutation> mutation = rowsFromBigQuery;

        // Only way I found to write to Spanner, not even sure if that works.
        SpannerWriteResult result = mutation.apply(
            SpannerIO.write().withInstanceId("myinstance").withDatabaseId("mydatabase").grouped());

        p.run().waitUntilFinish();

    }
}

A: It's intimidating to deal with these strange data types, but once you get used to the TableRow and Mutation types, you'll be able to code robust pipelines.
The first thing you need to do is take your PCollection of TableRows, and convert those into an intermediate format that is convenient for you. Let's use Beam's KV, which defines a key-value pair. In the following snippet, we're extracting the values from the TableRow, and concatenating the string you want:
rowsFromBigQuery
            .apply(
                MapElements.into(TypeDescriptors.kvs(TypeDescriptors.strings()
                                                     TypeDescriptors.integers()))
                    .via(tableRow -> KV.of(
                               (String) tableRow.get("myKey1")
                               + (String) tableRow.get("myKey2")
                               + (String) tableRow.get("myKey3"),
                               (Integer) tableRow.get("myIntegerField"))))

Finally, to write to Spanner, we use Mutation-type objects, which define the kind of mutation that we want to apply to a row in Spanner. We'll do it with another MapElements transform, which takes N inputs, and returns N outputs. We define the insert or update mutations there:
myKvPairsPCollection
            .apply(
                MapElements.into(TypeDescriptor.of(Mutation.class))
                    .via(elm -> Mutation.newInsertOrUpdateBuilder("myTableName)
                                    .set("key").to(elm.getKey())
                                    .set("value").to(elm.getValue()));

And then you can pass the output to that to SpannerIO.write. The whole pipeline looks something like this:
        Pipeline p = Pipeline.create(options);

        String tableSpec = "database.mytable";

        // read whole table from bigquery
        PCollection<TableRow> rowsFromBigQuery =
            p.apply(
                BigQueryIO.readTableRows().from(tableSpec));

        // Take in a TableRow, and convert it into a key-value pair
        PCollection<Mutation> mutations = rowsFromBigQuery
            // First we make the TableRows into the appropriate key-value
            // pair of string key and integer.
            .apply(
                MapElements.into(TypeDescriptors.kvs(TypeDescriptors.strings()
                                                     TypeDescriptors.integers()))
                    .via(tableRow -> KV.of(
                               (String) tableRow.get("myKey1")
                               + (String) tableRow.get("myKey2")
                               + (String) tableRow.get("myKey3"),
                               (Integer) tableRow.get("myIntegerField"))))
            // Now we construct the mutations
            .apply(
                MapElements.into(TypeDescriptor.of(Mutation.class))
                    .via(elm -> Mutation.newInsertOrUpdateBuilder("myTableName)
                                    .set("key").to(elm.getKey())
                                    .set("value").to(elm.getValue()));

        // Now we pass the mutations to spanner
        SpannerWriteResult result = mutations.apply(
            SpannerIO.write()
                    .withInstanceId("myinstance")
                    .withDatabaseId("mydatabase").grouped());

        p.run().waitUntilFinish();

    }


text:
Q: AnkhSVN over ssh problem I try to use the newest AnkhSVN with svn+ssh, but when I try to add a VS 2010 solution to the repository with URL svn+ssh://some.domain.com/svn/ I get the login window. Then I type the password and I can see the repo.
BUT when I click OK everything hangs and window's title says Not Responding.
Please, do you have any ideas?


text:
Q: Python: How to convert list of lists into data frame? I currently have a lists of lists which I have converted to a dataframe as you can see in the screenshot. I would like to break up each list into separate columns. Since each list has 5 entries, the resulting dataframe would be 10 columns by 720 rows. Does anyone know how to efficiently do this? I can create a bunch of for loops, but it is not efficient in my eyes. Thank you!!

A: Assuming that you are given two 720 by 5 lists a and b as in columns 0 and 1 respectively (here mocked by random values for demonstration), you could e.g. create two separate pd.DataFrames first and then merge them using pd.concat:
import pandas as pd
import numpy as np

a = np.random.random((720, 5)).tolist()
b = np.random.random((720, 5)).tolist()

df = pd.concat([pd.DataFrame(a), pd.DataFrame(b)], axis=1)
print(df.shape)

prints
(720, 10)


text:
Q: Algorithm for distributing neighbour sensitive work using a graph I have a number of servers which deal with rectangular chunks of the world, call them "regions". When a player moves from one region to another, if that region isn't owned by the current server, all the player data has to be sent to the server which owns the region they just moved into.
You could imagine that a region is just a node on a graph with 4 neighbors (connected regions). The graph grows and shrinks so I periodically re-balance the work distribution among the servers.
I'd like to use an algorithm to distribute regions to servers optimally, taking the following 3 points into account:

*

*balanced work distribution with regards to the weight of a node, i.e the number of players previously observed in it; if I divide the sum of the weight of all nodes, I need to hit the "nice" spot where the total weight each server handles is roughly equal to every other server in the system.

*contiguity of regions; taking into account above, nodes need to be next to each other to minimize swapping players between servers.

*and extending on (2), consider the number of swapovers from one region to another. A way of preferring that two regions are grouped together in the same server because they exhibit a high traffic of players moving between them, without breaking (1).

I've considered that one way I can achieve this is by using a crude floodfill which assigns scores to several types of region assignment "fills", but this is O(n^2) and probably isn't well suited to the task.
Another algorithm I've thought of starts at the areas of highest traffic and selects nodes with the highest crossover until it meets the minimum work threshold. This would be O(n), but could generate very "stranded" allocations of space where crossovers alternate in directions between redistribution of work, for example.
Is there another way I can assign regions to my servers, in say, O(n)?

A: As far as I know there is no easy and fast way split the nodes in a way which would create the optimal edge cut. Since you are planning to run it on only few servers and you know how your graph is going to look like, I think you could simply calculate the weight of a region and optimize the split so that each region has the same weight.
This should give you very good results. When running on 100s or 1000s of servers, this will take longer since you have so many regions which you need to keep in balance. Still you know the structure of your graph and should take advantage of this information.
If you wouldn't know the structure, there are several algorithms which can try to calculate an optimal edge cut in a centralized or decentralized way but none of them is what you are looking for, since it is an NP complex problem. I had to implement one on top of Giraph - Ja-Be-Ja from KTH (Royal Institute of Technology) and they compare their algorithm also with the others which are out there. So you can just see that your idea will for sure provide much better results for your problem.
Hope this helps


text:
Q: Using Argparse To Convert xml to csv in python I need to accept some command line arguments like so:
argparse.py hi.xml --> to produce hi.csv or
argparse.py hi.xml -o hello.csv --> to produce hello.csv

Here is my code:
import os
import sys
import argparse
import csv
import indent
from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment, tostring
import xml.etree.ElementTree as etree

def get_args(args):
    parser = argparse.ArgumentParser(description = "Converts CSV to XML")
    parser.add_argument('-v','--verbose',action='store_true',dest='verbose',help='Increases messages being printed to stdout')
    parser.add_argument("inputfile", help="Please input the name of the CSV file")
    parser.add_argument('-o','--outputfile',help='(optional) Output file name',nargs='?')
    args = parser.parse_args()
    ext = os.path.splitext(args.inputfile)[1].lower()
    if args.outputfile is None:
        if ext == ".csv":
            args.outputfile = os.path.splitext(args.inputfile)[0] + '.xml'

        elif ext == ".xml":
            args.outputfile = os.path.splitext(args.inputfile)[0] + '.csv'

    elif args.outputfile:
        if ext == ".csv":
            outputfile = open(args.outputfile, 'w')
        elif ext == ".xml":
            outputfile = open(args.outputfile,'w')
    else:
        sys.stderr.write('ERROR: Invalid extension %s\n' % ext)
        sys.exit(1)
    return args

def main(argv):
    args = get_args(argv[0:])
    if args is None:
        return 1
    ext = os.path.splitext(args.inputfile)[1].lower()
    if ext == ".csv":
        reader = read_csv(open(args.inputfile))
        generate_xml(reader, args.outputfile)

    if ext == ".xml":
        root = etree.parse(open(args.inputfile)).getroot()
        generate_csv(root, args.outputfile)

    if args.verbose:
        print ('Verbose Selected')
    if args.verbose:
        print ('Convert to XML with set name')

    return 0

def read_csv(inputfile):
    return list(csv.reader(inputfile))

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)
    head = SubElement(root, 'DrillHoles')
    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
            x1,y1,z1,x2,y2,z2,cost = row
            if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
                toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
                cost = SubElement(current_group, 'cost',{'':cost})
        i+=1
    head.set('total_holes', '%s'%i)
    indent.indent(root)
    tree.write(outfile)

def generate_csv(root, outfile):

    with open(outfile, 'w') as file_:

        writer = csv.writer(file_, delimiter="\t")

    for a in zip(root.findall("drillholes/hole/collar"),
                 root.findall("drillholes/hole/toe"),
                 root.findall("drillholes/hole/cost")):
        writer.writerow([x.text for x in a])

if (__name__ == "__main__"):
    sys.exit(main(sys.argv))

I just need help with the generate_csv part. As you can see from the function get_args(args) i obtain the parameters and this is also where i change the extension of the files using ext = .... then i return it using return args. The main function calls this function and obtains the parameters then checks for the extensions again which then leads to the next function depending on the ext. In the main function i have already parsed the xml file and so i just pass "root" and "args.outputfile" to the generate_csv method. However this is where the error occurs: xml.etree.ElementTree.parserError: no element found line 1 column 0. However, i believe that this may not be the only error and maybe the way i passed the parameters around somewhere it got lost or modified. Please help

A: This isn't exactly a minimal example, so it's hard to work out exactly what your problem is and what the specific question is.
The error says that the parser got no input. This suggests that either the file is actually empty, or the file pointer has been advanced to the end of the file. The file might be empty if you accidentally opened it for writing and truncated it to zero. The file pointer might be advanced to the end of the file if you accidentally opened it for reading, read everything from it, and neglected to rewind the file pointer.
So you can see what's going on, why not try something diagnostic that takes baby steps and prints out in between? That is, instead of etree.parse(open(args.inputfile)), try something like:
print( args.inputfile )
f = open( args.inputfile )
print( f.tell() )
print( f.read() )
f.seek(0)
xml = etree.parse( f )
print( xml )
root = xml.getroot()
print( root )

That way, you can see what's going on.


text:
Q: I want to append all logs in one file in python I have code for writing logs on current directory. It is working fine and it writes all logs in one file from different classes.
Now i want to write code in specific directory (ex: Logs directory)
class PyLog():

    def create_log_handler(self, module, log_file, log_level=None):

        logger = logging.getLogger(module)
        if not log_level is None:
            logger.setLevel(log_level)
        if not getattr(logger, 'handler_set', None):
            fileh = logging.FileHandler(log_file)
            fh_format = logging.Formatter('%(asctime)s -  %(name)s:%(lineno)d - %(levelname)s - %(message)s')
            fileh.setFormatter(fh_format)
            logger.addHandler(fileh)
            if not log_level is None:
                fileh.setLevel(log_level)
            logger.handler_set = True
            setattr(PyLog, 'log_file', log_file)
            setattr(PyLog, 'logger', logger)
        return logger

    def get_logger(self, module, log_file, log_level=None, set_attr=False):

        logger = logging.getLogger(module)

        if not log_level is None:
            logger.setLevel(log_level)

        if not getattr(logger, 'handler_set', None):
            fileh = logging.FileHandler(log_file)
            fh_format = logging.Formatter('%(asctime)s -  %(name)s:%(lineno)d - %(levelname)s - %(message)s')
            fileh.setFormatter(fh_format)
            logger.addHandler(fileh)

            if not log_level is None:
                fileh.setLevel(log_level)

            logger.handler_set = True

            if set_attr:
                setattr(PyLog, 'log_file', log_file)
                setattr(PyLog, 'logger', logger)
        return logger

    @staticmethod
    def write_log(logger_method, log_msg):
        log_msg = str(log_msg)
        print ("%s: %s"%(logger_method , log_msg))
        logger_method(log_msg)

    @staticmethod
    def getTimeStamp():
        return datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S')

I am creating object in some other xyz class like below
   try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                     getattr(PyLog, "log_file"), logging.INFO)
   except AttributeError:
       logger = PyLog().get_logger(self.__class__.__name__,
                                     os.path.join(os.getcwd(),
                                                  "%s.log" % self.__class__.__name__),
                                     logging.INFO)

Same in some abc class
    try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                        getattr(PyLog, "log_file"), logging.INFO)
      except AttributeError:
          logger = PyLog().get_logger(self.__class__.__name__,
                                        os.path.join(os.getcwd(),
                                                     "%s.log" % self.__class__.__name__),
                                        logging.INFO)

This use to write logs of xyz class and abc class in xyz logfile in current working directory.
Now i want to write all logs in Logs folder so i changed some line like below but it started writing creating log file for each class like xyz.log, abc.log.
       try:
           logger = PyLog().get_logger(self.__class__.__name__,
                                       getattr(PyLog, "log_file"), logging.INFO)
       except AttributeError:
           if not os.path.exists(os.getcwd() + "\\Logs"):
               os.mkdir(os.getcwd() + "\\Logs")

           log_dir = os.getcwd() + "\\Logs"
           logger = PyLog().get_logger(self.__class__.__name__,
                                       os.path.join(log_dir,
                                                    "%s.log" % self.__class__.__name__),
                                       logging.INFO)

Please someone help me to fix this. It should write all logs in one file.

A: I found solution. We have to set set_attr=True then it writes all logs in one file.
get_logger(self, module, log_file, log_level=None, set_attr=True)
Ex:
   try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                   getattr(PyLog, "log_file"), logging.INFO)
   except AttributeError:
       if not os.path.exists(os.getcwd() + "\\Logs"):
           os.mkdir(os.getcwd() + "\\Logs")

       log_dir = os.getcwd() + "\\Logs"
       logger = PyLog().get_logger(self.__class__.__name__,
                                   os.path.join(log_dir,
                                                "%s.log" % self.__class__.__name__),
                                   logging.INFO, True)


text:
Q: Keyword '|' in Makefile Prerequisites The MakeFile below:
afl-fuzz: afl-fuzz.c | test_x86
gcc afl-fuzz.c -o afl-fuzz

What's the meaning of '|' before test_x86 ?
The MakeFile is from: https://github.com/loverszhaokai/AFL/blob/gcc_mode/Makefile

A: targets : normal-prerequisites | order-only-prerequisites
The targets will not be updated if the order-only-prerequisites is changed.
Reference: https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html


text:
Q: R Knitr functionalities missing On the following image, we can see the three buttons on the far right.

On the link below, the three buttons on the far right disappear.

Could you help me solve this issue?


text:
Q: How to read the contents of (.bib) file format using Java I need to read .bib file and insert it tags into an objects of bib-entries
the file is big (almost 4000 lines) , so my first question is what to use (bufferrReader or FileReader)
the general format is
@ARTICLE{orleans01DJ,
author = {Doug Orleans and Karl Lieberherr},
title = {{{DJ}: {Dynamic} Adaptive Programming in {Java}}},
journal = {Metalevel Architectures and Separation of Crosscutting Concerns 3rd
Int'l Conf. (Reflection 2001), {LNCS} 2192},
year = {2001},
pages = {73--80},
month = sep,
editor = {A. Yonezawa and S. Matsuoka},
owner = {Administrator},
publisher = {Springer-Verlag},
timestamp = {2009.03.09}
}

@ARTICLE{Ossher:1995:SOCR,
author = {Harold Ossher and Matthew Kaplan and William Harrison and Alexander
Katz},
title = {{Subject-Oriented Composition Rules}},
journal = {ACM SIG{\-}PLAN Notices},
year = {1995},
volume = {30},
pages = {235--250},
number = {10},
month = oct,
acknowledgement = {Nelson H. F. Beebe, University of Utah, Department of Mathematics,
110 LCB, 155 S 1400 E RM 233, Salt Lake City, UT 84112-0090, USA,
Tel: +1 801 581 5254, FAX: +1 801 581 4148, e-mail: \path|beebe@math.utah.edu|,
\path|beebe@acm.org|, \path|beebe@computer.org| (Internet), URL:
\path|http://www.math.utah.edu/~beebe/|},
bibdate = {Fri Apr 30 12:33:10 MDT 1999},
coden = {SINODQ},
issn = {0362-1340},
keywords = {ACM; object-oriented programming systems; OOPSLA; programming languages;
SIGPLAN},
owner = {Administrator},
timestamp = {2009.02.26}
}

As you can see , there are some entries that have more than line, entries that end with }
entries that end with }, or }},
Also , some entries have {..},{..}.. in the middle
so , i am a little bit confused on how to start reading this file and how to get these entries and manipulate them.
Any help will be highly appreciated.

A: We currently discuss different options at JabRef.
These are the current options:

*

*JBibTeX

*ANTLRv3 Grammar

*JabRef's BibtexParser.java


text:
Q: Laravel routing in subdirectories Lets say that I have a folder structure that strays away from the default:
app/controllers
app/models
app/views

but what if I wanted something like this:
app/Site/Admin/controllers
app/Site/Admin/models
app/Site/Admin/views
---------------------
app/Site/Public/controllers
app/Site/Public/models
app/Site/Public/views

I thought namespacing a controller would be used? e.g.
namespace App/Site/Admin/controllers;

use App\Controllers\BaseController;
class DashboardController extends BaseController {

    public function index()
    {
        echo "hey";
    }

}

and then routing
Route::group(array('prefix' => 'admin'), function()
{
    Route::get('/dashboard', 'App\Site\Admin\controllers\DashboardController@index');
});

I've been testing but i can't quite get it working.

A: In your composer.json file, you need to configure the classmap property as such:
"autoload": {
    "classmap": [
        "app/Site/Admin/commands",
        "app/Site/Admin/controllers",
        "app/Site/Admin/models",
        "app/Site/Admin/database/migrations",
        "app/Site/Admin/database/seeds",
        "app/Site/Admin/tests/TestCase.php"
    ]
},

Then do composer update to load the new classmap.

A: 1.first thing you need to do is register the new folder you added to composer autoload.
2.second i say your namespace definition is wrong .
based on your structure,you shoud add this line in you composer.json:
"autoload": {
        "psr-4": {
              "": ["app/Site/Admin","app/Site/Public"]
         }
}

this will autoload all the file in app/site/Admin and app/Site/Public when you use them
then from your command line,go to root folder of your project :
composer dump-autoload

this command will regenerate composer autoload file
And your namespace should be :
namespace App\Site\Admin\controllers;

A: I personally would choose creating sub directories within the main /app folders. This way I'll have a second application, but still be able to reuse functionalities and manage it easier. So the file structure would look something like:
/app
--/controllers
----SomeController.php

----/Admin/DashboardController.php
-------DashboardController.php

Which Laravel version are you using? You can check this with:
php artisan --version

If you are using 4.2.*, you could simply add namespace to your route group, like so:
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin'), function(){
    Route::resource('dashboard', 'DashboardController');
}

Don't forget to also update your composer.json with the sub directories like @lowerends suggested and then execute the autoloading:
"autoload": {
    "classmap": [
        "app/controllers/Admin",
        "app/models/Admin",
        ...
    ]
},

# from the cli
composer dump-autoload

And finally, don't forget to add the according namespace to your classes, like so:
<?php
namespace Admin;

class DashboardController extends BaseController {
    ...

    # if for some reason you are referring to say a model class within the global namespace prefix it with a ("\") back slash

    // /app/models/User.php
    $users = \User::all();

    // /app/models/Admin/User.php
    $users = User::all()

}


text:
Q: Best Way to Extend a JavaScript Library? I am coming back to JavaScript after a long while working with Python, so I have forgotten some of the Javascript best practices.
I would like to work with predefined data structures such as the ones provided by bucket-js.  However, I noticed that bucket-js does not provide much of a toString() method for its objects; so I would like to provide my own methods.
What would be the best way to extend library objects of this type such that the extensions are available throughout my project, but do not involve involve making changes to the library source code?

A: Browser
If your target environment is browsers, then simply put the code that extends the library objects above the rest of your code.
Example:
<script src="bucket-js"></script>
<script>
        buckets.Set.prototype.toString = function() {
            //...
        }

        // Rest of your code
</script>

Node.js
If you are targeting Node.js, or browsers through something like Browserify that works with the same module-based organization, one method is to create your own patched module that patches the library object and then passes it back. You then require this module instead of the vanilla one.
More info: Monkey Patching in Node.js.
Example:
myPatchedBucketJS/index.js
var bucket = require('bucket-js');

buckets.Set.prototype.toString = function() {
    //...
}

module.exports = bucket;

main.js
var bucket = require('myPatchedBucketJS');


text:
Q: Ribbon Icon Doesn't Reverse with Black Theme I'm adding a new ribbon item to a custom ribbon in my Excel workbook using Office RibbonX Editor. The callbacks are all set up, and the image is a 64x64 png file with a transparent background. As you can see, the images all reverse when switching between white and black theme, with the exception of the first one. I can't see anything different between the first image file and the rest, and can't find any reference to image reversal for ribbon icons so wanted to ask here.
This is the ribbon using white theme:

And here is the same ribbon, using Black theme:

As you can see, apart from the first icon, the four right hand icons have all reversed from black on white and red on black to white on black and red on white.
This is the image file for the icon which has been loaded into the editor:

Here is the Xml for the first ribbon 'button', which structurally matches every other 'button' on the ribbon:


text:
Q: I am having this problem in while downloading Android Studio i am having this error while i try to download Android Studio..
Preparing "Install Android Emulator (revision: 30.6.5)".
Warning: Package "com.android.repository.impl.generated.v1.RemotePackage@862c48c8" (emulator) should be installed in
"D:\Program Files\ANDROIDSTUDIOSDK\emulator" but
it already exists.
Installing in "D:\Program Files\ANDROIDSTUDIOSDK\emulator-2" instead.
Downloading https://dl.google.com/android/repository/emulator-windows_x64-7324830.zip

Please help me i am new in Android Studio so please..

A: you have that file already in that particular path.. try to clear that file in below path D:\Program Files\ANDROIDSTUDIOSDK\emulator-2" and clear all caches then try again..
Hope it will work.. Happy Coding!!

A: As Nihthiya Althaf answered, you can try to clear the emulator folder, but I think you have to clear the D:\Program Files\ANDROIDSTUDIOSDK\emulator folder, and remove the D:\Program Files\ANDROIDSTUDIOSDK\emulator-2 folder. Or just delete both of them.


text:
Q: WMI call works in GUI thread (STA Thread), why does it fail in background threads (MTA Threads)? Okay, I have a method which simply backs up the Windows event logs as *.evt files.
In .net2.0 on Windows XP x86 and x64, this worked great, no issues.
We recently upgraded to .net4.0 (4.0.3 specifically) and now this code is failing in a very specific way. (Fails on XP x86 and x64, Win7 works fine)
If the method is executed by the main GUI thread in an event handler, it works fine.
If however this method is executed in a new Thread, or by the ThreadPool, it fails with an Access Denied error.
This application is being run as an administrator and accessing the local computer wmi provider.
I would guess that there is some kind of thread security new in .net4 that I have not satisfied or something like that.
Here is some sample code which illustrates the problem.
This was from a form with 3 buttons, the handlers are at the end and illustrates when it works and when it fails.
It saves a copy of all Windows event logs to ..\Log folder.
Compiling the below with target framework of .Net2.0, all three calling methods work fine.
Compiling with target framework of .Net4.0.3, and the last 2 calling methods fail with Access Denied.
What am I missing here?
    public void ExportWindowsEventLogs(object ignored)
    {
        try
        {
               ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_NTEventlogFile");

               searcher.Scope.Options.EnablePrivileges = true;    // Defaults to False which gives AccessDenied errors so
               foreach (ManagementObject oEventLogFile in searcher.Get())
               {
                   string LogName = oEventLogFile["LogfileName"] as string;
                   if (!String.IsNullOrEmpty(LogName))
                   {
                       // Obtain in-parameters for the method
                       ManagementBaseObject inParams =
                           oEventLogFile.GetMethodParameters("BackupEventlog");
                       // Add the input parameters.
                       string strPath = Application.StartupPath + @"\..\Log\" + LogName + "-Exported.Evt";
                       inParams["ArchiveFileName"] = strPath;

                       //Delete the old backup if it exists, as the WMI BackupEventLog method does not overwrite old files.
                       FileInfo backupFile = new FileInfo(strPath);
                       if (!backupFile.Directory.Exists)
                           backupFile.Directory.Create();
                       else if (backupFile.Exists)
                           backupFile.Delete();

                       InvokeMethodOptions options = new InvokeMethodOptions();

                       // Execute the method and obtain the return values.
                       //FAILS ON NEXT LINE WITH ACCESS DENIED ERROR,
                       //but oEventLogFile.ToString() works fine.
                       ManagementBaseObject outParams =
                           oEventLogFile.InvokeMethod("BackupEventlog", inParams, null);
                       object returnValue =  oEventLogFile.InvokeMethod("BackupEventlog", new object[] { strPath });
                   }
               }
        }
        catch(Exception err)
        {
            MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.ToString());
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        //WORKS
        ExportWindowsEventLogs(null);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //Access Denied error
        Thread workerThread = new Thread(new ParameterizedThreadStart(ExportWindowsEventLogs));
        workerThread.Priority = ThreadPriority.Lowest;
        workerThread.Start(true);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        //Access Denied error
        System.Threading.ThreadPool.QueueUserWorkItem(ExportWindowsEventLogs, null);
    }

UPDATE:
This appears to be directly related to the Thread.ApartmentState setting of the executing thread.
By default threads are created with ApartmentState.MTA, whereas the main GUI thread is an STA thread.
In .Net 4.0, My WMI code works when running in an STA thread, but does not work on the MTA threads. In .Net 2.0, it works in both.
Any ideas how to get it to work in an MTA thread on .Net 4.0? I'd like to use the threadpool to run this.


text:
Q: std::cout shows hex on the screen instead of text I get system time like this:
time_t t = time(0);
struct tm* now = localtime(&t);
TCHAR* tInfo = new TCHAR[256];
swprintf_s(tInfo
    , 256
    , _T("Current time: %i:%i:%i")
    , now->tm_hour
    , now->tm_min
    , now->tm_sec);

And then show on screen:
std::cout << tInfo << std::endl;

But insted of Current time: 12:57:56 I got: 0x001967a8 on the screen. What I did wrong ?

A: You are trying to print a "wide" string. You need to use :
std::wcout << tInfo << std::endl;

The "narrow" version cout doesn't know about "wide" characters, so will just print the address, just like if you tried to print some other random pointer type.

A: Try:
std::wcout << tInfo << std::endl;

A: C++ shares its date/time functions with C. The tm structure is probably the easiest for a C++ programmer to work with - the following prints today's date:
#include <ctime>
#include <iostream>
using namespace std;

int main() {
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;
}


text:
Q: Put_metric_alarm - How to use comparison operator with "Equal to Threshold" in AWS - Python Boto3 Currently, I can see only below possible values for the Comparision parameter, is it possible for EqualToThreshold to be used as comparison operator?
GreaterThanOrEqualToThreshold
GreaterThanThreshold
LessThanThreshold
LessThanOrEqualToThreshold
LessThanLowerOrGreaterThanUpperThreshold
LessThanLowerThreshold
GreaterThanUpperThreshold

Suppose I want to create an alarm whenever the threshold value equals 0, but I do not see the "Equal" option. Is there any other work around we can use to make that work?

A: There is no Equal, but in your case you could use:
LessThanOrEqualToThreshold of 0

instead of Equal to 0.


text:
Q: Cannot mount disks at bootup I've been having a particular problem with Ubuntu and its flavours for a year. Now that I have made a fresh install of Xubuntu, I thought the problem might fix itself but it has not. Please keep in mind that I am a normal computer user. I have scoured the net for answers and simple solutions that my competence allows, I have tried.
This thread is very close to the problem I am having, although I can mount my disks once the OS has started if I click manually on them in Thunar or Nautilus. They are simply grayed out as shown here.
If I start GNOME Disks, the disks are found without a problem.
If you take a look at the settings, they should be correct. If I take away the automatic mount options at boot up, I get an error like:
An error occurred while mounting /mnt/*my disk name* keys:Press S to skip mounting or M for manual recovery

...similar to this problem.
Here is my BIOS information, the BIOS sees the disks without a problems, and when I used to run windows, there never was a problem.
BIOS Information
    Vendor: American Megatrends Inc.
    Version: 0809
    Release Date: 05/16/2014
    Address: 0xF0000
    Runtime Size: 64 kB
    ROM Size: 8192 kB
    Characteristics:
            PCI is supported
            APM is supported
            BIOS is upgradeable
            BIOS shadowing is allowed
            Boot from CD is supported
            Selectable boot is supported
            BIOS ROM is socketed
            EDD is supported
            5.25"/1.2 MB floppy services are supported (int 13h)
            3.5"/720 kB floppy services are supported (int 13h)
            3.5"/2.88 MB floppy services are supported (int 13h)
            Print screen service is supported (int 5h)
            8042 keyboard services are supported (int 9h)
            Serial services are supported (int 14h)
            Printer services are supported (int 17h)
            ACPI is supported
            USB legacy is supported
            BIOS boot specification is supported
            Targeted content distribution is supported
            UEFI is supported
    BIOS Revision: 4.6

As requested:
The /etc/fstab contents when all disks are mounted (manually) are:
cat /etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda2 during installation
UUID=2fc3dd54-6898-49f0-bd3d-40c9c822dd12 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=7D71-BEB0  /boot/efi       vfat    defaults        0       1
# swap was on /dev/sda3 during installation
UUID=43c256fc-2a8f-47ff-b6e5-77c6a2b68cbf none            swap    sw              0       0

When not mounted are
<file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda2 during installation
UUID=2fc3dd54-6898-49f0-bd3d-40c9c822dd12 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=7D71-BEB0  /boot/efi       vfat    defaults        0       1
# swap was on /dev/sda3 during installation
UUID=43c256fc-2a8f-47ff-b6e5-77c6a2b68cbf none            swap    sw              0       0

<file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda2 during installation
UUID=2fc3dd54-6898-49f0-bd3d-40c9c822dd12 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=7D71-BEB0  /boot/efi       vfat    defaults        0       1
# swap was on /dev/sda3 during installation
UUID=43c256fc-2a8f-47ff-b6e5-77c6a2b68cbf none            swap    sw              0       0

I would really appreciate help.
Thank you


text:
Q: How to add onmouseover styling to an element through javascript? Attempting to remove and reapply function to the onmouseover event of an element. Not sure how to go about this, have attempted several ways without any luck.

<!DOCTYPE html>
<html>
<body>

<button id="my_button" onmouseover="myFunction(this)">Try it</button>

<script>

function myFunction(ele) {
  alert("hi")
  document.getElementById("my_button").onmouseover = "null";
  document.getElementById("my_button").onmouseover = "myFunction(this)";
}

</script>
</body>
</html>

A: you can use :

<button id="my_button" onmouseover="alert('hi')">Try it</button>

A: The issue is that you're setting the button onmouseover property to a string in myFunction instead of to a function object.
The HTML parser creates an anonynmous handler function from the onmousever attribute value for you, but setting the button property to a string in JavaScript won't create such a function. Try

<!DOCTYPE html>
<html>
<body>

<button id="my_button" onmouseover="myFunction.call(this, event)">Try it</button>

<script>

function myFunction(event) {
  alert("hi, this.tagName = " + this.tagName)
  document.getElementById("my_button").onmouseover = "null";
  document.getElementById("my_button").onmouseover = myFunction; // a function object
}

</script>
</body>
</html>

Notice I've modified myFunction to see the button object as its this value, and its argument to be the mouse event raised for the click, and changed the call in the handler generated by the HTML to call myFunction as if it were the actual event handler. This was to keep the calls to myFunction seeing the button as its this value and event as its argument in both cases.
For more about the handler created by the HTML parser see a previous answer   (disclaimer: of mine) to 'this inside event handler from HTML attribute' that goes into greater detail.

Note that for various reasons it is no longer recommended to create event handlers using oneventname attribute values in HTML when you can add them using element.addEventListener in JavaSript as part of initialization.

A: try

<!DOCTYPE html>
<html>
<body>
<button id="my_button" class="mousemove" >try it</button>
<script>
document.getElementsByClassName("mousemove")[0].onmousemove = function(){
  alert("hi")
  document.getElementById("my_button").onmousemove = function(){ return null }
}
</script>
</body>
</html>


text:
Q: Async programming control issue in c# I am using async programming in my c# and I am trying to update data into the db on checking if the records exist else add new record
var existingStudent = await CheckIfStudentExists(student); // check if the Student with the StudentCode is already exist

if (existingStudent is null)
{
    await _context.Students.AddAsync(student);
    await SaveChanges();
}
else
{
    student.StudentId = existingStudent.StudentId;
    _context.Students.Update(student);
    await SaveChanges();
}

Since here I am uploading bulk files (say around 7000) in one shot. It happens that the same StudentCode with 2 different files can comeup. Many times I have observed that ADD part of the code is executed without checking if the student exists.
What is the change I need to do so that If-Else condition is not executed till the CheckIfStudentExists is executed.

A: Well, this code is vulnerable to race condition. Nothing stops two threads checking that student does not exists and enter block of a code where you insert student. This leads to the same student inserted twice.
What you can do is to use some synchronization technique, like locks or semaphore. I will present you the simpliest lock, but it is up to you to choose for yourself how you want synchronize threads.
// somewhere in a class define
private readonly object syncObject = new object();

// and use it in the method
lock(syncObject)
{
    var existingStudent = await CheckIfStudentExists(student); // check if the Student with the StudentCode is already exist

    if (existingStudent is null)
    {
        await _context.Students.AddAsync(student);
        await SaveChanges();
    }
    else
    {
        student.StudentId = existingStudent.StudentId;
        _context.Students.Update(student);
        await SaveChanges();
    }
}

A: if (existingStudent == null)
{
    await _context.Students.AddAsync(student);
    await SaveChanges();
}
else
{
    student.StudentId = existingStudent.StudentId;
    _context.Students.Update(student);
    await SaveChanges();
}


text:
Q: Is it possible to make a real integration test with JerseyTest? There are many pages on the net, declaring that they describe the creation of integration tests with JerseyTest. Such as:
https://blog.codecentric.de/en/2012/05/writing-lightweight-rest-integration-tests-with-the-jersey-test-framework/
But notice! It is not an integration test really. It mocks the whole service under the API function. So, it is a unit test. And all examples for 'integration' tests that I had found, are such mocking stubs.
And I want to create a really integration test, I want to send a JSON string and get back another JSON string (or HTML). Of course, for that Jersey in coordination with JerseyTest should collaborate somehow to create a request, call my API function, follow it to the DB queries, fulfil them, and return a response that I can assert by parts.
How can I do it? (If it is possible, of course)


text:
Q: Android reloading intent data on returning to activity from activity group I have multiple tabs and within them I have got an activity group for each. When I go from one tab to another then hit back I lose my intent data.
For example, I start activity 1, pass object 1 to activity 2 via the activitygroup I then go to activity 3 passing object 1, however when I go back to activity 2 onCreate is never called and I cannot set my intent data if I want to go back to Activity 3.

A: If you want to send data between activities you can use startActivitiForResult or you can do something like this :
Intent intent = new Intent(Activity.this, Activiti2.class);
intent.putExtra("key", "value");
startActivity(intent);

in Activity2 :
String getData = getIntent().getStringExtra("key","default value");
// or getParent().getIntent().getStringExtra("key","default value"); depending on your situation.

and if you want to send data to Activity from Activity2 you can do something like this :
 Intent intent = getParent().getIntent();
 intent.putExtra("key", 0); // default sorting
 getParent().setResult(RESULT_OK, intent);
 finish();


text:
Q: How to play music with the front speaker on Android i have this code for detect if the smartphone plays music
myButton=(Button)findViewById(R.id.button);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Evento click
               if(mAudio.isMusicActive())
               {
                   //Code Here
               }

            }
        });

i need to play music on the internal speaker(is used to talk on the phone) is possible?


text:
Q: Laravel Validation Error Handing I have a statement in my code like this
  return response()->json([
     'error'=>$validator->errors()->all()
  ]);

When I view the response it has curly braces around it and looks like an object and it throws an error in the console that says
SyntaxError: Unexpected end of JSON input
    at parse ()
What do I need to change to get the format that my ajax call can interpret?
This code worked inside of a controller but when I move it to a different page it breaks so it seems there is something in the controller that corrects this, but is missing on my own page.  Any ideas?

A: you can try something like below code
$data['success'] = false;
$data['message'] = $validator->errors()->all();
echo json_encode($data);

A: obviously the json structure is wrong, u show use json_encode() to handle the $validator->errors()->all();
return response()->json([
 'error'=>json_encode($validator->errors()->all())

]);


text:
Q: Construir tabla con JQuery con los datos retornados de un JSON La cuestión es que en mi código js no se que debo hacer muy bien que debo hacer en la función pintarTr y en la función llenarTabla para que me muestre los resultados que tengo en el json.
Este es el código js:

$(document).ready(function(){

    var clientId = $("#clientId option:selected").val();
    var clientName = $("#clientId option:selected").text();

    var professionalId = $("#professionalId option:selected").val();
    var professionalName = $("#professionalId option:selected").text();

    validarSelect(clientId, clientName);
    validarSelectProfessional(professionalId, professionalName);
    var alert = 'El informe de condiciones de salud se carga para: ';

    $('#clientId').change(function(){

        clientId = $(this).val();
        clientName = $('#clientId option:selected').text();

        validarSelect(clientId, clientName);
    });

    $('#professionalId').change(function(){

        professionalId = $(this).val();
        professionalName = $('#professionalId option:selected').text();

        validarSelectProfessional(professionalId, professionalName);
    });

    $('select[multiple=multiple]').multipleSelect({
        filter: true,
        selectAll: true,
        placeholder: labelMax,
        countSelected: '# seleccionados',
    });

    function validarSelect(clientId, clientName){
        if (clientId) {
            $("#clientName").html(alert+""+clientName);
            $("#hreport_clientId").val(clientId);
        }else{
            $("#clientName").html(alert+" informe de condiciones de salud ");
            $("#hreport_clientId").val(null);
        }
    }

    function validarSelectProfessional(professionalId, professionalName){
        if (professionalId) {
            $("#professionalName").html(alert+""+professionalName);
            $("#hreport_professionalId").val(professionalId);
        }else{
            $("#professionalName").html(alert+" informe de condiciones de salud ");
            $("#hreport_professionalId").val(null);
        }
    }

});

$("#btn_consulta").click(function() {
    try {
        if($("#clientId").val() == ""){
            alert("Seleccione un cliente.");
        }else if($("#professionalId").val() == ""){
            alert("Seleccione un profesional.");
        }else{
            var clientId = $("#clientId").val();
            var professionalId = $("#professionalId").val();
            $.ajax({
                url: $('#url').val(),
                type: 'GET',
                data: {
                    clientId: clientId,
                    professionalId: professionalId
                },
                beforeSend: function() {
                    loaderAdmin();
                    pintarTr();
                },
                success: function(json) {
                    llenarTabla(json);
                },
                complete: function() {
                    loaderAdmin(true);
                }
            });
        }
    } catch (e) {
        console.log("Error Function buildDataTable: " + e.message + "\nLine: " + e.lineNumber);
        return false;
    }
});

function llenarTabla(json) {
 try{
        $('#subida_archivoh').css('display', '');

  $('#contentTable').html(tabla);

      buildDataTableMatrix();
 }catch (e) {
        console.log("Error Function llenarTabla: " + e.message + "\nLine: " + e.lineNumber);
        return false;
    }
}

function pintarTr() {
    try {

    } catch (e) {
        console.log("Error Function pintarTr: " + e.message + "\nLine: " + e.lineNumber);
        return false;
    }
}

/**
 * Construye las tabla dinamica DataTable
 * @returns
 */
function buildDataTableMatrix() {
    try {
        var table = $('.dinamicTable').DataTable({
            dom: 'Bfrtip',
            scrollX: false,
            scrollY: '50vh',
            footer: false,
            scrollCollapse: true,
            order: [
                [2, "desc"]
            ],
            //paging: false,
            buttons: [{
                //extend: 'reporte',
                footer: false,
                bom: true,
                fieldSeparator: ';',
            }],
        });

    } catch (e) {
        console.log("Error Fuction buildDataTable: " + e.message + "\nLine: " + e.lineNumber);
        return false;
    }

}

y mi html:

Informe de condiciones de salud

            <select name="clientId" id="clientId" class="form-control"  style="width: 312px;" >
                <option value="">Seleccione un cliente</option>
                {% for client in clients %}
                    <option value={{client.clientId}}>{{client.tradename}}</option>
                {% endfor %}
            </select>
            <input type="hidden" id="url" value="{{ path('statistics_find_Hreports') }}">

            <select name="professionalId" id="professionalId" class="form-control"  style="width: 312px;" >
                <option value="">Seleccione un Profesional</option>
                {% for professional in professionals %}
                    <option value={{professional.professionalId}}>{{professional.name}}</option>
                {% endfor %}
            </select>
            <input type="hidden" id="url" value="{{ path('statistics_find_Hreports') }}">

            <button class="btn btn-primary" id="btn_consulta" >Consultar</button>

    <input type="hidden" id="srcImgLoader" value="{{ asset('assets/images/loader-2.gif') }}">

                Id_Reporte
                Reporte
                Cliente
                Profesional

    {% set x = {'classFormGroup' : 'col-md-12'} %}

            {{ macroF.start(form, 'Importar pdf', { 'attr': {'class': 'center'} }) }}

            {{ macroF.input(form.hreportFile, 'hreportFile', x) }}
            {{ form_widget(form.clientId) }}
            {{ form_widget(form.professionalId)}}
            {{ macroF.end(form, '') }}

{% endblock %}

{% block scriptfooter %}

{% endblock %}

Estos son los resultados:

Agradezco su ayuda.

A: Utilizando la libreria de Datatable puedes insertar tu Arreglo de Objetos (JSON) como parametro y automaticamente crea la tabla

$('#TuIDdeLaTabla').DataTable({
    data: JSONArray,
    columns: [
        { data: 'Dato1' },
        { data: 'Dato2' },
        { data: 'Dato3' }
    ]
});

Te dejo la documentacion para mas informacion
Como usar Objetos en Datatable

A: En to código javascript llamas a la clase .dinamicTable , pero en tu html no esta referenciada en ninguna parte, y la tabla en concreto que quieres usar para mostrar los datos tiene como identificador otro diferente:
Código de la función:
/**
 * Construye las tabla dinamica DataTable
 * @returns
 */
function buildDataTableMatrix() {
    try {
        var table = $('.dinamicTable').DataTable({
            dom: 'Bfrtip',
            scrollX: false,
            scrollY: '50vh',
            footer: false,
            scrollCollapse: true,
            order: [
                [2, "desc"]
            ],
            //paging: false,
            buttons: [{
                //extend: 'reporte',
                footer: false,
                bom: true,
                fieldSeparator: ';',
            }],
        });

    } catch (e) {
        console.log("Error Fuction buildDataTable: " + e.message + "\nLine: " + e.lineNumber);
        return false;
    }

Cabecera de la tabla:

Un saludo !


text:
Q: Scheduled task copying problems - no errors I am building a script that will do database backup and will copy the backup to a safe storage location on another computer. I have that specific location already mounted on Y: and have built my script (.bat).
The script runs fine in test runs, but when task scheduler runs it the part in charge of copying:
copy /Y "C:\something or other\Backup.bak" "Y:\DB\DB-%mydate%.bak"

doesn't run. In order to see what is going on when scheduler runs the script I appended
>> backup.log
to every line of the script.
When I tried manually running the scrip through task scheduler in order to test what is the problem the only thing copy outputs is:
0 file(s) copied

and nothing else. No other error.
I know that Start Folder set in task could be the problem but I did set it to the folder where the script is. Also start folder shouldn't be an issue since all the time I'm working with full paths.
EDIT: I'm running this on Windows Server 2003 SP2 if it has anything to do with it.
So any ideas what could be the problem?

A: Hello I have recently done some work with Windows server Scheduled tasks.
The exit code may help you if you look at the task scheduler highlight your task and select the history tab 0x0 is success 0x1 is some kind of error but not very specific...
Some basic pointers

*

*You can test the scheduled task by right clicking and selecting run

*The user account the task is running as requires logon as batch user
permissions on the server you intend to run the task on this can be
added to local policy start> run/search gpedit.msc or by
administering group policy on the domain.

*If it is not the account you are using to test shift+right click command prompt and run as the user running the  task then run your batch file this will at least give you confidence the user account can run the batch file interactively

for more information see http://technet.microsoft.com/en-us/library/cc721846.aspx

A: can you try to map the network drive inside the script or use UNC ?
something like
pushd \\server\path
copy c:\backup.bak .
popd

A: I was having this issue when trying to access/copy files from a protected network share via a Scheduled Task.
My problem was with the Scheduled Task's configuration.  Using Win10, my Task was configured as follows (under "General" - "Security options"):

*

*[ ] "Run only when user is logged on"

*[x] "Run whether user is logged on or not"

*

*[x] "Do not store password.  The task will only have access to local resources"  [This is the problem]
I fixed the problem by un-checking the "Do not store password" checkbox.
Presumably, I could also fix it by opting for "Run only when user is logged on".


text:
Q: Laptop settings resizing web page pushing divs 'off' the page - is there a way around this via code? My boss is running a laptop which has a setting which is resizing font sizes and making them larger by about a third.  This is fine but we have a java app running on the site and the div tags are being pushed off of the page because of the increase in font size.  Is there a way to stop font being resized, via code?
Thanks, R.

A: Depends on the browser, but most use zooming now: see this article: http://www.codinghorror.com/blog/2009/01/the-two-types-of-browser-zoom.html
I do not think you can stop this, nor should you. What about people who need to larger font size.

A: It sounds like the problem is in your DIVs, not in your fonts. Unless your text contains huge strings with no "breaking" characters in them, a DIV should merely set itself to its parent's width as default behavior.


text:
Q: How to replace all linebreaks from a datatable [PAD] I'd like to replace all linebreaks from my whole datatable, but I don't know how to do it...
I tried using 'Replace text' but I accomplished nothing.
my data

A: You can use decodeUriComponent('%0A') in Replace formula to find "new line" character.
At the end the expression will look like this:
replace(outputs('Compose'),decodeUriComponent('%0A'),'-')

this will replace all "new-line" characters with dash "-".


text:
Q: D3 Pie Chart with only one part of JSON data So I am very new to D3.js so I am looking for a little bit of help.  I would like to make a pie chart using just the first part of the JSON response.  For example, here is what the JSON looks like:
[
    {
        "Count": 4224,
        "DNS": 0,
        "Connect": 181,
        "SSL": 218,
        "Send": 65.7,
        "Server Busy": 1459,
        "Receive": 3,
        "RTT": 1926.7
    },
    {
        "Count": 5268,
        "DNS": 0,
        "Connect": 153.3,
        "SSL": 218,
        "Send": 54,
        "Server Busy": 2211,
        "Receive": 1,
        "RTT": 2637.3
    },
    {
        "Count": 5567,
        "DNS": 0,
        "Connect": 103,
        "SSL": 190,
        "Send": 53,
        "Server Busy": 2100,
        "Receive": 2,
        "RTT": 2448
    }
]

So what happens here is RTT is the total (the whole pie) and then Receive, Server Busy, Send, SSL, Connect, and DNS are the pieces to make up the whole (those all added up equal RTT).  All the examples I have found online don't do it this way, so I'm wondering if this is possible, and if so, how could I do that?
I have the basics set up (it just uses all 3 RTT's), but I'm not sure how to use the data the way I want to.  Any help is appreciated.  Thank you!
<!DOCTYPE html>

      <meta charset="UTF-8">
      <title>D3 Graphic</title>

D3 Graphic


text:
Q: Erdas Imagine 2011 removing points from polygons I've been running into an issue with Erdas Imagine 2011. I have been creating training sites in a polygon shapefile to use with a decision tree classifier but it seems like the software keep automatically simplifying/removing points from the polygons I draw. This only seems to happen when I am zoomed in past a certain scale.
I've tried copying the shapefile and using 'Save As' to create a new copy but neither fixed the issue. New shapefiles created in Erdas do not seem to have this problem (although at one point I swear that new shapefiles were having this issue but have not been able to recreate it). I have also tried editing this shapefile in ArcGIS and it seems to work fine.
Before this started happening I had viewed the data in ArcCatalog. Could that have causes this issue? Is there some setting I am missing?
I attached two screen shots to try and clarify. I made both ellipses the same way (using the 'Ellipses' tool on the 'Drawing' tab). This is an exaggerated example but shows the issue.


text:
Q: Removing the iCloud back up message I've been getting messages of the form

iPhone Not Backed Up
This iPhone hasn't been backed up in 141 weeks. Backups happen when this iPhone is plugged in, locked and connected to Wi-Fi.

I have the basic, free 5GB iCloud plan. I've turned off the storage for many apps, including Photos. Making my iCloud use only 594MB.
Is there a way to make it stop?

A: You can disable iCloud Backup in Settings → Apple ID → iCloud → iCloud Backup by switching the switch off.


text:
Q: Android : Split string with { character I have an string
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,"

I want only this 46199005.
But { shows an error, when try to split the string
String[] separated = name.split("edge_followed_by\":{\"count\":");

Showing a suggestion , number expected and want me to replace with *.
Can anyone help me in this.

A: Just replace { with \{.
split is trying to use it as a part of regular expression.

A: Ideally, you should use JSON to parse this if you have proper structure. but if you want to get only the number you can split it using ":" and then split using "}". it should give you the exact number.

A: Why not to use:
String[] separated = name.split(":");
separated[2].split("}")[0];

A: Your string is not exact JSON object otherwise you can simply do json parsing and get the count value.
You can get count value using subtring operations like below:
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,";

String substr = name.substring(name.indexOf("\"count\":") + 10);

String finalstr = substr.substring( 0, substr.indexOf("},"));

Log.d("Extracted_Value", finalstr); // output -> 46199005

There can be multiple ways. This is just one. Hope it will help you!


text:
Q: Subtract previous year's from value from each grouped row in data frame I am trying to calculated the lagged difference (or actual increase) for data that has been inadvertently aggregated. Each successive year in the data includes values from the previous year. A sample data set can be created with this code:
set.seed(1234)
x <- data.frame(id=1:5, value=sample(20:30, 5, replace=T), year=3)
y <- data.frame(id=1:5, value=sample(10:19, 5, replace=T), year=2)
z <- data.frame(id=1:5, value=sample(0:9, 5, replace=T), year=1)
(df <- rbind(x, y, z))

I can use a combination of lapply() and split() to calculate the difference between each year for every unique id, like so:
(diffs <- lapply(split(df, df$id), function(x){-diff(x$value)}))

However, because of the nature of the diff() function, there are no results for the values in year 1, which means that after I flatten the diffs list of lists with Reduce(), I cannot add the actual yearly increases back into the data frame, like so:
df$actual <- Reduce(c, diffs)  # flatten the list of lists

In this example, there are only 10 calculated differences or lags, while there are 15 rows in the data frame, so R throws an error when trying to add a new column.
How can I create a new column of actual increases with (1) the values for year 1 and (2) the calculated diffs/lags for all subsequent years?
This is the output I'm eventually looking for. My diffs list of lists calculates the actual values for years 2 and 3 just fine.
id value year actual
 1    21    3      5
 2    26    3     16
 3    26    3     14
 4    26    3     10
 5    29    3     14
 1    16    2     10
 2    10    2      5
 3    12    2     10
 4    16    2      7
 5    15    2     13
 1     6    1      6
 2     5    1      5
 3     2    1      2
 4     9    1      9
 5     2    1      2

A: I think this will work for you.  When you run into the diff problem just lengthen the vector by putting 0 in as the first number.
df <- df[order(df$id, df$year), ]
sdf <-split(df, df$id)
df$actual <- as.vector(sapply(seq_along(sdf), function(x) diff(c(0, sdf[[x]][,2]))))
df[order(as.numeric(rownames(df))),]

There's lots of ways to do this but this one is fairly fast and uses base.
Here's a second & third way of approaching this problem utilizing aggregate and by:
aggregate:
df <- df[order(df$id, df$year), ]
diff2 <- function(x) diff(c(0, x))
df$actual <- c(unlist(t(aggregate(value~id, df, diff2)[, -1])))
df[order(as.numeric(rownames(df))),]

by:
df <- df[order(df$id, df$year), ]
diff2 <- function(x) diff(c(0, x))
df$actual <- unlist(by(df$value, df$id, diff2))
df[order(as.numeric(rownames(df))),]

plyr
df <- df[order(df$id, df$year), ]
df <- data.frame(temp=1:nrow(df), df)
library(plyr)
df <- ddply(df, .(id), transform, actual=diff2(value))
df[order(-df$year, df$temp),][, -1]

It gives you the final product of:
> df[order(as.numeric(rownames(df))),]
   id value year actual
1   1    21    3      5
2   2    26    3     16
3   3    26    3     14
4   4    26    3     10
5   5    29    3     14
6   1    16    2     10
7   2    10    2      5
8   3    12    2     10
9   4    16    2      7
10  5    15    2     13
11  1     6    1      6
12  2     5    1      5
13  3     2    1      2
14  4     9    1      9
15  5     2    1      2

EDIT:  Avoiding the Loop
May I suggest avoiding the loop and turning what I gave to you into a function (the by solution is the easiest one for me to work with) and sapply that to the two columns you desire.
set.seed(1234)  #make new data with another numeric column
x <- data.frame(id=1:5, value=sample(20:30, 5, replace=T), year=3)
y <- data.frame(id=1:5, value=sample(10:19, 5, replace=T), year=2)
z <- data.frame(id=1:5, value=sample(0:9, 5, replace=T), year=1)
df <- rbind(x, y, z)
df <- df.rep <- data.frame(df[, 1:2], new.var=df[, 2]+sample(1:5, nrow(df),
          replace=T), year=df[, 3])

df <- df[order(df$id, df$year), ]
diff2 <- function(x) diff(c(0, x))                   #function one
group.diff<- function(x) unlist(by(x, df$id, diff2)) #answer turned function
df <- data.frame(df, sapply(df[, 2:3], group.diff))  #apply group.diff to col 2:3
df[order(as.numeric(rownames(df))),]                 #reorder it

Of course you'd have to rename these unless you used transform as in:
df <- df[order(df$id, df$year), ]
diff2 <- function(x) diff(c(0, x))                   #function one
group.diff<- function(x) unlist(by(x, df$id, diff2)) #answer turned function
df <- transform(df, actual=group.diff(value), actual.new=group.diff(new.var))
df[order(as.numeric(rownames(df))),]

This would depend on how many variables you were doing this to.

A: 1) diff.zoo. With the zoo package its just a matter of converting it to zoo using split= and then performing the diff :
library(zoo)

zz <- zz0 <- read.zoo(df, split = "id", index = "year", FUN = identity)
zz[2:3, ] <- diff(zz)

It gives the following (in wide form rather than the long form you mentioned) where each column is an id and each row is a year minus the prior year:
> zz
   1  2  3  4  5
1  6  5  2  9  2
2 10  5 10  7 13
3  5 16 14 10 14

The wide form shown may actually be preferable but you can convert it to long form if you want that like this:
dt <- function(x) as.data.frame.table(t(x))
setNames(cbind(dt(zz), dt(zz0)[3]), c("id", "year", "value", "actual"))

This puts the years in ascending order which is the convention normally used in R.
2) rollapply.   Also using zoo this alternative uses a rolling calculation to add the actual column to your data.  It assumes the data is structured as you show with the same number of years in each group arranged in order:
df$actual <- rollapply(df$value, 6, partial = TRUE, align = "left",
   FUN = function(x) if (length(x) < 6) x[1] else x[1]-x[6])

3) subtraction.  Making the same assumptions as in the prior solution we can further simplify it to just this which subtracts from each value the value 5 positions hence:
transform(df, actual = value - c(tail(value, -5), rep(0, 5)))

or this variation:
transform(df, actual = replace(value, year > 1, -diff(ts(value), 5)))

EDIT: added rollapply and subtraction solutions.

A: Kind of hackish but keeping in place your wonderful Reduce you could add mock rows to your df for year 0:
mockRows <- data.frame(id = 1:5, value = 0, year = 0)
(df <- rbind(df, mockRows))
(df <- df[order(df$id, df$year), ])

(diffs <- lapply(split(df, df$id), function(x){diff(x$value)}))
(df <- df[df$year != 0,])

(df$actual <- Reduce(c, diffs)) # flatten the list of lists
df[order(as.numeric(rownames(df))),]

This is the output:
   id value year actual
1   1    21    3      5
2   2    26    3     16
3   3    26    3     14
4   4    26    3     10
5   5    29    3     14
6   1    16    2     10
7   2    10    2      5
8   3    12    2     10
9   4    16    2      7
10  5    15    2     13
11  1     6    1      6
12  2     5    1      5
13  3     2    1      2
14  4     9    1      9
15  5     2    1      2