Programs & Examples On #Blackberry os v4.5

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Array versus List<T>: When to use which?

Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.

For example,

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.

But suppose that

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

Drop data frame columns by name

Out of interest, this flags up one of R's weird multiple syntax inconsistencies. For example given a two-column data frame:

df <- data.frame(x=1, y=2)

This gives a data frame

subset(df, select=-y)

but this gives a vector

df[,-2]

This is all explained in ?[ but it's not exactly expected behaviour. Well at least not to me...

Convert string to number and add one

var first_value = '2';
// convert this string value into int
parseInt(first_value);

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

try this:

public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private CallBack callBack;

    public interface CallBack {
        void async( JSONObject jsonResult );
        void sync( JSONObject jsonResult );
        void progress( Integer... status );
        void cancel();
    }

    public SomAsyncTask(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected JSONObject doInBackground(String... strings) {

        JSONObject dataJson = null;

        //TODO query, get some dataJson

        if(this.callBack != null)
            this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD

        return dataJson;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        if(this.callBack != null)
            this.callBack.progress(values);// synchronize with MAIN LOOP THREAD

    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);

        if(this.callBack != null)
            this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();

        if(this.callBack != null)
            this.callBack.cancel();

    }
}

And usage example:

public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         final Context _localContext = getContext();
         SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {

                @Override
                public void async(JSONObject jsonResult) {//async thread
                    //some async process, e.g. send data to server...
                }

                @Override
                public void sync(JSONObject jsonResult) {//sync thread
                    //get result...

                    //get some resource of Activity variable...
                    Resources resources = _localContext.getResources();
                }

                @Override
                public void progress(Integer... status) {//sync thread
                    //e.g. change status progress bar...
                }

                @Override
                public void cancel() {

                }

            };

            new SomeAsyncTask( someCallBack )
                                .execute("someParams0", "someParams1", "someParams2");

    }

Temporarily disable all foreign key constraints

To disable foreign key constraints:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS 
(
  SELECT DISTINCT obj = 
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' 
    + QUOTENAME(OBJECT_NAME(parent_object_id)) 
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' NOCHECK CONSTRAINT ALL;
' FROM x;

EXEC sp_executesql @sql;

To re-enable:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS 
(
  SELECT DISTINCT obj = 
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' 
    + QUOTENAME(OBJECT_NAME(parent_object_id)) 
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' WITH CHECK CHECK CONSTRAINT ALL;
' FROM x;

EXEC sp_executesql @sql;

However, you will not be able to truncate the tables, you will have to delete from them in the right order. If you need to truncate them, you need to drop the constraints entirely, and re-create them. This is simple to do if your foreign key constraints are all simple, single-column constraints, but definitely more complex if there are multiple columns involved.

Here is something you can try. In order to make this a part of your SSIS package you'll need a place to store the FK definitions while the SSIS package runs (you won't be able to do this all in one script). So in some utility database, create a table:

CREATE TABLE dbo.PostCommand(cmd NVARCHAR(MAX));

Then in your database, you can have a stored procedure that does this:

DELETE other_database.dbo.PostCommand;

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id))
   + '.' + QUOTENAME(OBJECT_NAME(fk.parent_object_id)) 
   + ' ADD CONSTRAINT ' + fk.name + ' FOREIGN KEY (' 
   + STUFF((SELECT ',' + c.name
    FROM sys.columns AS c 
        INNER JOIN sys.foreign_key_columns AS fkc 
        ON fkc.parent_column_id = c.column_id
        AND fkc.parent_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
+ ') REFERENCES ' + 
QUOTENAME(OBJECT_SCHEMA_NAME(fk.referenced_object_id))
+ '.' + QUOTENAME(OBJECT_NAME(fk.referenced_object_id))
+ '(' + 
STUFF((SELECT ',' + c.name
    FROM sys.columns AS c 
        INNER JOIN sys.foreign_key_columns AS fkc 
        ON fkc.referenced_column_id = c.column_id
        AND fkc.referenced_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') + ');
' FROM sys.foreign_keys AS fk
WHERE OBJECTPROPERTY(parent_object_id, 'IsMsShipped') = 0;

INSERT other_database.dbo.PostCommand(cmd) SELECT @sql;

IF @@ROWCOUNT = 1
BEGIN
  SET @sql = N'';

  SELECT @sql += N'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(fk.parent_object_id)) 
    + ' DROP CONSTRAINT ' + fk.name + ';
  ' FROM sys.foreign_keys AS fk;

  EXEC sp_executesql @sql;
END

Now when your SSIS package is finished, it should call a different stored procedure, which does:

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = cmd FROM other_database.dbo.PostCommand;

EXEC sp_executesql @sql;

If you're doing all of this just for the sake of being able to truncate instead of delete, I suggest just taking the hit and running a delete. Maybe use bulk-logged recovery model to minimize the impact of the log. In general I don't see how this solution will be all that much faster than just using a delete in the right order.

In 2014 I published a more elaborate post about this here:

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

What is the best way to paginate results in SQL Server

   CREATE view vw_sppb_part_listsource as 
    select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (
      select 
          part.SPPB_PART_ID
          , 0 as is_rev
          , part.part_number 
          , part.init_id 
      from t_sppb_init_part part 
      left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
      where prev.SPPB_PART_ID is null 
      union 
      select 
          part.SPPB_PART_ID
          , 1 as is_rev
          , prev.part_number 
          , part.init_id 
      from t_sppb_init_part part 
      inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
    ) sppb_part

will restart idx when it comes to different init_id

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

How can I profile C++ code running on Linux?

Survey of C++ profiling techniques: gprof vs valgrind vs perf vs gperftools

In this answer, I will use several different tools to a analyze a few very simple test programs, in order to concretely compare how those tools work.

The following test program is very simple and does the following:

  • main calls fast and maybe_slow 3 times, one of the maybe_slow calls being slow

    The slow call of maybe_slow is 10x longer, and dominates runtime if we consider calls to the child function common. Ideally, the profiling tool will be able to point us to the specific slow call.

  • both fast and maybe_slow call common, which accounts for the bulk of the program execution

  • The program interface is:

    ./main.out [n [seed]]
    

    and the program does O(n^2) loops in total. seed is just to get different output without affecting runtime.

main.c

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

uint64_t __attribute__ ((noinline)) common(uint64_t n, uint64_t seed) {
    for (uint64_t i = 0; i < n; ++i) {
        seed = (seed * seed) - (3 * seed) + 1;
    }
    return seed;
}

uint64_t __attribute__ ((noinline)) fast(uint64_t n, uint64_t seed) {
    uint64_t max = (n / 10) + 1;
    for (uint64_t i = 0; i < max; ++i) {
        seed = common(n, (seed * seed) - (3 * seed) + 1);
    }
    return seed;
}

uint64_t __attribute__ ((noinline)) maybe_slow(uint64_t n, uint64_t seed, int is_slow) {
    uint64_t max = n;
    if (is_slow) {
        max *= 10;
    }
    for (uint64_t i = 0; i < max; ++i) {
        seed = common(n, (seed * seed) - (3 * seed) + 1);
    }
    return seed;
}

int main(int argc, char **argv) {
    uint64_t n, seed;
    if (argc > 1) {
        n = strtoll(argv[1], NULL, 0);
    } else {
        n = 1;
    }
    if (argc > 2) {
        seed = strtoll(argv[2], NULL, 0);
    } else {
        seed = 0;
    }
    seed += maybe_slow(n, seed, 0);
    seed += fast(n, seed);
    seed += maybe_slow(n, seed, 1);
    seed += fast(n, seed);
    seed += maybe_slow(n, seed, 0);
    seed += fast(n, seed);
    printf("%" PRIX64 "\n", seed);
    return EXIT_SUCCESS;
}

gprof

gprof requires recompiling the software with instrumentation, and it also uses a sampling approach together with that instrumentation. It therefore strikes a balance between accuracy (sampling is not always fully accurate and can skip functions) and execution slowdown (instrumentation and sampling are relatively fast techniques that don't slow down execution very much).

gprof is built-into GCC/binutils, so all we have to do is to compile with the -pg option to enable gprof. We then run the program normally with a size CLI parameter that produces a run of reasonable duration of a few seconds (10000):

gcc -pg -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
time ./main.out 10000

For educational reasons, we will also do a run without optimizations enabled. Note that this is useless in practice, as you normally only care about optimizing the performance of the optimized program:

gcc -pg -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out 10000

First, time tells us that the execution time with and without -pg were the same, which is great: no slowdown! I have however seen accounts of 2x - 3x slowdowns on complex software, e.g. as shown in this ticket.

Because we compiled with -pg, running the program produces a file gmon.out file containing the profiling data.

We can observe that file graphically with gprof2dot as asked at: Is it possible to get a graphical representation of gprof results?

sudo apt install graphviz
python3 -m pip install --user gprof2dot
gprof main.out > main.gprof
gprof2dot < main.gprof | dot -Tsvg -o output.svg

Here, the gprof tool reads the gmon.out trace information, and generates a human readable report in main.gprof, which gprof2dot then reads to generate a graph.

The source for gprof2dot is at: https://github.com/jrfonseca/gprof2dot

We observe the following for the -O0 run:

enter image description here

and for the -O3 run:

enter image description here

The -O0 output is pretty much self-explanatory. For example, it shows that the 3 maybe_slow calls and their child calls take up 97.56% of the total runtime, although execution of maybe_slow itself without children accounts for 0.00% of the total execution time, i.e. almost all the time spent in that function was spent on child calls.

TODO: why is main missing from the -O3 output, even though I can see it on a bt in GDB? Missing function from GProf output I think it is because gprof is also sampling based in addition to its compiled instrumentation, and the -O3 main is just too fast and got no samples.

I choose SVG output instead of PNG because the SVG is searchable with Ctrl + F and the file size can be about 10x smaller. Also, the width and height of the generated image can be humoungous with tens of thousands of pixels for complex software, and GNOME eog 3.28.1 bugs out in that case for PNGs, while SVGs get opened by my browser automatically. gimp 2.8 worked well though, see also:

but even then, you will be dragging the image around a lot to find what you want, see e.g. this image from a "real" software example taken from this ticket:

enter image description here

Can you find the most critical call stack easily with all those tiny unsorted spaghetti lines going over one another? There might be better dot options I'm sure, but I don't want to go there now. What we really need is a proper dedicated viewer for it, but I haven't found one yet:

You can however use the color map to mitigate those problems a bit. For example, on the previous huge image, I finally managed to find the critical path on the left when I made the brilliant deduction that green comes after red, followed finally by darker and darker blue.

Alternatively, we can also observe the text output of the gprof built-in binutils tool which we previously saved at:

cat main.gprof

By default, this produces an extremely verbose output that explains what the output data means. Since I can't explain better than that, I'll let you read it yourself.

Once you have understood the data output format, you can reduce verbosity to show just the data without the tutorial with the -b option:

gprof -b main.out

In our example, outputs were for -O0:

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls   s/call   s/call  name    
100.35      3.67     3.67   123003     0.00     0.00  common
  0.00      3.67     0.00        3     0.00     0.03  fast
  0.00      3.67     0.00        3     0.00     1.19  maybe_slow

            Call graph


granularity: each sample hit covers 2 byte(s) for 0.27% of 3.67 seconds

index % time    self  children    called     name
                0.09    0.00    3003/123003      fast [4]
                3.58    0.00  120000/123003      maybe_slow [3]
[1]    100.0    3.67    0.00  123003         common [1]
-----------------------------------------------
                                                 <spontaneous>
[2]    100.0    0.00    3.67                 main [2]
                0.00    3.58       3/3           maybe_slow [3]
                0.00    0.09       3/3           fast [4]
-----------------------------------------------
                0.00    3.58       3/3           main [2]
[3]     97.6    0.00    3.58       3         maybe_slow [3]
                3.58    0.00  120000/123003      common [1]
-----------------------------------------------
                0.00    0.09       3/3           main [2]
[4]      2.4    0.00    0.09       3         fast [4]
                0.09    0.00    3003/123003      common [1]
-----------------------------------------------

Index by function name

   [1] common                  [4] fast                    [3] maybe_slow

and for -O3:

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  us/call  us/call  name    
100.52      1.84     1.84   123003    14.96    14.96  common

            Call graph


granularity: each sample hit covers 2 byte(s) for 0.54% of 1.84 seconds

index % time    self  children    called     name
                0.04    0.00    3003/123003      fast [3]
                1.79    0.00  120000/123003      maybe_slow [2]
[1]    100.0    1.84    0.00  123003         common [1]
-----------------------------------------------
                                                 <spontaneous>
[2]     97.6    0.00    1.79                 maybe_slow [2]
                1.79    0.00  120000/123003      common [1]
-----------------------------------------------
                                                 <spontaneous>
[3]      2.4    0.00    0.04                 fast [3]
                0.04    0.00    3003/123003      common [1]
-----------------------------------------------

Index by function name

   [1] common

As a very quick summary for each section e.g.:

                0.00    3.58       3/3           main [2]
[3]     97.6    0.00    3.58       3         maybe_slow [3]
                3.58    0.00  120000/123003      common [1]

centers around the function that is left indented (maybe_flow). [3] is the ID of that function. Above the function, are its callers, and below it the callees.

For -O3, see here like in the graphical output that maybe_slow and fast don't have a known parent, which is what the documentation says that <spontaneous> means.

I'm not sure if there is a nice way to do line-by-line profiling with gprof: `gprof` time spent in particular lines of code

valgrind callgrind

valgrind runs the program through the valgrind virtual machine. This makes the profiling very accurate, but it also produces a very large slowdown of the program. I have also mentioned kcachegrind previously at: Tools to get a pictorial function call graph of code

callgrind is the valgrind's tool to profile code and kcachegrind is a KDE program that can visualize cachegrind output.

First we have to remove the -pg flag to go back to normal compilation, otherwise the run actually fails with Profiling timer expired, and yes, this is so common that I did and there was a Stack Overflow question for it.

So we compile and run as:

sudo apt install kcachegrind valgrind
gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
time valgrind --tool=callgrind valgrind --dump-instr=yes \
  --collect-jumps=yes ./main.out 10000

I enable --dump-instr=yes --collect-jumps=yes because this also dumps information that enables us to view a per assembly line breakdown of performance, at a relatively small added overhead cost.

Off the bat, time tells us that the program took 29.5 seconds to execute, so we had a slowdown of about 15x on this example. Clearly, this slowdown is going to be a serious limitation for larger workloads. On the "real world software example" mentioned here, I observed a slowdown of 80x.

The run generates a profile data file named callgrind.out.<pid> e.g. callgrind.out.8554 in my case. We view that file with:

kcachegrind callgrind.out.8554

which shows a GUI that contains data similar to the textual gprof output:

enter image description here

Also, if we go on the bottom right "Call Graph" tab, we see a call graph which we can export by right clicking it to obtain the following image with unreasonable amounts of white border :-)

enter image description here

I think fast is not showing on that graph because kcachegrind must have simplified the visualization because that call takes up too little time, this will likely be the behavior you want on a real program. The right click menu has some settings to control when to cull such nodes, but I couldn't get it to show such a short call after a quick attempt. If I click on fast on the left window, it does show a call graph with fast, so that stack was actually captured. No one had yet found a way to show the complete graph call graph: Make callgrind show all function calls in the kcachegrind callgraph

TODO on complex C++ software, I see some entries of type <cycle N>, e.g. <cycle 11> where I'd expect function names, what does that mean? I noticed there is a "Cycle Detection" button to toggle that on and off, but what does it mean?

perf from linux-tools

perf seems to use exclusively Linux kernel sampling mechanisms. This makes it very simple to setup, but also not fully accurate.

sudo apt install linux-tools
time perf record -g ./main.out 10000

This added 0.2s to execution, so we are fine time-wise, but I still don't see much of interest, after expanding the common node with the keyboard right arrow:

Samples: 7K of event 'cycles:uppp', Event count (approx.): 6228527608     
  Children      Self  Command   Shared Object     Symbol                  
-   99.98%    99.88%  main.out  main.out          [.] common              
     common                                                               
     0.11%     0.11%  main.out  [kernel]          [k] 0xffffffff8a6009e7  
     0.01%     0.01%  main.out  [kernel]          [k] 0xffffffff8a600158  
     0.01%     0.00%  main.out  [unknown]         [k] 0x0000000000000040  
     0.01%     0.00%  main.out  ld-2.27.so        [.] _dl_sysdep_start    
     0.01%     0.00%  main.out  ld-2.27.so        [.] dl_main             
     0.01%     0.00%  main.out  ld-2.27.so        [.] mprotect            
     0.01%     0.00%  main.out  ld-2.27.so        [.] _dl_map_object      
     0.01%     0.00%  main.out  ld-2.27.so        [.] _xstat              
     0.00%     0.00%  main.out  ld-2.27.so        [.] __GI___tunables_init
     0.00%     0.00%  main.out  [unknown]         [.] 0x2f3d4f4944555453  
     0.00%     0.00%  main.out  [unknown]         [.] 0x00007fff3cfc57ac  
     0.00%     0.00%  main.out  ld-2.27.so        [.] _start              

So then I try to benchmark the -O0 program to see if that shows anything, and only now, at last, do I see a call graph:

Samples: 15K of event 'cycles:uppp', Event count (approx.): 12438962281   
  Children      Self  Command   Shared Object     Symbol                  
+   99.99%     0.00%  main.out  [unknown]         [.] 0x04be258d4c544155  
+   99.99%     0.00%  main.out  libc-2.27.so      [.] __libc_start_main   
-   99.99%     0.00%  main.out  main.out          [.] main                
   - main                                                                 
      - 97.54% maybe_slow                                                 
           common                                                         
      - 2.45% fast                                                        
           common                                                         
+   99.96%    99.85%  main.out  main.out          [.] common              
+   97.54%     0.03%  main.out  main.out          [.] maybe_slow          
+    2.45%     0.00%  main.out  main.out          [.] fast                
     0.11%     0.11%  main.out  [kernel]          [k] 0xffffffff8a6009e7  
     0.00%     0.00%  main.out  [unknown]         [k] 0x0000000000000040  
     0.00%     0.00%  main.out  ld-2.27.so        [.] _dl_sysdep_start    
     0.00%     0.00%  main.out  ld-2.27.so        [.] dl_main             
     0.00%     0.00%  main.out  ld-2.27.so        [.] _dl_lookup_symbol_x 
     0.00%     0.00%  main.out  [kernel]          [k] 0xffffffff8a600158  
     0.00%     0.00%  main.out  ld-2.27.so        [.] mmap64              
     0.00%     0.00%  main.out  ld-2.27.so        [.] _dl_map_object      
     0.00%     0.00%  main.out  ld-2.27.so        [.] __GI___tunables_init
     0.00%     0.00%  main.out  [unknown]         [.] 0x552e53555f6e653d  
     0.00%     0.00%  main.out  [unknown]         [.] 0x00007ffe1cf20fdb  
     0.00%     0.00%  main.out  ld-2.27.so        [.] _start              

TODO: what happened on the -O3 execution? Is it simply that maybe_slow and fast were too fast and did not get any samples? Does it work well with -O3 on larger programs that take longer to execute? Did I miss some CLI option? I found out about -F to control the sample frequency in Hertz, but I turned it up to the max allowed by default of -F 39500 (could be increased with sudo) and I still don't see clear calls.

One cool thing about perf is the FlameGraph tool from Brendan Gregg which displays the call stack timings in a very neat way that allows you to quickly see the big calls. The tool is available at: https://github.com/brendangregg/FlameGraph and is also mentioned on his perf tutorial at: http://www.brendangregg.com/perf.html#FlameGraphs When I ran perf without sudo I got ERROR: No stack counts found so for now I'll be doing it with sudo:

git clone https://github.com/brendangregg/FlameGraph
sudo perf record -F 99 -g -o perf_with_stack.data ./main.out 10000
sudo perf script -i perf_with_stack.data | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > flamegraph.svg

but in such a simple program the output is not very easy to understand, since we can't easily see neither maybe_slow nor fast on that graph:

enter image description here

On the a more complex example it becomes clear what the graph means:

enter image description here

TODO there are a log of [unknown] functions in that example, why is that?

Another perf GUI interfaces which might be worth it include:

  • Eclipse Trace Compass plugin: https://www.eclipse.org/tracecompass/

    But this has the downside that you have to first convert the data to the Common Trace Format, which can be done with perf data --to-ctf, but it needs to be enabled at build time/have perf new enough, either of which is not the case for the perf in Ubuntu 18.04

  • https://github.com/KDAB/hotspot

    The downside of this is that there seems to be no Ubuntu package, and building it requires Qt 5.10 while Ubuntu 18.04 is at Qt 5.9.

gperftools

Previously called "Google Performance Tools", source: https://github.com/gperftools/gperftools Sample based.

First install gperftools with:

sudo apt install google-perftools

Then, we can enable the gperftools CPU profiler in two ways: at runtime, or at build time.

At runtime, we have to pass set the LD_PRELOAD to point to libprofiler.so, which you can find with locate libprofiler.so, e.g. on my system:

gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libprofiler.so \
  CPUPROFILE=prof.out ./main.out 10000

Alternatively, we can build the library in at link time, dispensing passing LD_PRELOAD at runtime:

gcc -Wl,--no-as-needed,-lprofiler,--as-needed -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
CPUPROFILE=prof.out ./main.out 10000

See also: gperftools - profile file not dumped

The nicest way to view this data I've found so far is to make pprof output the same format that kcachegrind takes as input (yes, the Valgrind-project-viewer-tool) and use kcachegrind to view that:

google-pprof --callgrind main.out prof.out  > callgrind.out
kcachegrind callgrind.out

After running with either of those methods, we get a prof.out profile data file as output. We can view that file graphically as an SVG with:

google-pprof --web main.out prof.out

enter image description here

which gives as a familiar call graph like other tools, but with the clunky unit of number of samples rather than seconds.

Alternatively, we can also get some textual data with:

google-pprof --text main.out prof.out

which gives:

Using local file main.out.
Using local file prof.out.
Total: 187 samples
     187 100.0% 100.0%      187 100.0% common
       0   0.0% 100.0%      187 100.0% __libc_start_main
       0   0.0% 100.0%      187 100.0% _start
       0   0.0% 100.0%        4   2.1% fast
       0   0.0% 100.0%      187 100.0% main
       0   0.0% 100.0%      183  97.9% maybe_slow

See also: How to use google perf tools

Instrument your code with raw perf_event_open syscalls

I think this is the same underlying subsystem that perf uses, but you could of course attain even greater control by explicitly instrumenting your program at compile time with events of interest.

This is be too hardcore for most people, but it's kind of fun. Minimal runnable example at: Quick way to count number of instructions executed in a C program

Tested in Ubuntu 18.04, gprof2dot 2019.11.30, valgrind 3.13.0, perf 4.15.18, Linux kernel 4.15.0, FLameGraph 1a0dc6985aad06e76857cf2a354bd5ba0c9ce96b, gperftools 2.5-2.

Intel VTune

https://en.wikipedia.org/wiki/VTune

This is closed source and x86-only, but it is likely to be amazing from what I've heard. I'm not sure how free it is to use, but it seems to be free to download.

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

Select Tomcat server in Targeted Runtime

Project->Properties->Targeted Runtimes (Select your Tomcat Server)

Cannot serve WCF services in IIS on Windows 8

Seemed to be a no brainer; the WCF service should be enabled using Programs and Features -> Turn Windows features on or off in the Control Panel. Go to .NET Framework Advanced Services -> WCF Services and enable HTTP Activation as described in this blog post on mdsn.

From the command prompt (as admin), you can run:

C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45

If you get an error then use the below

C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation45

jQuery check if <input> exists and has a value

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

_x000D_
_x000D_
jQuery.expr[':'].hasValue = function(el) {_x000D_
  return el.value != "";_x000D_
};_x000D_
_x000D_
_x000D_
var data = $("form input:hasValue").serialize();_x000D_
console.log(data)_x000D_
_x000D_
_x000D_
var elHasValue = $("[name='LastName']").is(":hasValue");_x000D_
console.log(elHasValue)
_x000D_
label { display: block; margin-top:10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
  <label>_x000D_
    First Name:_x000D_
    <input type="text" name="FirstName" value="Frida" />_x000D_
  </label>_x000D_
_x000D_
  <label>_x000D_
    Last Name:_x000D_
    <input type="text" name="LastName" />_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Further Reading:

OpenCV Python rotate image by X degrees around specific point

import imutils

vs = VideoStream(src=0).start()
...

while (1):
   frame = vs.read()
   ...

   frame = imutils.rotate(frame, 45)

More: https://github.com/jrosebr1/imutils

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

If like me you recently moved certain classes to different packages ect. and you use android navigation. Make sure to change the argType to you match you new package address. from:

app:argType="com.example.app.old.Item" 

to:

app:argType="com.example.app.new.Item" 

How do I "commit" changes in a git submodule?

A submodule is its own repo/work-area, with its own .git directory.

So, first commit/push your submodule's changes:

$ cd path/to/submodule
$ git add <stuff>
$ git commit -m "comment"
$ git push

Then, update your main project to track the updated version of the submodule:

$ cd /main/project
$ git add path/to/submodule
$ git commit -m "updated my submodule"
$ git push

phpMyAdmin - The MySQL Extension is Missing

Just as others stated you need to remove the ';' from:
;extension=php_mysql.dll and
;extension=php_mysqli.dll

in your php.ini to enable mysql and mysqli extensions. But MOST IMPORTANT of all, you should set the extension_dir in your php.ini to point to your extensions directory. The default most of the time is "ext". You should change it to the absolute path to the extensions folder. i.e. if you have your xampp installed on drive C, then C:/xampp/php/ext is the absolute path to the ext folder, and It should work like a charm!

How can I set the form action through JavaScript?

Setting form action after selection of option using JavaScript

<script>
    function onSelectedOption(sel) {
        if ((sel.selectedIndex) == 0) {
            document.getElementById("edit").action =
            "http://www.example.co.uk/index.php";
            document.getElementById("edit").submit();
        }
        else
        {
            document.getElementById("edit").action =
            "http://www.example.co.uk/different.php";
            document.getElementById("edit").submit();
        }
    }
</script>

<form name="edit" id="edit" action="" method="GET">
    <input type="hidden" name="id" value="{ID}" />
</form>

<select name="option" id="option" onchange="onSelectedOption(this);">
    <option name="contactBuyer">Edit item</option>
    <option name="relist">End listing</option>
</select>

Codesign error: Provisioning profile cannot be found after deleting expired profile

Select the lines in codesigning that are blank under Any iOS SDK and select the right certificate.

Pointer vs. Reference

This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.

While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.

Looping over arrays, printing both index and value

In bash 4, you can use associative arrays:

declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
    echo "key: $key, value: ${foo[$key]}"
done

# output
# $ key: 0, value bar.
# $ key: 35, value baz.

In bash 3, this works (also works in zsh):

map=( )
map+=("0:bar")
map+=("35:baz")

for keyvalue in "${map[@]}" ; do
    key=${keyvalue%%:*}
    value=${keyvalue#*:}
    echo "key: $key, value $value."
done

The calling thread cannot access this object because a different thread owns it

I kept getting the error when I added cascading comboboxes to my WPF application, and resolved the error by using this API:

    using System.Windows.Data;

    private readonly object _lock = new object();
    private CustomObservableCollection<string> _myUiBoundProperty;
    public CustomObservableCollection<string> MyUiBoundProperty
    {
        get { return _myUiBoundProperty; }
        set
        {
            if (value == _myUiBoundProperty) return;
            _myUiBoundProperty = value;
            NotifyPropertyChanged(nameof(MyUiBoundProperty));
        }
    }

    public MyViewModelCtor(INavigationService navigationService) 
    {
       // Other code...
       BindingOperations.EnableCollectionSynchronization(AvailableDefectSubCategories, _lock );

    }

For details, please see https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Windows.Data.BindingOperations.EnableCollectionSynchronization);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.7);k(DevLang-csharp)&rd=true

Select rows where column is null

Do you mean something like:

SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL

?

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

Dropdown select with images

You don't even need javascript to do this!

I hope this got you intrigued so here it goes. First, the html structure:

<div id="image-dropdown">
    <input type="radio" id="line1" name="line-style" value="1" checked="checked" />
    <label for="line1"></label>
    <input type="radio" id="line2" name="line-style" value="2" />
    <label for="line2"></label>
    ...
</div>

Whaaat? Radio buttons? Correct. We'll style them to look like a dropdown list with images, because that's what you're after! The trick is in knowing that when labels are correctly linked to inputs (that "for" attribute and target element id), the input will implicitly become active; click on a label = click on a radio button. Here comes comes slightly abbreviated css with comments inline:

#image-dropdown {
    /*style the "box" in its minimzed state*/
    border:1px solid black; width:200px; height:50px; overflow:hidden;
    /*animate the dropdown collapsing*/
    transition: height 0.1s;
}
#image-dropdown:hover {
    /*when expanded, the dropdown will get native means of scrolling*/
    height:200px; overflow-y:scroll;
    /*animate the dropdown expanding*/
    transition: height 0.5s;
}
#image-dropdown input {
    /*hide the nasty default radio buttons!*/
    position:absolute;top:0;left:0;opacity:0;
}
#image-dropdown label {
    /*style the labels to look like dropdown options*/
    display:none; margin:2px; height:46px; opacity:0.2; 
    background:url("http://www.google.com/images/srpr/logo3w.png") 50% 50%;}
#image-dropdown:hover label{
    /*this is how labels render in the "expanded" state.
     we want to see only the selected radio button in the collapsed menu,
     and all of them when expanded*/
    display:block;
}
#image-dropdown input:checked + label {
    /*tricky! labels immediately following a checked radio button
      (with our markup they are semantically related) should be fully opaque
      and visible even in the collapsed menu*/
    opacity:1 !important; display:block;
}

Full example here: http://jsfiddle.net/NDCSR/1/

NB1: you'll probably need to use it with position:absolute inside a container with position:relative +high z-index.

NB2: when adding more backgrounds for individual line styles, consider having the selectors based on the "for" attribute of the label like so:

label[for=linestyle2] {background-image:url(...);}

Make an image width 100% of parent div, but not bigger than its own width

Found this post on a Google search, and it solved my issue thanks to @jwal reply, but I made one addition to his solution.

img.content.x700 {
  width: auto !important; /*override the width below*/
  width: 100%;
  max-width: 678px;
  float: left;
  clear: both;
}

With the above I changed the max-width to the dimensions of the content container that my image is in. In this case it is: container width - padding - boarder = max width

This way my image won't break out of the containing div, and I can still float the image within the content div.

I've tested in IE 9, FireFox 18.0.2 and Chrome 25.0.1364.97, Safari iOS and seems to work.

Additional: I tested this on an image 1024px wide displayed at 678px (the max width), and an image 500px wide displayed at 500px (width of the image).

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");

How to find locked rows in Oracle

you can find the locked tables in oralce by querying with following query

    select
   c.owner,
   c.object_name,
   c.object_type,
   b.sid,
   b.serial#,
   b.status,
   b.osuser,
   b.machine
from
   v$locked_object a ,
   v$session b,
   dba_objects c
where
   b.sid = a.session_id
and
   a.object_id = c.object_id;

How to use Sublime over SSH

Depending on your exact needs, you may consider using BitTorrent Sync. Create a shared folder on your home PC and your work PC. Edit the files on your home PC (using Sublime or whatever you like), and they will sync automatically when you save. BitTorrent Sync does not rely on a central server storing the files (a la Dropbox and the like), so you should in theory be clear of any issues due to a third party storing sensitive info.

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

Tricks to manage the available memory in an R session

If you are working on Linux and want to use several processes and only have to do read operations on one or more large objects use makeForkCluster instead of a makePSOCKcluster. This also saves you the time sending the large object to the other processes.

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

how can the textbox width be reduced?

<input type="text" style="width:50px;"/>

Remove all stylings (border, glow) from textarea

if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important

Python Decimals format

Just use Python's standard string formatting methods:

>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'

If you are using a Python version under 2.6, use

>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'

one line if statement in php

Use ternary operator:

echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

echo (($test != '') ?: $redText); //this will not work properly for this case

Laravel Blade html image

In Laravel 5.x you can use laravelcollective/html and the syntax:

{!! Html::image('img/logo.png') !!}

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Similar to a few posts prior - I went to SDK Manager and uninstalled v20 and version L. Then I installed version 19 and this problem was resolved and I could debug using my android device, no errors.

insert echo into the specific html element like div which has an id or class

Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this

echo '<div>' .$row['name']. '</div>' ;

and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this

echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;

Volley JsonObjectRequest Post request not working

I had the same issue once, the empty POST array is caused due a redirection of the request (on your server side), fix the URL so it doesn't have to be redirected when it hits the server. For Example, if https is forced using the .htaccess file on your server side app, make sure your client request has the "https://" prefix. Usually when a redirect happens the POST array is lost. I Hope this helps!

How to select data of a table from another database in SQL Server?

I've used this before to setup a query against another server and db via linked server:

EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'

per the comment above:

select * from [server].[database].[schema].[table]

e.g.

select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

WAMP 403 Forbidden message on Windows 7

The access to your Apache server is forbidden from addresses other than 127.0.0.1 in httpd.conf (Apache's config file) :

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Directory>

The same goes for your PHPMyAdmin access, the config file is phpmyadmin.conf :

<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from 127.0.0.1
</Directory>

You can set them to allow connections from all IP addresses like follows :

AllowOverride All
Order allow,deny
Allow from all

C# How to change font of a label

Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Check the constructor of the Font class for further options.

Get value when selected ng-option changes

I have tried some solutions,but here is basic production snippet. Please, pay attention to console output during quality assurance of this snippet.

Mark Up :

<!DOCTYPE html>
<html ng-app="appUp">
<head>
<title>
  Angular Select snippet
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

</head>


<body ng-controller="upController">

<div  class="container">

 <div class="row">
 <div class="col-md-4">

 </div> 
 <div class="col-md-3">
    <div class="form-group">
    <select name="slct" id="slct" class="form-control" ng-model="selBrand" ng-change="Changer(selBrand)" ng-options="brand as brand.name for brand in stock">
    <option value="">
        Select Brand
    </option>
    </select>
    </div>

    <div class="form-group">
    <input type="hidden" name="delimiter" value=":" ng-model="delimiter" />
    <input type="hidden" name="currency" value="$" ng-model="currency" />
    <span>
     {{selBrand.name}}{{delimiter}}{{selBrand.price}}{{currency}}
    </span>
    </div>

 </div> 
 <div class="col-md-4">

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

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">
</script>
<script src="js/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script src="js/main.js"></script>
</body>

</html>

Code:

var c = console;

var d = document;


 var app = angular.module('appUp',[]).controller('upController',function($scope){

    $scope.stock = [{
     name:"Adidas",
     price:420      
    },
    {
     name:"Nike",
     price:327      
    },
    {
     name:"Clark",
     price:725      
    }
    ];//data 



    $scope.Changer = function(){
     if($scope.selBrand){ 
     c.log("brand:"+$scope.selBrand.name+",price:"+$scope.selBrand.price);
     $scope.currency = "$";
     $scope.delimiter = ":";
     }
     else{

        $scope.currency = "";
        $scope.delimiter = "";
        c.clear();
     }
    }; // onchange handler

 });

Explanation: important point here is null check of the changed value, i.e. if value is 'undefined' or 'null' we should to handle this situation.

How to correctly catch change/focusOut event on text input in React.js?

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

The project type is not supported by this installation

You could also try to run the following command:

devenv /ResetSkipPkgs

Determine if variable is defined in Python

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

jQuery - selecting elements from inside a element

You can use any one these [starting from the fastest]

$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")

Take a look

Calculate difference in keys contained in two Python dictionaries

Not sure if it is still relevant but I came across this problem, my situation i just needed to return a dictionary of the changes for all nested dictionaries etc etc. Could not find a good solution out there but I did end up writing a simple function to do this. Hope this helps,

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

I got openCV installed smoothly in my mac by:

$ brew install opencv
$ brew link --overwrite --dry-run opencv // to force linking
$ pip3 install opencv-contrib-python

I got it at windows 10 using:

c:\> pip3 install opencv-python
c:\> pip3 install opencv-contrib-python

Then I got it tested by

$ python3
Python 3.7.3 (default, Mar 27 2019, 09:23:15) 
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.0'
>>> exit()

Get the number of rows in a HTML table

var x = document.getElementById("myTable").rows.length;

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

How to check if a variable exists in a FreeMarker template?

To check if the value exists:

[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>

Quickly create large file on a Windows system

I was searching for a way to generate large files with data, not just sparse file. Came across the below technique:

If you want to create a file with real data then you can use the below command line script.

echo "This is just a sample line appended to create a big file.. " > dummy.txt
for /L %i in (1,1,14) do type dummy.txt >> dummy.txt

(Run the above two commands one after another or you can add them to a batch file.)

The above commands create a 1 MB file dummy.txt within few seconds...

How to add a downloaded .box file to Vagrant?

Solution for Windows:

  • Open the cmd or powershell as admin
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box 'name_of_my_box.box'
  • vagrant box list should show the new box in the list

Solution for MAC:

  • Open terminal
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box "./name_of_my_box.box"
  • vagrant box list should show the new box in the list

Getting list of files in documents folder

Simple and dynamic solution (Swift 5):

extension FileManager {

  class func directoryUrl() -> URL? {
      let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
      return paths.first
  }

  class func allRecordedData() -> [URL]? {
     if let documentsUrl = FileManager.directoryUrl() {
        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
            return directoryContents.filter{ $0.pathExtension == "m4a" }
        } catch {
            return nil
        }
     }
     return nil
  }}

Why is my CSS bundling not working with a bin deployed MVC4 app?

As an addendum to the existing answers, none of which worked for me I found my solution HERE:

https://bundletransformer.codeplex.com/discussions/429707

The solution was to

  1. right click the .less files in visual studio
  2. Select properties
  3. Mark the Build Action as Content
  4. Redeploy

I did NOT need to remove extensionless handlers (as can be found in other solutions on the internet)

I did NOT have to add the <add name="BundleModule" type="System.Web.Optimization.BundleModule" /> web.config setting.

Hope this helps!

compareTo() vs. equals()

Equals -

1- Override the GetHashCode method to allow a type to work correctly in a hash table.

2- Do not throw an exception in the implementation of an Equals method. Instead, return false for a null argument.

3-

  x.Equals(x) returns true.

  x.Equals(y) returns the same value as y.Equals(x).

  (x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true.

Successive invocations of x.Equals(y) return the same value as long as the object referenced by x and y are not modified.

x.Equals(null) returns false.

4- For some kinds of objects, it is desirable to have Equals test for value equality instead of referential equality. Such implementations of Equals return true if the two objects have the same value, even if they are not the same instance.

For Example -

   Object obj1 = new Object();
   Object obj2 = new Object();
   Console.WriteLine(obj1.Equals(obj2));
   obj1 = obj2; 
   Console.WriteLine(obj1.Equals(obj2)); 

Output :-

False
True

while compareTo -

Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

It returns -

Less than zero - This instance precedes obj in the sort order. Zero - This instance occurs in the same position in the sort order as obj. Greater than zero - This instance follows obj in the sort order.

It can throw ArgumentException if object is not the same type as instance.

For example you can visit here.

So I suggest better to use Equals in place of compareTo.

How do I view events fired on an element in Chrome DevTools?

You can use monitorEvents function.

Just inspect your element (right mouse click ? Inspect on visible element or go to Elements tab in Chrome Developer Tools and select wanted element) then go to Console tab and write:

monitorEvents($0)

Now when you move mouse over this element, focus or click it, the name of the fired event will be displayed with its data.

To stop getting this data just write this to console:

unmonitorEvents($0)

$0 is just the last DOM element selected by Chrome Developer Tools. You can pass any other DOM object there (for example result of getElementById or querySelector).

You can also specify event "type" as second parameter to narrow monitored events to some predefined set. For example:

monitorEvents(document.body, 'mouse')

List of this available types is here.

I made a small gif that illustrates how this feature works:

usage of monitorEvents function

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

SQL to generate a list of numbers from 1 to 100

You could use XMLTABLE:

SELECT rownum
FROM XMLTABLE('1 to 100');

-- alternatively(useful for generating range i.e. 10-20)
SELECT (COLUMN_VALUE).GETNUMBERVAL() AS NUM
FROM XMLTABLE('1 to 100');

DBFiddle Demo

Multiple aggregate functions in HAVING clause

Something like this?

HAVING COUNT(caseID) > 2
AND COUNT(caseID) < 4

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

Using Python, find anagrams for a list of words

There are multiple solutions to this problem:

  1. Classic approach

    First, let's consider what defines an anagram: two words are anagrams of each other if they consist of the same set of letters and each letter appears exactly the same number or time in both words. This is basically a histogram of letters count of each word. This is a perfect use case for collections.Counter data structure (see docs). The algorithms is as follows:

    • Build a dictionary where keys would be histograms and values would be lists of words that have this histogram.
    • For each word build it's histogram and add it to the list that corresponds to this histogram.
    • Output list of dictionary values.

    Here is the code:

    from collections import Counter, defaultdict
    
    def anagram(words):
        anagrams = defaultdict(list)
        for word in words:
            histogram = tuple(Counter(word).items()) # build a hashable histogram
            anagrams[histogram].append(word)
        return list(anagrams.values())
    
    keywords = ("hi", "hello", "bye", "helol", "abc", "cab", 
                    "bac", "silenced", "licensed", "declines")
    
    print(anagram(keywords))
    

    Note that constructing Counter is O(l), while sorting each word is O(n*log(l)) where l is the length of the word.

  2. Solving anagrams using prime numbers

    This is a more advanced solution, that relies on the "multiplicative uniqueness" of prime numbers. You can refer to this SO post: Comparing anagrams using prime numbers, and here is a sample python implementation.

Java: Why is the Date constructor deprecated, and what do I use instead?

new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();

(the pre-Java-8 way)

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Cloud Firestore collection count

No, there is no built-in support for aggregation queries right now. However there are a few things you could do.

The first is documented here. You can use transactions or cloud functions to maintain aggregate information:

This example shows how to use a function to keep track of the number of ratings in a subcollection, as well as the average rating.

exports.aggregateRatings = firestore
  .document('restaurants/{restId}/ratings/{ratingId}')
  .onWrite(event => {
    // Get value of the newly added rating
    var ratingVal = event.data.get('rating');

    // Get a reference to the restaurant
    var restRef = db.collection('restaurants').document(event.params.restId);

    // Update aggregations in a transaction
    return db.transaction(transaction => {
      return transaction.get(restRef).then(restDoc => {
        // Compute new number of ratings
        var newNumRatings = restDoc.data('numRatings') + 1;

        // Compute new average rating
        var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings');
        var newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;

        // Update restaurant info
        return transaction.update(restRef, {
          avgRating: newAvgRating,
          numRatings: newNumRatings
        });
      });
    });
});

The solution that jbb mentioned is also useful if you only want to count documents infrequently. Make sure to use the select() statement to avoid downloading all of each document (that's a lot of bandwidth when you only need a count). select() is only available in the server SDKs for now so that solution won't work in a mobile app.

Python not working in command prompt?

Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:

  1. Press the windows key.
  2. Type "system env". Press enter.
  3. Press alt + n
  4. Press alt + e
  5. Press right, and then ; (that's a semicolon)
  6. Without adding a space, type this at the end: C:\Python27
  7. Hit enter twice. Hit esc.
  8. Use windows key + r to bring up the run dialog. Type in python and press enter.

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

Spring Boot Configure and Use Two DataSources

# Here '1stDB' is the database name
spring.datasource.url=jdbc:mysql://localhost/A
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


# Here '2ndDB' is the database name
spring.second-datasourcee.url=jdbc:mysql://localhost/B
spring.second-datasource.username=root
spring.second-datasource.password=root
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver


    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.second-datasource")
    public DataSource secondDataSource() {
       return DataSourceBuilder.create().build();
    }

How to make --no-ri --no-rdoc the default for gem install?

Step by steps:

To create/edit the .gemrc file from the terminal:

vi  ~/.gemrc

You will open a editor called vi. paste in:

gem: --no-ri --no-rdoc

click 'esc'-button.

type in:

:exit

You can check if everything is correct with this command:

sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc

Execute SQL script from command line

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

what you have is fine - however to save some typing, you can simply use for your data


data: $('#formId').serialize()

see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.

clientHeight/clientWidth returning different values on different browsers

The equivalent of offsetHeight and offsetWidth in jQuery is $(window).width(), $(window).height() It's not the clientHeight and clientWidth

What are the differences between the BLOB and TEXT datatypes in MySQL?

A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field

L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.

Reference: http://dev.mysql.com/doc/refman/5.0/en/blob.html

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

Getting the array length of a 2D array in Java

Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:

if (row > 0) col = test[0].length;

What is the documents directory (NSDocumentDirectory)?

It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:

extension FileManager {
    static var documentDir : URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }
}

Remove lines that contain certain string

Regex is a little quicker than the accepted answer (for my 23 MB test file) that I used. But there isn't a lot in it.

import re

bad_words = ['bad', 'naughty']

regex = f"^.*(:{'|'.join(bad_words)}).*\n"
subst = ""

with open('oldfile.txt') as oldfile:
    lines = oldfile.read()

result = re.sub(regex, subst, lines, re.MULTILINE) 

with open('newfile.txt', 'w') as newfile:
    newfile.write(result)

enter image description here

C# DateTime to "YYYYMMDDHHMMSS" format

You can use a custom format string:

DateTime d = DateTime.Now;
string dateString = d.ToString("yyyyMMddHHmmss");

Substitute "hh" for "HH" if you do not want 24-hour clock time.

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

How do I compute the intersection point of two lines?

The most concise solution I have found uses Sympy: https://www.geeksforgeeks.org/python-sympy-line-intersection-method/

# import sympy and Point, Line 
from sympy import Point, Line 
  
p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) 
l1 = Line(p1, p2) 
  
# using intersection() method 
showIntersection = l1.intersection(p3) 
  
print(showIntersection) 

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

If you are using Jersey for REST API's you can do as below

You don't have to change your webservices implementation.

I will explain for Jersey 2.x

1) First add a ResponseFilter as shown below

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

public class CorsResponseFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

2) then in the web.xml , in the jersey servlet declaration add the below

    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>YOUR PACKAGE.CorsResponseFilter</param-value>
    </init-param>

Detect Safari browser

Only Safari whitout Chrome:

After trying others codes I didn't find any that works with new and old versions of Safari.

Finally, I did this code that's working very well for me:

_x000D_
_x000D_
var ua = navigator.userAgent.toLowerCase(); _x000D_
var isSafari = false;_x000D_
try {_x000D_
  isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);_x000D_
}_x000D_
catch(err) {}_x000D_
isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1))));_x000D_
_x000D_
//test_x000D_
if (isSafari)_x000D_
{_x000D_
  //Code for Safari Browser (Desktop and Mobile)_x000D_
  document.getElementById('idbody').innerHTML = "This is Safari!";_x000D_
}_x000D_
else_x000D_
{_x000D_
  document.getElementById('idbody').innerHTML = "Not is Safari!";_x000D_
}
_x000D_
<body id="idbody">_x000D_
</body>
_x000D_
_x000D_
_x000D_

What USB driver should we use for the Nexus 5?

I am on Windows 8.1, and I tried everything from the other answers and nothing worked. Finally, I decided to try "Pick from a list of drivers" and found "LGE Mobile Sooner Single ADB Interface" under "ADB Interface". ADB.exe was finally able to find the Nexus 5 and sideload 4.4.1.

I hope this helps.

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

Convert hex string (char []) to int?

Something like this could be useful:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

SQL Server add auto increment primary key to existing table

Create a new Table With Different name and same columns, Primary Key and Foreign Key association and link this in your Insert statement of code. For E.g : For EMPLOYEE, replace with EMPLOYEES.

CREATE TABLE EMPLOYEES(

    EmpId        INT NOT NULL IDENTITY(1,1), 
    F_Name       VARCHAR(20) ,
    L_Name       VARCHAR(20) ,
    DOB          DATE ,
    DOJ          DATE ,
    PRIMARY KEY (EmpId),
    DeptId int FOREIGN KEY REFERENCES DEPARTMENT(DeptId),
    DesgId int FOREIGN KEY REFERENCES DESIGNATION(DesgId),
    AddId int FOREIGN KEY REFERENCES ADDRESS(AddId)   
) 

However, you have to either delete the existing EMPLOYEE Table or do some adjustment according to your requirement.

Is it possible to have a default parameter for a mysql stored procedure?

SET myParam = IFNULL(myParam, 0);

Explanation: IFNULL(expression_1, expression_2)

The IFNULL function returns expression_1 if expression_1 is not NULL; otherwise it returns expression_2. The IFNULL function returns a string or a numeric based on the context where it is used.

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

jQuery UI Datepicker - Multiple Date Selections

use this on:

$('body').on('focus',".datumwaehlen", function(){
    $(this).datepicker({
        minDate: -20
    });
});

/bin/sh: pushd: not found

pushd is a bash enhancement to the POSIX-specified Bourne Shell. pushd cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd command might do the chdir(2) call and then start a new shell, but ... it wouldn't be very usable.) pushd is a shell builtin, just like cd.

So, either change your script to start with #!/bin/bash or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

PHP date() with timezone?

For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.

Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:

$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).

What is ViewModel in MVC?

  • ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers)
  • ViewModel can have specific validation rules using data annotations or IDataErrorInfo.
  • ViewModel can have multiple entities or objects from different data models or data source.

Designing ViewModel

public class UserLoginViewModel 
{ 
[Required(ErrorMessage = "Please enter your username")] 
[Display(Name = "User Name")]
[MaxLength(50)]
public string UserName { get; set; }
 [Required(ErrorMessage = "Please enter your password")]
 [Display(Name = "Password")]
 [MaxLength(50)]
 public string Password { get; set; } 
} 

Presenting the viewmodel in the view

@model MyModels.UserLoginViewModel 
@{
 ViewBag.Title = "User Login";
 Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
<div class="editor-label">
 @Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
 @Html.TextBoxFor(m => m.UserName)
 @Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
 @Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
 @Html.PasswordFor(m => m.Password)
 @Html.ValidationMessageFor(m => m.Password)
</div>
<p>
 <input type="submit" value="Log In" />
</p>
</div>
}

Working with Action

public ActionResult Login()
{ 
return View();
}
[HttpPost]
public ActionResult Login(UserLoginViewModel user)
{
// To acces data using LINQ
DataClassesDataContext mobjentity = new DataClassesDataContext();
 if (ModelState.IsValid) 
{ 
try
 {
 var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList(); 
 if (q.Count > 0) 
 { 
 return RedirectToAction("MyAccount");
 }
 else
 {
 ModelState.AddModelError("", "The user name or password provided is incorrect.");
 }
 }
 catch (Exception ex)
 {
 } 
 } 
 return View(user);
} 
  1. In ViewModel put only those fields/data that you want to display on the view/page.
  2. Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
  3. Use a mapper when ViewModel become more complex.

What's the meaning of exception code "EXC_I386_GPFLT"?

EXC_I386_GPFLT is surely referring to "General Protection fault", which is the x86's way to tell you that "you did something that you are not allowed to do". It typically DOESN'T mean that you access out of memory bounds, but it could be that your code is going out of bounds and causing bad code/data to be used in a way that makes for an protection violation of some sort.

Unfortunately it can be hard to figure out exactly what the problem is without more context, there are 27 different causes listed in my AMD64 Programmer's Manual, Vol 2 from 2005 - by all accounts, it is likely that 8 years later would have added a few more.

If it is a 64-bit system, a plausible scenario is that your code is using a "non-canonical pointer" - meaning that a 64-bit address is formed in such a way that the upper 16 bits of the address aren't all copies of the top of the lower 48 bits (in other words, the top 16 bits of an address should all be 0 or all 1, based on the bit just below 16 bits). This rule is in place to guarantee that the architecture can "safely expand the number of valid bits in the address range". This would indicate that the code is either overwriting some pointer data with other stuff, or going out of bounds when reading some pointer value.

Another likely causes is unaligned access with an SSE register - in other word, reading a 16-byte SSE register from an address that isn't 16-byte aligned.

There are, as I said, many other possible reasons, but most of those involve things that "normal" code wouldn't be doing in a 32- or 64-bit OS (such as loading segment registers with invalid selector index or writing to MSR's (model specific registers)).

How are ssl certificates verified?

The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.

You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.

The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).

Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.

How to convert JSON object to JavaScript array?

function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>
</li>

Note the change from let first = first to first as isFirst

How can I create my own comparator for a map?

Since C++11, you can also use a lambda expression instead of defining a comparator struct:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;

Output:

1
two
three
fouuur

I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

Code on Ideone

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

In my case, I tried to run from a mounted ISO. exec name are okay. I fixed the problem by copying all ISO files to the hard disk.

How to run a class from Jar which is not the Main-Class in its Manifest file

Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

MyJar1.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar

MyJar2.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar

etc. Then just run it with java -jar MyJar2.jar

Spring MVC - How to return simple String as JSON in Rest Controller

JSON is essentially a String in PHP or JAVA context. That means string which is valid JSON can be returned in response. Following should work.

  @RequestMapping(value="/user/addUser", method=RequestMethod.POST)
  @ResponseBody
  public String addUser(@ModelAttribute("user") User user) {

    if (user != null) {
      logger.info("Inside addIssuer, adding: " + user.toString());
    } else {
      logger.info("Inside addIssuer...");
    }
    users.put(user.getUsername(), user);
    return "{\"success\":1}";
  }

This is okay for simple string response. But for complex JSON response you should use wrapper class as described by Shaun.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I was facing the same issue and with some hint from @tadtab 's answer, I was able to figure out a solution for the same problem in my project.

Steps:

1->Follow the steps mentioned in @tadtab's answers.

2->Right Click on the project->Click on Properties->Search for Deployment Assembly.

3->Search whether your folder exists on the screen. (If not, add it).

4->On the screen you will find a 'Deploy Path' column corresponding to your source folder. Copy that path. In my case, it was /views.

enter image description here 5->So basically, in the setPrefix() method, we should have the path at the time of deployment. Earlier I was just using /views in the setPrefix() method, so I was getting the same error. But after, it worked well.

@Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/classes/");
        resolver.setSuffix(".jsp");

        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;

    }

The same should be applicable to XML configuration also.

No @XmlRootElement generated by JAXB

Joe's answer (Joe Jun 26 '09 at 17:26) does it for me. The simple answer is that absence of an @XmlRootElement annotation is no problem if you marshal a JAXBElement. The thing that confused me is the generated ObjectFactory has 2 createMyRootElement methods - the first takes no parameters and gives the unwrapped object, the second takes the unwrapped object and returns it wrapped in a JAXBElement, and marshalling that JAXBElement works fine. Here's the basic code I used (I'm new to this, so apologies if the code's not formatted correctly in this reply), largely cribbed from link text:

ObjectFactory objFactory = new ObjectFactory();
MyRootElement root = objFactory.createMyRootElement();
...
// Set root properties
...
if (!writeDocument(objFactory.createMyRootElement(root), output)) {
    System.err.println("Failed to marshal XML document");
}
...

private boolean writeDocument(JAXBElement document, OutputStream output) {

  Class<?> clazz = document.getValue().getClass();
  try {
    JAXBContext context =
        JAXBContext.newInstance(clazz.getPackage().getName());
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(document, output);
    return true;

  } catch (JAXBException e) {
    e.printStackTrace(System.err);
    return false;
  }
}

Show percent % instead of counts in charts of categorical variables

As of March 2017, with ggplot2 2.2.1 I think the best solution is explained in Hadley Wickham's R for data science book:

ggplot(mydataf) + stat_count(mapping = aes(x=foo, y=..prop.., group=1))

stat_count computes two variables: count is used by default, but you can choose to use prop which shows proportions.

Decorators with parameters?

Writing a decorator that works with and without parameter is a challenge because Python expects completely different behavior in these two cases! Many answers have tried to work around this and below is an improvement of answer by @norok2. Specifically, this variation eliminates the use of locals().

Following the same example as given by @norok2:

import functools

def multiplying(f_py=None, factor=1):
    assert callable(f_py) or f_py is None
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return factor * func(*args, **kwargs)
        return wrapper
    return _decorator(f_py) if callable(f_py) else _decorator


@multiplying
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying()
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying(factor=10)
def summing(x): return sum(x)

print(summing(range(10)))
# 450

Play with this code.

The catch is that the user must supply key,value pairs of parameters instead of positional parameters and the first parameter is reserved.

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

Keep only date part when using pandas.to_datetime

Pandas DatetimeIndex and Series have a method called normalize that does exactly what you want.

You can read more about it in this answer.

It can be used as ser.dt.normalize()

Key Shortcut for Eclipse Imports

Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.

Press Ctrl+3

And type whatever the hell you want :) It's a shortcut for shortcuts

enter image description here

Compiling simple Hello World program on OS X via command line

Also, you can use an IDE like CLion (JetBrains) or a text editor like Atom, with the gpp-compiler plugin, works like a charm (F5 to compile & execute).

How to run function of parent window when child window closes?

Check following link. This would be helpful too..

In Parent Window:

function OpenChildAsPopup() {
        var childWindow = window.open("ChildWindow.aspx", "_blank",
        "width=200px,height=350px,left=200,top=100");
        childWindow.focus();
 }

function ChangeBackgroudColor() {
        var para = document.getElementById('samplePara');
        if (para !="undefied") {
            para.style.backgroundColor = '#6CDBF5';
        }
 }

Parent Window HTML Markup:

<div>
  <p id="samplePara" style="width: 350px;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  </p><br />
 <asp:Button ID="Button1" Text="Open Child Window" 
         runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>

In Child Window:

// This will be called when the child window is closed.     
  window.onunload = function (e) {
        opener.ChangeBackgroudColor();
        //or you can do
        //var para = opener.document.getElementById('samplePara');
        //if (para != "undefied") {
        //    para.style.backgroundColor = '#6CDBF5';
        //}
    };

Finding Variable Type in JavaScript

To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):

In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)

The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.

As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

How in node to split string by newline ('\n')?

I made an eol module for working with line endings in node or browsers. It has a split method like

var lines = eol.split(text)

Using a Glyphicon as an LI bullet point (Bootstrap 3)

Using Font Awesome 5, the markup is a bit more complex than the previouis answer. Per the FA documentation, the markup should be:

<ul class="fa-ul">
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
  <li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
  <li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>

How exactly does __attribute__((constructor)) work?

This page provides great understanding about the constructor and destructor attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.

As explained in this thread, the constructor and destructor attributes create entries in the .ctors and .dtors section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section attribute; (2) constructor and destructor attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).

The use of constructor and destructor attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main() is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100 as the compiler reserves priority values between 0-100 for implementation. Aconstructor or destructor specified with priority executes before a constructor or destructor specified without priority.

With the 'section' attribute or with inline-assembly, you can also place function references in the .init and .fini ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init section, will execute before the function reference itself (as usual).

I have tried to illustrate each of those in the example below:

#include <stdio.h>
#include <stdlib.h>

/*  test function utilizing attribute 'section' ".ctors"/".dtors"
    to create constuctors/destructors without assigned priority.
    (provided by Michael Ambrus in earlier answer)
*/

#define SECTION( S ) __attribute__ ((section ( S )))

void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}

void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

/*  functions constructX, destructX use attributes 'constructor' and
    'destructor' to create prioritized entries in the .ctors, .dtors
    ELF sections, respectively.

    NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));

/*  init_some_function() - called by elf_init()
*/
int init_some_function () {
    printf ("\n  init_some_function() called by elf_init()\n");
    return 1;
}

/*  elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
    __asm__ (".section .init \n call elf_init \n .section .text\n");

    if(!init_some_function ())
    {
        exit (1);
    }

    printf ("\n    elf_init() -- (.section .init)\n");

    return 1;
}

/*
    function definitions for constructX and destructX
*/
void construct1 () {
    printf ("\n      construct1() constructor -- (.section .ctors) priority 101\n");
}

void construct2 () {
    printf ("\n      construct2() constructor -- (.section .ctors) priority 102\n");
}

void destruct1 () {
    printf ("\n      destruct1() destructor -- (.section .dtors) priority 101\n\n");
}

void destruct2 () {
    printf ("\n      destruct2() destructor -- (.section .dtors) priority 102\n");
}

/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {

    printf ("\n\t  [ main body of program ]\n");

    return 0;
}

output:

init_some_function() called by elf_init()

    elf_init() -- (.section .init)

    construct1() constructor -- (.section .ctors) priority 101

    construct2() constructor -- (.section .ctors) priority 102

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        [ main body of program ]

        test() utilizing -- (.section .ctors/.dtors) w/o priority

    destruct2() destructor -- (.section .dtors) priority 102

    destruct1() destructor -- (.section .dtors) priority 101

The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.

Simple search MySQL database using php

You need to use $_POST not $_post.

How do I "break" out of an if statement?

You probably need to break up your if statement into smaller pieces. That being said, you can do two things:

  • wrap the statement into do {} while (false) and use real break (not recommended!!! huge kludge!!!)

  • put the statement into its own subroutine and use return This may be the first step to improving your code.

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

How to npm install to a specified directory?

In the documentation it's stated: Use the prefix option together with the global option:

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.

When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.

(Emphasis by them)

So in your root directory you could install with

npm install --prefix <path/to/prefix_folder> -g

and it will install the node_modules folder into the folder

<path/to/prefix_folder>/lib/node_modules

How do I show running processes in Oracle DB?

Keep in mind that there are processes on the database which may not currently support a session.

If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)

CSS Border Not Working

Use this line of code in your css

border: 1px solid #000 !important;

or if you want border only in left and right side of container then use:

border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;

Check if enum exists in Java

Most of the answers suggest either using a loop with equals to check if the enum exists or using try/catch with enum.valueOf(). I wanted to know which method is faster and tried it. I am not very good at benchmarking, so please correct me if I made any mistakes.

Heres the code of my main class:

    package enumtest;

public class TestMain {

    static long timeCatch, timeIterate;
    static String checkFor;
    static int corrects;

    public static void main(String[] args) {
        timeCatch = 0;
        timeIterate = 0;
        TestingEnum[] enumVals = TestingEnum.values();
        String[] testingStrings = new String[enumVals.length * 5];
        for (int j = 0; j < 10000; j++) {
            for (int i = 0; i < testingStrings.length; i++) {
                if (i % 5 == 0) {
                    testingStrings[i] = enumVals[i / 5].toString();
                } else {
                    testingStrings[i] = "DOES_NOT_EXIST" + i;
                }
            }

            for (String s : testingStrings) {
                checkFor = s;
                if (tryCatch()) {
                    ++corrects;
                }
                if (iterate()) {
                    ++corrects;
                }
            }
        }

        System.out.println(timeCatch / 1000 + "us for try catch");
        System.out.println(timeIterate / 1000 + "us for iterate");
        System.out.println(corrects);
    }

    static boolean tryCatch() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        try {
            TestingEnum.valueOf(checkFor);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } finally {
            timeEnd = System.nanoTime();
            timeCatch += timeEnd - timeStart;
        }

    }

    static boolean iterate() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        TestingEnum[] values = TestingEnum.values();
        for (TestingEnum v : values) {
            if (v.toString().equals(checkFor)) {
                timeEnd = System.nanoTime();
                timeIterate += timeEnd - timeStart;
                return true;
            }
        }
        timeEnd = System.nanoTime();
        timeIterate += timeEnd - timeStart;
        return false;
    }
}

This means, each methods run 50000 times the lenght of the enum I ran this test multiple times, with 10, 20, 50 and 100 enum constants. Here are the results:

  • 10: try/catch: 760ms | iteration: 62ms
  • 20: try/catch: 1671ms | iteration: 177ms
  • 50: try/catch: 3113ms | iteration: 488ms
  • 100: try/catch: 6834ms | iteration: 1760ms

These results were not exact. When executing it again, there is up to 10% difference in the results, but they are enough to show, that the try/catch method is far less efficient, especially with small enums.

What does the Ellipsis object do?

Summing up what others have said, as of Python 3, Ellipsis is essentially another singleton constant similar to None, but without a particular intended use. Existing uses include:

  • In slice syntax to represent the full slice in remaining dimensions
  • In type hinting to indicate only part of a type(Callable[..., int] or Tuple[str, ...])
  • In type stub files to indicate there is a default value without specifying it

Possible uses could include:

  • As a default value for places where None is a valid option
  • As the content for a function you haven't implemented yet

adb command not found in linux environment

Follow these steps:

Set android vars

Initially go to your home and press `Ctrl + H` it will show you hidden files now look for .bashrc file, open it with any text editor

then place the lines below at the end of file:

export ANDROID_HOME=/myPathSdk/android-sdk-linux
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools


Now Reboot the system

It Works!

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

How do I remove duplicate items from an array in Perl?

Previous answers pretty much summarize the possible ways of accomplishing this task.

However, I suggest a modification for those who don't care about counting the duplicates, but do care about order.

my @record = qw( yeah I mean uh right right uh yeah so well right I maybe );
my %record;
print grep !$record{$_} && ++$record{$_}, @record;

Note that the previously suggested grep !$seen{$_}++ ... increments $seen{$_} before negating, so the increment occurs regardless of whether it has already been %seen or not. The above, however, short-circuits when $record{$_} is true, leaving what's been heard once 'off the %record'.

You could also go for this ridiculousness, which takes advantage of autovivification and existence of hash keys:

...
grep !(exists $record{$_} || undef $record{$_}), @record;

That, however, might lead to some confusion.

And if you care about neither order or duplicate count, you could for another hack using hash slices and the trick I just mentioned:

...
undef @record{@record};
keys %record; # your record, now probably scrambled but at least deduped

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

Send data from a textbox into Flask?

Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.

from flask import request

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
    if request.method == "POST":
         #perform action here
var value = $('.textbox').val();
$.ajax({
  type: 'POST',
  url: "{{ url_for('parse_data') }}",
  data: JSON.stringify(value),
  contentType: 'application/json',
  success: function(data){
    // do something with the received data
  }
});

While loop in batch

set /a countfiles-=%countfiles%

This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:

set /a countfiles-=1

I'm not sure if the for loop will work, better try something like this:

:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop

How to convert .pfx file to keystore with private key?

I found this page which tells you how to import a PFX to JKS (Java Key Store):

keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

  • View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

  • Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

  • ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

How do I get LaTeX to hyphenate a word that contains a dash?

multi-disciplinary will not be hyphenated, as explained by kennytm. But multi-\-disciplinary has the same hyphenation opportunities that multidisciplinary has.

I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):

The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.

Passing a 2D array to a C++ function

We can use several ways to pass a 2D array to a function:

  • Using single pointer we have to typecast the 2D array.

     #include<bits/stdc++.h>
     using namespace std;
    
    
     void func(int *arr, int m, int n)
     {
         for (int i=0; i<m; i++)
         {
            for (int j=0; j<n; j++)
            {
               cout<<*((arr+i*n) + j)<<" ";
            }
            cout<<endl;
         }
     }
    
     int main()
     {
         int m = 3, n = 3;
         int arr[m][n] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
         func((int *)arr, m, n);
         return 0;
     }
    
  • Using double pointer In this way, we also typecast the 2d array

     #include<bits/stdc++.h>
     using namespace std;
    
    void func(int **arr, int row, int col)
    {
       for (int i=0; i<row; i++)
       {
          for(int j=0 ; j<col; j++)
          {
            cout<<arr[i][j]<<" ";
          }
          printf("\n");
       }
    }
    
    int main()
    {
      int row, colum;
      cin>>row>>colum;
      int** arr = new int*[row];
    
      for(int i=0; i<row; i++)
      {
         arr[i] = new int[colum];
      }
    
      for(int i=0; i<row; i++)
      {
          for(int j=0; j<colum; j++)
          {
             cin>>arr[i][j];
          }
      }
      func(arr, row, colum);
    
      return 0;
    }
    

C#: what is the easiest way to subtract time?

Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

How to set the color of "placeholder" text?

Try this

_x000D_
_x000D_
input::-webkit-input-placeholder { /* WebKit browsers */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */_x000D_
    color:    #f51;_x000D_
}_x000D_
input::-moz-placeholder { /* Mozilla Firefox 19+ */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-ms-input-placeholder { /* Internet Explorer 10+ */_x000D_
    color:    #f51;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

How to get name of dataframe column in pyspark?

Python

As @numeral correctly said, column._jc.toString() works fine in case of unaliased columns.

In case of aliased columns (i.e. column.alias("whatever") ) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1] .

I don't know Scala syntax, but I'm sure It can be done the same.

php static function

Calling non-static methods statically generates an E_STRICT level warning.

SQLite3 database or disk is full / the database disk image is malformed

During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.

var updateStatementString : String! = ""

for item in cardids {
    let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
    updateStatementString.append(newstring)
}

print(updateStatementString)

let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)

return Int64(results)

Efficient SQL test query or validation query that will work across all (or most) databases

select 1 would work in sql server, not sure about the others.

Use standard ansi sql to create a table and then query from that table.

Multiple modals overlay

Unfortunately I do not have the reputation to comment, but it should be noted that the accepted solution with the hardcoded baseline of a 1040 z-index seems to be superior to the zIndex calculation that tries to find the maximum zIndex being rendered on the page.

It appears that certain extensions/plugins rely on top level DOM content which makes the .Max calculation such an obscenely large number, that it can't increment the zIndex any further. This results in a modal where the overlay appears over the modal incorrectly (if you use Firebug/Google Inspector tools you'll see a zIndex on the order of 2^n - 1)

I haven't been able to isolate what the specific reason the various forms of Math.Max for z-Index leads to this scenario, but it can happen, and it will appear unique to a few users. (My general tests on browserstack had this code working perfectly).

Hope this helps someone.

Getting JSONObject from JSONArray

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

for(int i = 0; deletedtrs_array.length(); i++){

            JSONObject myObj = deletedtrs_array.getJSONObject(i);
}

Difference between Mutable objects and Immutable objects

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

For example:(Point is mutable and string immutable)

     Point myPoint = new Point( 0, 0 );
    System.out.println( myPoint );
    myPoint.setLocation( 1.0, 0.0 );
    System.out.println( myPoint );

    String myString = new String( "old String" );
    System.out.println( myString );
    myString.replaceAll( "old", "new" );
    System.out.println( myString );

The output is:

java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String

Find and replace in file and overwrite file doesn't work, it empties the file

With all due respect to the above correct answers, it's always a good idea to "dry run" scripts like that, so that you don't corrupt your file and have to start again from scratch.

Just get your script to spill the output to the command line instead of writing it to the file, for example, like that:

sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

OR

less index.html | sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g 

This way you can see and check the output of the command without getting your file truncated.

PHP Fatal error: Call to undefined function json_decode()

Solution for LAMP users:

apt-get install php5-json
service apache2 restart

Source

SSIS cannot convert because a potential loss of data

For me just removed the OLE DB source from SSIS and added again. Worked!

How to install Visual Studio 2015 on a different drive

I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):

mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"

mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"

How to move child element from one parent to another using jQuery

Based on the answers provided, I decided to make a quick plugin to do this:

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);

Usage:

$('#nodeToMove').moveTo('#newParent');

How to convert a table to a data frame

I figured it out already:

as.data.frame.matrix(mytable) 

does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Populating a data frame in R in a loop

this works too.

df = NULL
for (k in 1:10)
    {
       x = 1
       y = 2
       z = 3
       df = rbind(df, data.frame(x,y,z))
     }

output will look like this

df #enter

x y z #col names
1 2 3

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

How to add/update child entities when updating a parent entity in EF

OK guys. I had this answer once but lost it along the way. absolute torture when you know there's a better way but can't remember it or find it! It's very simple. I just tested it multiple ways.

var parent = _dbContext.Parents
  .Where(p => p.Id == model.Id)
  .Include(p => p.Children)
  .FirstOrDefault();

parent.Children = _dbContext.Children.Where(c => <Query for New List Here>);
_dbContext.Entry(parent).State = EntityState.Modified;

_dbContext.SaveChanges();

You can replace the whole list with a new one! The SQL code will remove and add entities as needed. No need to concern yourself with that. Be sure to include child collection or no dice. Good luck!

How can I apply a border only inside a table?

Works for any combination of tbody/thead/tfoot and td/th

_x000D_
_x000D_
table.inner-border {_x000D_
    border-collapse: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
_x000D_
table.inner-border > thead > tr > th,_x000D_
table.inner-border > thead > tr > td,_x000D_
table.inner-border > tbody > tr > th,_x000D_
table.inner-border > tbody > tr > td,_x000D_
table.inner-border > tfoot > tr > th,_x000D_
table.inner-border > tfoot > tr > td {_x000D_
    border-bottom: 1px solid black;_x000D_
    border-right: 1px solid black;_x000D_
}_x000D_
_x000D_
table.inner-border > thead > tr > :last-child,_x000D_
table.inner-border > tbody > tr > :last-child,_x000D_
table.inner-border > tfoot > tr > :last-child {_x000D_
    border-right: 0;_x000D_
}_x000D_
_x000D_
table.inner-border > :last-child > tr:last-child > td,_x000D_
table.inner-border > :last-child > tr:last-child > th {_x000D_
    border-bottom: 0;_x000D_
}
_x000D_
<table class="inner-border">_x000D_
    <thead>_x000D_
    <tr>_x000D_
        <th>head1,1</th>_x000D_
        <td>head1,2</td>_x000D_
        <td>head1,3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>head2,1</td>_x000D_
        <td>head2,2</td>_x000D_
        <th>head2,3</th>_x000D_
    </tr>_x000D_
    </thead>_x000D_
    <tr>_x000D_
        <td>1,1</td>_x000D_
        <th>1,2</th>_x000D_
        <td>1,3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>2,1</td>_x000D_
        <td>2,2</td>_x000D_
        <td>2,3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>3,1</td>_x000D_
        <td>3,2</td>_x000D_
        <td>3,3</td>_x000D_
    </tr>_x000D_
    <thead>_x000D_
    <tr>_x000D_
        <th>foot1,1</th>_x000D_
        <td>foot1,2</td>_x000D_
        <td>foot1,3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>foot2,1</td>_x000D_
        <th>foot2,2</th>_x000D_
        <th>foot2,3</th>_x000D_
    </tr>_x000D_
    </thead>_x000D_
</table>
_x000D_
_x000D_
_x000D_

What can MATLAB do that R cannot do?

We can't because it's expected/required by our customers.

Zookeeper connection error

This can happen if there are too many open connections.

Try increasing the maxClientCnxns setting.

From documentation:

maxClientCnxns (No Java system property)

Limits the number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. This is used to prevent certain classes of DoS attacks, including file descriptor exhaustion. Setting this to 0 or omitting it entirely removes the limit on concurrent connections.

You can edit settings in the config file. Most likely it can be found at /etc/zookeeper/conf/zoo.cfg.

In modern ZooKeeper versions default value is 60. You can increase it by adding the maxClientCnxns=4096 line to the end of the config file.

Printing a char with printf

#include <stdio.h>
#include <stdlib.h>

int func(char a, char b, char c) /* demonstration that char on stack is promoted to int !!!
                                    note: this promotion is NOT integer promotion, but promotion during handling of the stack. don't confuse the two */
{
  const char *p = &a;
  printf("a=%d\n"
         "b=%d\n"
         "c=%d\n", *p, p[-(int)sizeof(int)], p[-(int)sizeof(int) * 2]); // don't do this. might probably work on x86 with gcc (but again: don't do this)
}


int main(void)
{
  func(1, 2, 3);

  //printf with %d treats its argument as int (argument must be int or smaller -> works because of conversion to int when on stack -- see demo above)
  printf("%d, %d, %d\n", (long long) 1, 2, 3); // don't do this! Argument must be int or smaller type (like char... which is converted to int when on the stack -- see above)



  // backslash followed by number is a oct VALUE
  printf("%d\n", '\377');             /* prints -1   -> IF char is signed char: char literal has all bits set and is thus value -1.
                                                     -> char literal is then integer promoted to int. (this promotion has nothing to do with the stack. don't confuse the two!!!) */
                                      /* prints 255  -> IF char is unsigned char: char literal has all bits set and is thus value 255.
                                                     -> char literal is then integer promoted to int */


  // backslash followed by x is a hex VALUE
  printf("%d\n", '\xff');             /* prints -1   -> IF char is signed char: char literal has all bits set and is thus value -1.
                                                     -> char literal is then integer promoted to int */
                                      /* prints 255  -> IF char is unsigned char: char literal has all bits set and is thus value 255.
                                                     -> char literal is then integer promoted to int */


  printf("%d\n", 255);                // prints 255


  printf("%d\n", (char)255);          // prints -1   -> 255 is cast to char where it is -1
  printf("%d\n", '\n');               // prints 10   -> Ascii newline has VALUE 10. The char 10 is integer promoted to int 10
  printf("%d\n", sizeof('\n'));       // prints 4    -> Ascii newline is char, but integer promoted to int. And sizeof(int) is 4 (on many architectures)
  printf("%d\n", sizeof((char)'\n')); // prints 1    -> Switch off integer promotion via cast!

  return 0;
}

How to do vlookup and fill down (like in Excel) in R?

I also like using qdapTools::lookup or shorthand binary operator %l%. It works identically to an Excel vlookup, but it accepts name arguments opposed to column numbers

## Replicate Ben's data:
hous <- structure(list(HouseType = c("Semi", "Single", "Row", "Single", 
    "Apartment", "Apartment", "Row"), HouseTypeNo = c(1L, 2L, 3L, 
    2L, 4L, 4L, 3L)), .Names = c("HouseType", "HouseTypeNo"), 
    class = "data.frame", row.names = c(NA, -7L))


largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 
    1000, replace = TRUE)), stringsAsFactors = FALSE)


## It's this simple:
library(qdapTools)
largetable[, 1] %l% hous

How to add an image in Tkinter?

Following code works on my machine

  1. you probably have something missing in your code.
  2. please also check the code files's encoding.
  3. make sure you have PIL package installed

    import Tkinter as tk
    from PIL import ImageTk, Image
    
    path = 'C:/xxxx/xxxx.jpg'
    
    root = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(root, image = img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")
    root.mainloop()
    

Quicksort with Python

For Version Python 3.x: a functional-style using operator module, primarily to improve readability.

from operator import ge as greater, lt as lesser

def qsort(L): 
    if len(L) <= 1: return L
    pivot   = L[0]
    sublist = lambda op: [*filter(lambda num: op(num, pivot), L[1:])]

    return qsort(sublist(lesser))+ [pivot] + qsort(sublist(greater))

and is tested as

print (qsort([3,1,4,2,5]) == [1,2,3,4,5])

Why does the Google Play store say my Android app is incompatible with my own device?

The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.

I changed nothing in this app except for adding more content into the res/drawable directory. When the .apk size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.

I will attempt to contact Google developer support and ask for clarification on the reason for this limit.

UPDATE: Here is Google developer support response to this:

Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.

However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.

I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.

I also removed all the <uses-feature> stuff, and now have just this:

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />

How can I get screen resolution in java?

Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

Here are links to the JavaDoc.

GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()

Visual C++: How to disable specific linker warnings?

I suspect /ignore is a VC6 link.exe option. for VS2005 and VS2008's linker there's no documented /ignore option available, but the linker looks just ignore the "/ignore:XXX" option, no error and no effect.

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I had the same problem with Microsoft Visual Studio 2010 Ultimate and it was solved by the method described in this youtube video

The video suggests to rename the file cvtres.exe in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin (in my Win7X64 matchine) to cvtres-old.exe

How to use Python's pip to download and keep the zipped files for a package?

The --download-cache option should do what you want:

pip install --download-cache="/pth/to/downloaded/files" package

However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz files were there.

The --download option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download option did not download dependencies.)

pip install package --download="/pth/to/downloaded/files"

The pip documentation outlines using --download for fast & local installs.

libpng warning: iCCP: known incorrect sRGB profile

You can also just fix this in photoshop...

  1. Open your .png file.
  2. File -> Save As and in the dialog that opens up uncheck "ICC Profile: sRGB IEC61966-2.1"
  3. Uncheck "As a Copy".
  4. Courageously save over your original .png.
  5. Move on with your life knowing that you've removed just that little bit of evil from the world.

Error installing mysql2: Failed to build gem native extension

I have several computers, 32 and 64 bits processor, they run on Ubuntu Linux, Maverick (10.10) release.

I had the same problem, and for me, the sudo apt-get install libmysql-ruby libmysqlclient-dev did the job!!!

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

Sum the digits of a number

If you want to keep summing the digits until you get a single-digit number (one of my favorite characteristics of numbers divisible by 9) you can do:

def digital_root(n):
    x = sum(int(digit) for digit in str(n))
    if x < 10:
        return x
    else:
        return digital_root(x)

Which actually turns out to be pretty fast itself...

%timeit digital_root(12312658419614961365)

10000 loops, best of 3: 22.6 µs per loop

File Explorer in Android Studio

1- menu, "Tools" -> "Android" -> "DDMS (monitor included)" 2- Open the File Explorer tab.

What is the Ruby <=> (spaceship) operator?

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

Checkout another branch when there are uncommitted changes on the current branch

If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.

Example:

$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"

$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
     # experiment now contains changes that master doesn't have
     # any future changes to this file will keep you from changing branches
     # until the changes are stashed or committed

$ echo "and we're back" >> file.txt  # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

This goes for untracked files as well as tracked files. Here's an example for an untracked file.

Example:

$ git checkout -b experimental  # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"

$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
    file.txt
Please move or remove them before you can switch branches.
Aborting

A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...

$ echo 'experimental change' >> file.txt # change to existing tracked file
   # I want to save these, but not on master

$ git checkout -b experiment
M       file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

Typescript - multidimensional array initialization

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = [];
myArray.push(["value1", "value2"]);

Postgres: clear entire database before re-creating / re-populating from bash script

To dump:

pg_dump -Fc mydb > db.dump

To restore:

pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

What is the difference between null and System.DBNull.Value?

DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.

http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

private final static attribute vs private final attribute

If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.

You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

How to append rows in a pandas dataframe in a for loop?

There are 2 reasons you may append rows in a loop, 1. add to an existing df, and 2. create a new df.

to create a new df, I think its well documented that you should either create your data as a list and then create the data frame:

cols = ['c1', 'c2', 'c3']
lst = []
for a in range(2):
    lst.append([1, 2, 3])
df1 = pd.DataFrame(lst, columns=cols)
df1
Out[3]: 
   c1  c2  c3
0   1   2   3
1   1   2   3

OR, Create the dataframe with an index and then add to it

cols = ['c1', 'c2', 'c3']
df2 = pd.DataFrame(columns=cols, index=range(2))
for a in range(2):
    df2.loc[a].c1 = 4
    df2.loc[a].c2 = 5
    df2.loc[a].c3 = 6
df2
Out[4]: 
  c1 c2 c3
0  4  5  6
1  4  5  6

If you want to add to an existing dataframe, you could use either method above and then append the df's together (with or without the index):

df3 = df2.append(df1, ignore_index=True)
df3
Out[6]: 
  c1 c2 c3
0  4  5  6
1  4  5  6
2  1  2  3
3  1  2  3

Or, you can also create a list of dictionary entries and append those as in the answer above.

lst_dict = []
for a in range(2):
    lst_dict.append({'c1':2, 'c2':2, 'c3': 3})
df4 = df1.append(lst_dict)
df4
Out[7]: 
   c1  c2  c3
0   1   2   3
1   1   2   3
0   2   2   3
1   2   2   3

Using the dict(zip(cols, vals)))

lst_dict = []
for a in range(2):
    vals = [7, 8, 9]
    lst_dict.append(dict(zip(cols, vals)))
df5 = df1.append(lst_dict)

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639