Programs & Examples On #G1gc

G1 or Garbage First is a generational partially collecting concurrent and parallel garbage collection algorithm. It is targeted for multi-processor machines with large memories and can meet soft realtime requirements with garbage collection (GC) pause time goals. An implementation of the G1 currently ships with the new Java 7 VMS - officially supported from JDK7 update 4.

java.lang.OutOfMemoryError: GC overhead limit exceeded

You're essentially running out of memory to run the process smoothly. Options that come to mind:

  1. Specify more memory like you mentioned, try something in between like -Xmx512m first
  2. Work with smaller batches of HashMap objects to process at once if possible
  3. If you have a lot of duplicate strings, use String.intern() on them before putting them into the HashMap
  4. Use the HashMap(int initialCapacity, float loadFactor) constructor to tune for your case

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

Vue.js - How to properly watch for nested data

I've found it works this way too:

watch: {
    "details.position"(newValue, oldValue) {
        console.log("changes here")
    }
},
data() {
    return {
      details: {
          position: ""
      }
    }
}

define a List like List<int,string>?

List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)
{
     Console.WriteLine(mylist[i]);
}

Is there a way to specify a default property value in Spring XML?

There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:

config.properties:

timeout.default=30
timeout.myBean=60

context.xml:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>config.properties</value>
    </property>
</bean>

<bean id="myBean" class="Test">
    <property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>

To use the default while still being able to easily override later, do this in config.properties:

timeout.myBean = ${timeout.default}

PHP json_decode() returns NULL with valid JSON?

This worked for me

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

When setting the curl options for CURLOPT_CAINFO please remember to use single quotes, using double quotes will only cause another error. So your option should look like:

curl_setopt ($ch, CURLOPT_CAINFO, 'c:\wamp\www\mywebfolder\cacert.pem');

Additionally, in your php.ini file setting should be written as:(notice my double quotes)

curl.cainfo = "C:\wamp\www\mywebfolder"

I put it directly below the line that says this: extension=php_curl.dll

(For organizing purposes only, you could put it anywhere within your php.ini, i just put it close to another curl reference so when I search using keyword curl I caan find both curl references in one area.)

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Don't escape the underscore. Might be causing some whackness.

Displaying the build date

I just added pre-build event command:

powershell -Command Get-Date -Format 'yyyy-MM-ddTHH:mm:sszzz' > Resources\BuildDateTime.txt

in the project properties to generate a resource file that is then easy to read from the code.

Auto increment in phpmyadmin

Just run a simple MySQL query and set the auto increment number to whatever you want.

ALTER TABLE `table_name` AUTO_INCREMENT=10000

In terms of a maximum, as far as I am aware there is not one, nor is there any way to limit such number.

It is perfectly safe, and common practice to set an id number as a primiary key, auto incrementing int. There are alternatives such as using PHP to generate membership numbers for you in a specific format and then checking the number does not exist prior to inserting, however for me personally I'd go with the primary id auto_inc value.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

The above answers get at the most fundamental aspects of the C++ memory model. In practice, most uses of std::atomic<> "just work", at least until the programmer over-optimizes (e.g., by trying to relax too many things).

There is one place where mistakes are still common: sequence locks. There is an excellent and easy-to-read discussion of the challenges at https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf. Sequence locks are appealing because the reader avoids writing to the lock word. The following code is based on Figure 1 of the above technical report, and it highlights the challenges when implementing sequence locks in C++:

atomic<uint64_t> seq; // seqlock representation
int data1, data2;     // this data will be protected by seq

T reader() {
    int r1, r2;
    unsigned seq0, seq1;
    while (true) {
        seq0 = seq;
        r1 = data1; // INCORRECT! Data Race!
        r2 = data2; // INCORRECT!
        seq1 = seq;

        // if the lock didn't change while I was reading, and
        // the lock wasn't held while I was reading, then my
        // reads should be valid
        if (seq0 == seq1 && !(seq0 & 1))
            break;
    }
    use(r1, r2);
}

void writer(int new_data1, int new_data2) {
    unsigned seq0 = seq;
    while (true) {
        if ((!(seq0 & 1)) && seq.compare_exchange_weak(seq0, seq0 + 1))
            break; // atomically moving the lock from even to odd is an acquire
    }
    data1 = new_data1;
    data2 = new_data2;
    seq = seq0 + 2; // release the lock by increasing its value to even
}

As unintuitive as it seams at first, data1 and data2 need to be atomic<>. If they are not atomic, then they could be read (in reader()) at the exact same time as they are written (in writer()). According to the C++ memory model, this is a race even if reader() never actually uses the data. In addition, if they are not atomic, then the compiler can cache the first read of each value in a register. Obviously you wouldn't want that... you want to re-read in each iteration of the while loop in reader().

It is also not sufficient to make them atomic<> and access them with memory_order_relaxed. The reason for this is that the reads of seq (in reader()) only have acquire semantics. In simple terms, if X and Y are memory accesses, X precedes Y, X is not an acquire or release, and Y is an acquire, then the compiler can reorder Y before X. If Y was the second read of seq, and X was a read of data, such a reordering would break the lock implementation.

The paper gives a few solutions. The one with the best performance today is probably the one that uses an atomic_thread_fence with memory_order_relaxed before the second read of the seqlock. In the paper, it's Figure 6. I'm not reproducing the code here, because anyone who has read this far really ought to read the paper. It is more precise and complete than this post.

The last issue is that it might be unnatural to make the data variables atomic. If you can't in your code, then you need to be very careful, because casting from non-atomic to atomic is only legal for primitive types. C++20 is supposed to add atomic_ref<>, which will make this problem easier to resolve.

To summarize: even if you think you understand the C++ memory model, you should be very careful before rolling your own sequence locks.

How to execute a Ruby script in Terminal?

Open Terminal

cd to/the/program/location
ruby program.rb

or add #!/usr/bin/env ruby in the first of your program (script tell that this is executed using Ruby Interpreter)

Open Terminal

cd to/the/program/location
chmod 777 program.rb
./program.rb

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Macro to Auto Fill Down to last adjacent cell

This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.

Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

What is the difference between varchar and nvarchar?

I had a look at the answers and many seem to recommend to use nvarchar over varchar, because space is not a problem anymore, so there is no harm in enabling Unicode for little extra storage. Well, this is not always true when you want to apply an index over your column. SQL Server has a limit of 900 bytes on the size of the field you can index. So if you have a varchar(900) you can still index it, but not varchar(901). With nvarchar, the number of characters is halved, so you can index up to nvarchar(450). So if you are confident you don't need nvarchar, I don't recommend using it.

In general, in databases, I recommend sticking to the size you need, because you can always expand. For example, a colleague at work once thought that there is no harm in using nvarchar(max) for a column, as we have no problem with storage at all. Later on, when we tried to apply an index over this column, SQL Server rejected this. If, however, he started with even varchar(5), we could have simply expanded it later to what we need without such a problem that will require us to do a field migration plan to fix this problem.

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

low dpi is 0.75x dimensions of medium dpi

high dpi is 1.5x dimensions of medium dpi

extra high dpi is 2x dimensinons of medium dpi

It's a good practice to make all the images in vector based format so you can resize them easily using a vector design software like Illustrator etc..

How to conclude your merge of a file?

I just did:

git merge --continue

At which point vi launched to edit a merge comment. A quick :wq and the merge was done.

Joining two lists together

The way with the least space overhead is to use the Concat extension method.

var combined = list1.Concat(list2);

It creates an instance of IEnumerable<T> which will enumerate the elements of list1 and list2 in that order.

MVC 3 file upload and model binding

1st download jquery.form.js file from below url

http://plugins.jquery.com/form/

Write below code in cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
    <div id="uploadTemplate">

        <input type="text" value="Asif" id="txtname" name="txtName" />


        <div id="dvAddTemplate">
            Add Template
            <br />
            <input type="file" name="file" id="file" tabindex="2" />
            <br />
            <input type="submit" value="Submit" />
            <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
        </div>

        <div id="TemplateTree" style="overflow-x: auto;"></div>
    </div>

    <div id="progressBarDiv" style="display: none;">
        <img id="loading-image" src="~/Images/progress-loader.gif" />
    </div>

}


<script type="text/javascript">

    $(document).ready(function () {
        debugger;
        alert('sample');
        var status = $('#status');
        $('#frmTemplateUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {
                    //$("#uploadTemplate").hide();
                    $("#btnAction").hide();
                    $("#progressBarDiv").show();
                    //progress_run_id = setInterval(progress, 300);
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {
                        //clearInterval(progress_run_id);
                        $("#uploadTemplate").show();
                        $("#btnAction").show();
                        $("#progressBarDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });

    });


</script>

Action method :-

 public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

 public void Upload(HttpPostedFileBase file, string txtname )
        {

            try
            {
                string attachmentFilePath = file.FileName;
                string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);

           }
            catch (Exception ex)
            {

            }
        }

PHP new line break in emails

If you output to html or an html e-mail you will need to use <br> or <br /> instead of \n.

If it's just a text e-mail: Are you perhaps using ' instead of "? Although then your values would not be inserted either...

Typescript es6 import module "File is not a module error"

Extended - to provide more details based on some comments

The error

Error TS2306: File 'test.ts' is not a module.

Comes from the fact described here http://exploringjs.com/es6/ch_modules.html

17. Modules

This chapter explains how the built-in modules work in ECMAScript 6.

17.1 Overview

In ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.

17.1.1 Multiple named exports

There can be multiple named exports:

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
...

17.1.2 Single default export

There can be a single default export. For example, a function:

//------ myFunc.js ------
export default function () { ··· } // no semicolon!

Based on the above we need the export, as a part of the test.js file. Let's adjust the content of it like this:

// test.js - exporting es6
export module App {
  export class SomeClass {
    getName(): string {
      return 'name';
    }
  }
  export class OtherClass {
    getName(): string {
      return 'name';
    }
  }
}

And now we can import it with these thre ways:

import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";

And we can consume imported stuff like this:

var a1: app1.App.SomeClass  = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();

var b1: app2.App.SomeClass  = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();

var c1: App.SomeClass  = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();

and call the method to see it in action:

console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())

Original part is trying to help to reduce the amount of complexity in usage of the namespace

Original part:

I would really strongly suggest to check this Q & A:

How do I use namespaces with TypeScript external modules?

Let me cite the first sentence:

Do not use "namespaces" in external modules.

Don't do this.

Seriously. Stop.

...

In this case, we just do not need module inside of test.ts. This could be the content of it adjusted test.ts:

export class SomeClass
{
    getName(): string
    {
        return 'name';
    }
}

Read more here

Export =

In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.

we can later consume it like this:

import App = require('./test');

var sc: App.SomeClass = new App.SomeClass();

sc.getName();

Read more here:

Optional Module Loading and Other Advanced Loading Scenarios

In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.

The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.

The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).

Why isn't Python very good for functional programming?

Let me demonstrate with a piece of code taken from an answer to a "functional" Python question on SO

Python:

def grandKids(generation, kidsFunc, val):
  layer = [val]
  for i in xrange(generation):
    layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
  return layer

Haskell:

grandKids generation kidsFunc val =
  iterate (concatMap kidsFunc) [val] !! generation

The main difference here is that Haskell's standard library has useful functions for functional programming: in this case iterate, concat, and (!!)

C# declare empty string array

Those curly things are sometimes hard to remember, that's why there's excellent documentation:

// Declare a single-dimensional array  
int[] array1 = new int[5];

PHP - iterate on string characters

For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

$string = "a sample string for testing";
$char = $string[4] // equals to m

I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):

$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m

This method is going to be faster cause we are using a real array and not assuming one to be an array.

Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

Using string[i]
0.24960017204285 Seconds

Using str_split
0.18720006942749 Seconds

Which means the second method is way faster.

Angular 2 two way binding using ngModel is not working

Add below code to following files.

app.component.ts

<input type="text" [(ngModel)]="fname" >
{{fname}}
export class appcomponent {
fname:any;
}

app.module.ts

import {FormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent],
bootstrap:    [ AppComponent ]
})

Hope this helps

Case insensitive comparison NSString

An alternative if you want more control than just case insensitivity is:

[someString compare:otherString options:NSCaseInsensitiveSearch];

Numeric search and diacritical insensitivity are two handy options.

How to draw a circle with text in the middle?

Adding a circle around a number can be easily done with CSS. This can be done using the border-radius property.

Here, we also used the display property set to "inline-block" to represent the element as an inline-level block container.

  span.circle {
  background: #010101;
  border-radius: 50%;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  color: #f1f1f1;
  display: inline-block;
  font-weight: bold;
  line-height: 40px;
  margin-right: 5px;
  text-align: center;
  width: 40px;
}
 <span class="circle">1</span>

How can I set size of a button?

This is how I did it.

            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("SAP Multiple Entries");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(10,10,10,10));
            frame.setLayout(new FlowLayout());
            frame.setSize(512, 512);
            JButton button = new JButton("Select File");
            button.setPreferredSize(new Dimension(256, 256));
            panel.add(button);

            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();

                        keep = selectedFile.getAbsolutePath();


                       // System.out.println(keep);
                        //out.println(file.flag); 
                       if(file.flag==true) {
                           JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
                       }
                       else{
                           JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
                       }
                    }
                }
            });
            frame.add(button);
            frame.pack();
            frame.setVisible(true);

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

Key existence check in HashMap

The Jon Skeet answer addresses well the two scenarios (map with null value and not null value) in an efficient way.

About the number entries and the efficiency concern, I would like add something.

I have a HashMap with say a 1.000 entries and I am looking at improving the efficiency. If the HashMap is being accessed very frequently, then checking for the key existence at every access will lead to a large overhead.

A map with 1.000 entries is not a huge map.
As well as a map with 5.000 or 10.000 entries.
Map are designed to make fast retrieval with such dimensions.

Now, it assumes that hashCode() of the map keys provides a good distribution.

If you may use an Integer as key type, do it.
Its hashCode() method is very efficient since the collisions are not possible for unique int values :

public final class Integer extends Number implements Comparable<Integer> {
    ...
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    public static int hashCode(int value) {
        return value;
    }
    ...
}

If for the key, you have to use another built-in type as String for example that is often used in Map, you may have some collisions but from 1 thousand to some thousands of objects in the Map, you should have very few of it as the String.hashCode() method provides a good distribution.

If you use a custom type, override hashCode() and equals() correctly and ensure overall that hashCode() provides a fair distribution.
You may refer to the item 9 of Java Effective refers it.
Here's a post that details the way.

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

apt-get for Cygwin?

This got it working for me:

curl https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg > \
apt-cyg && install apt-cyg /bin

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

How to do a JUnit assert on a message in a logger

Mocking is an option here, although it would be hard, because loggers are generally private static final - so setting a mock logger wouldn't be a piece of cake, or would require modification of the class under test.

You can create a custom Appender (or whatever it's called), and register it - either via a test-only configuration file, or runtime (in a way, dependent on the logging framework). And then you can get that appender (either statically, if declared in configuration file, or by its current reference, if you are plugging it runtime), and verify its contents.

What is the difference between Java RMI and RPC?

The difference between RMI and RPC is that:

  • RMI as the name indicates Remote Method Invoking: it invokes a method or an object. And
  • RPC it invokes a function.

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

Access non-numeric Object properties by index?

If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead

var keys = []
var obj = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
}
for (var key in obj){
    keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])

Creating a new dictionary in Python

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

Convert Dictionary to JSON in Swift

This works for me:

import SwiftyJSON

extension JSON {
    
    mutating func appendIfKeyValuePair(key: String, value: Any){
        if var dict = self.dictionaryObject {
            dict[key] = value
            self = JSON(dict)
        }
    }
}

Usage:

var data: JSON = []

data.appendIfKeyValuePair(key: "myKey", value: "myValue")

Does Python have an ordered set?

The answer is no, but you can use collections.OrderedDict from the Python standard library with just keys (and values as None) for the same purpose.

Update: As of Python 3.7 (and CPython 3.6), standard dict is guaranteed to preserve order and is more performant than OrderedDict. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict.)

Here's an example of how to use dict as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict class method fromkeys() to create a dict, then simply ask for the keys() back.

>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']

>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']

How do I run PHP code when a user clicks on a link?

If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>

Port 443 in use by "Unable to open process" with PID 4

Some process is using this port, so you can change the port that is used by xampp, to be able to use it. For this job you have to do this:

1- Open httpd-ssl.conf in xampp\apache\conf\extra

2- Look for the line containing Listen 443

3- Change port number to anything you want. I use 4430. ex. Listen 4430.

4- Replace every 443 strings in that file with 4430.

5- Save the file.

SQL Server Creating a temp table for this query

If you want to just create a temp table inside the query that will allow you to do something with the results that you deposit into it you can do something like the following:

DECLARE @T1 TABLE (
Item 1 VARCHAR(200)
, Item 2 VARCHAR(200)
, ...
, Item n VARCHAR(500)
)

On the top of your query and then do an

INSERT INTO @T1
SELECT
FROM
(...)

Check if object value exists within a Javascript array of objects and if not add a new object to array

I like Andy's answer, but the id isn't going to necessarily be unique, so here's what I came up with to create a unique ID also. Can be checked at jsfiddle too. Please note that arr.length + 1 may very well not guarantee a unique ID if anything had been removed previously.

var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';

// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));

function tryAdd(name, array) {
    var found = false;
    var i = 0;
    var maxId = 1;
    for (i in array) {
        // Check max id
        if (maxId <= array[i].id)
            maxId = array[i].id + 1;

        // Don't need to add if we find it
        if (array[i].username === name)
            found = true;
    }

    if (!found)
        array[++i] = { id: maxId, username: name };
}

Maven2: Best practice for Enterprise Project (EAR file)

i have made a github repository to show what i think is a good (or best practices) startup project structure...

https://github.com/StefanHeimberg/stackoverflow-1134894

some keywords:

  • Maven 3
  • BOM (DependencyManagement of own dependencies)
  • Parent for all Projects (DependencyManagement from external dependencies and PluginManagement for global Project configuration)
  • JUnit / Mockito / DBUnit
  • Clean War project without WEB-INF/lib because dependencies are in EAR/lib folder.
  • Clean Ear project.
  • Minimal deployment descriptors for Java EE7
  • No Local EJB Interface because @LocalBean is sufficient.
  • Minimal maven configuration through maven user properties
  • Actual Deployment Descriptors for Servlet 3.1 / EJB 3.2 / JPA 2.1
  • usage of macker-maven-plugin to check architecture rules
  • Integration Tests enabled, but skipped. (skipITs=false) useful to enable on CI Build Server

Maven Output:

Reactor Summary:

MyProject - BOM .................................... SUCCESS [  0.494 s]
MyProject - Parent ................................. SUCCESS [  0.330 s]
MyProject - Common ................................. SUCCESS [  3.498 s]
MyProject - Persistence ............................ SUCCESS [  1.045 s]
MyProject - Business ............................... SUCCESS [  1.233 s]
MyProject - Web .................................... SUCCESS [  1.330 s]
MyProject - Application ............................ SUCCESS [  0.679 s]
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.817 s
Finished at: 2015-01-27T00:51:59+01:00
Final Memory: 24M/207M
------------------------------------------------------------------------

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

python save image from url

A sample code that works for me on Windows:

import requests

with open('pic1.jpg', 'wb') as handle:
        response = requests.get(pic_url, stream=True)

        if not response.ok:
            print response

        for block in response.iter_content(1024):
            if not block:
                break

            handle.write(block)

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

PHP CSV string to array

You can convert CSV string to Array with this function.

    function csv2array(
        $csv_string,
        $delimiter = ",",
        $skip_empty_lines = true,
        $trim_fields = true,
        $FirstLineTitle = false
    ) {
        $arr = array_map(
            function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
                if ($FirstLineTitle && !$FirstLine) {
                    $FirstLine = explode( $delimiter, $result[0] );
                }
                $lineResult = array_map(
                    function ( $field ) {
                        return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
                    },
                    $trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
                );
                return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
            },
            ($result = preg_split(
                $skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
                preg_replace_callback(
                    '/"(.*?)"/s',
                    function ( $field ) {
                        return urlencode( utf8_encode( $field[1] ) );
                    },
                    $enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
                )
            ))
        );
        return $FirstLineTitle ? array_splice($arr, 1) : $arr;
    }

"make clean" results in "No rule to make target `clean'"

This works for me. Are you sure you're indenting with tabs?

CC = gcc
CFLAGS = -g -pedantic -O0 -std=gnu99 -m32 -Wall
PROGRAMS = digitreversal
all : $(PROGRAMS)
digitreversal : digitreversal.o
    [tab]$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

.PHONY: clean
clean:
    [tab]@rm -f $(PROGRAMS) *.o core

Echo equivalent in PowerShell for script testing

By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:

$filesizecounter = 8096
"filesizecounter : $filesizecounter"

Of course, you do give up some flexibility when not using the Write-* methods.

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

Permission denied when launch python script via bash

#strace ./scripts/replace-md5sums.py

git with IntelliJ IDEA: Could not read from remote repository

You need to Generate a new SSH key and add it to your ssh-agent. For That you should follow this link.

After you create the public key and add it to your github account, you should use Built-in (not Native) option under Setting-> Version Control -> Git -> SSH executable in your Intellij Idea.

Set the maximum character length of a UITextField in Swift

I use this step, first Set delegate texfield in viewdidload.

    override func viewDidLoad() {
        super.viewDidLoad()

        textfield.delegate = self

    }

and then shouldChangeCharactersIn after you include UITextFieldDelegate.

extension viewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                let newLength = (textField.text?.utf16.count)! + string.utf16.count - range.length
                if newLength <= 8 { 
                    return true
                } else {
                    return false
                }
            }
    }

Error when deploying an artifact in Nexus

I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.

In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.

sorting a vector of structs

Use a comparison function:

bool compareByLength(const data &a, const data &b)
{
    return a.word.size() < b.word.size();
}

and then use std::sort in the header #include <algorithm>:

std::sort(info.begin(), info.end(), compareByLength);

Android YouTube app Play Video Intent

This will work if youtube app installed. If not, a chooser will show up to select other application:

Uri uri = Uri.parse( "https://www.youtube.com/watch?v=bESGLojNYSo" );
uri = Uri.parse( "vnd.youtube:" + uri.getQueryParameter( "v" ) );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );

How to parse a CSV file using PHP

Handy one liner to parse a CSV file into an array

$csv = array_map('str_getcsv', file('data.csv'));

what is Array.any? for javascript

polyfill* :

Array.prototype.any=function(){
    return (this.some)?this.some(...arguments):this.filter(...arguments).reduce((a,b)=> a || b)
};

If you want to call it as Ruby , that it means .any not .any(), use :

Object.defineProperty( Array.prototype, 'any', {
  get: function ( ) { return (this.some)?this.some(function(e){return e}):this.filter(function(e){return e}).reduce((a,b)=> a || b) }
} ); 

__

`* : https://en.wikipedia.org/wiki/Polyfill

How to use string.substr() function?

As shown here, the second argument to substr is the length, not the ending position:

string substr ( size_t pos = 0, size_t n = npos ) const;

Generate substring

Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.

Your line b = a.substr(i,i+1); will generate, for values of i:

substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45  (since your string stops there).

What you need is b = a.substr(i,2);

You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:

b = a.substr(i,2);
cout << b << " ";

In fact, the entire thing could be more simply written as:

#include <iostream>
#include <string>
using namespace std;
int main(void) {
    string a;
    cin >> a;
    for (int i = 0; i < a.size() - 1; i++)
        cout << a.substr(i,2) << " ";
    cout << endl;
    return 0;
}

How to order by with union in SQL?

Can use this:

Select id,name,age
From Student
Where age < 15
Union ALL
SELECT * FROM (Select id,name,age
From Student
Where Name like "%a%")

Visual Studio keyboard shortcut to display IntelliSense

In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.

Ctrl + , (comma)

Enter image description here

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {
      $('#firstname').val($('#name').val());
    });
});

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

Excel compare two columns and highlight duplicates

There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).

So for A1, you can set a conditional format using the following formula:

=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))

Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.

What the above formula is doing:

  • VLOOKUP is looking up the value of Cell A1 (first parameter) against the whole of column B ($B:$B), in the first column (that's the 3rd parameter, redundant here, but typically VLOOKUP looks up a table rather than a column). The last parameter, FALSE, specifies that the match must be exact rather than just the closest match.
  • VLOOKUP will return #ISNA if no match is found, so the NOT(ISNA(...)) returns true for all cells which have a match in column B.

Can you write nested functions in JavaScript?

The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.

var foo = function () { alert('default function'); }

function pickAFunction(a_or_b) {
    var funcs = {
        a: function () {
            alert('a');
        },
        b: function () {
            alert('b');
        }
    };
    foo = funcs[a_or_b];
}

foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();

How to convert hex string to Java string?

First of all read in the data, then convert it to byte array:

 byte b = Byte.parseByte(str, 16); 

and then use String constructor:

new String(byte[] bytes) 

or if the charset is not system default then:

new String(byte[] bytes, String charsetName) 

Tomcat won't stop or restart

FIRST --> rm catalina.engine

THEN -->./startup.sh

NEXT TIME you restart --> ./shutdown.sh -force

How do I assign a port mapping to an existing Docker container?

Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network?

The best solution would be using reversed proxy within the same network

  1. Create a new network if your previous container not in any named ones.

    docker network create my_network

  2. Join your existing container to the created network

    docker network connect my_network my_existing_container

  3. Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network

    docker run -d --name nginx --network my_network -p 9000:9000 nginx

    Optionally remove the default.conf in nginx

    docker exec nginx rm /etc/nginx/conf.d/default.conf

  4. Create a new nginx config

    server
    {
        listen 9000;
    
        location / {
            proxy_pass http://my_existing_container:9000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
    

    Copy the config to nginx container.

    docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf

  5. Restart nginx

    docker restart nginx

Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.

Edit:

To reverse proxy non-http services, the config file is a bit different. Here is a simple example:

upstream my_service {
    server my_existing_container:9000;
}

server {
    listen 9000;
    proxy_pass my_service;
}

How to decode jwt token in javascript without using a library?

As "window" object is not present in nodejs environment, we could use the following lines of code :

let base64Url = token.split('.')[1]; // token you get
let base64 = base64Url.replace('-', '+').replace('_', '/');
let decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));

It's working for me perfectly. Hope it helps.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

From the Apple Developer Forum (account required):

"The compiler and linker are capable of using features and performing optimizations that do not work on older OS versions. -mmacosx-version-min tells the tools what OS versions you need to work with, so the tools can disable optimizations that won't run on those OS versions. If you need to run on older OS versions then you must use this flag.

"The downside to -mmacosx-version-min is that the app's performance may be worse on newer OS versions then it could have been if it did not need to be backwards-compatible. In most cases the differences are small."

How to get the selected radio button value using js

Use:

document.querySelector('#elementId:checked').value;

This will return the value of the selected radio button.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

Correct modification of state arrays in React.js

this.setState({
  arrayvar: [...this.state.arrayvar, ...newelement]
})

How to handle query parameters in angular 2

For Angular 4

Url:

http://example.com/company/100

Router Path :

const routes: Routes = [
  { path: 'company/:companyId', component: CompanyDetailsComponent},

]

Component:

@Component({
  selector: 'company-details',
  templateUrl: './company.details.component.html',
  styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
   companyId: string;

   constructor(private router: Router, private route: ActivatedRoute) {
          this.route.params.subscribe(params => {
          this.companyId = params.companyId;
          console.log('companyId :'+this.companyId);
     }); 
  }
}

Console Output:

companyId : 100

Peak memory usage of a linux/unix process

If the process runs for at least a couple seconds, then you can use the following bash script, which will run the given command line then print to stderr the peak RSS (substitute for rss any other attribute you're interested in). It's somewhat lightweight, and it works for me with the ps included in Ubuntu 9.04 (which I can't say for time).

#!/usr/bin/env bash
"$@" & # Run the given command line in the background.
pid=$! peak=0
while true; do
  sleep 1
  sample="$(ps -o rss= $pid 2> /dev/null)" || break
  let peak='sample > peak ? sample : peak'
done
echo "Peak: $peak" 1>&2

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Framework

Windows Forms, ASP.NET and WPF application must be developed using .NET Framework library.

.NET Standard

Xamarin, iOS and Mac OS X application must be developed using .NET Standard library

.NET Core

Universal Windows Platform (UWP) and Linux application must be developed using .NET Core library. The API is implemented in C++ and you can using the C++, VB.NET, C#, F# and JavaScript languages.NET

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

How to pass multiple parameters in thread in VB

In addition to what Dario stated about the Delegates you could execute a delegate with several parameters:

Predefine your delegate:

Private Delegate Sub TestThreadDelegate(ByRef goodList As List(Of String), ByVal coolvalue As Integer)

Get a handle to the delegate, create parameters in an array, DynamicInvoke on the Delegate:

Dim tester As TestThreadDelegate = AddressOf Me.testthread
Dim params(1) As Object
params(0) = New List(Of String)
params(1) = 0

tester.DynamicInvoke(params)

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I had tried everything I could find on the net including the methods that have been given on this answer. After almost trying to solve the problem for whole day I have found the solution that have worked for me like a charm.

in the file WebApiConfig in folder App_Start, comment all the lines of code and add the following code:

`public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();
        var enableCorsAttribute = new EnableCorsAttribute("*",
                                           "Origin, Content-Type, Accept",
                                           "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            //routeTemplate: "api/{controller}/{id}",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Formatters.Add(new BrowserJsonFormatter());
    }

    public class BrowserJsonFormatter : JsonMediaTypeFormatter
    {
        public BrowserJsonFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            this.SerializerSettings.Formatting = Formatting.Indented;
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }`

Sending mail from Python using SMTP

The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

Can Mysql Split a column?

Here is another variant I posted on related question. The REGEX check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

How to allow only one radio button to be checked?

Give them the same name, and it will work. By definition Radio buttons will only have one choice, while check boxes can have many.

<input type="radio" name="Radio1" />

How to use ng-repeat without an html element

If you use ng > 1.2, here is an example of using ng-repeat-start/end without generating unnecessary tags:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script>_x000D_
      angular.module('mApp', []);_x000D_
    </script>_x000D_
  </head>_x000D_
  <body ng-app="mApp">_x000D_
    <table border="1" width="100%">_x000D_
      <tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
      <tr>_x000D_
        <td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
        <td>{{elem.v[0]}}</td>_x000D_
      </tr>_x000D_
      <tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
        <td>{{v}}</td>_x000D_
      </tr>_x000D_
_x000D_
      <tr ng-if="0" ng-repeat-end></tr>_x000D_
    </table>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The important point: for tags used for ng-repeat-start and ng-repeat-end set ng-if="0", to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->), and there will be no garbage.

How to change TextField's height and width?

Screenshot:

enter image description here


Widget _buildTextField() {
  final maxLines = 5;

  return Container(
    margin: EdgeInsets.all(12),
    height: maxLines * 24.0,
    child: TextField(
      maxLines: maxLines,
      decoration: InputDecoration(
        hintText: "Enter a message",
        fillColor: Colors.grey[300],
        filled: true,
      ),
    ),
  );
}

How to automatically allow blocked content in IE?

That's something I'm not sure that you can change through the HTML of the webpage itself, it's a client-side setting to tell their browser if they want security to be high. Most other browsers will not do this but from what I'm aware of this is not possible to stop unless the user disables the feature.

Does it still do what you want it to do after you click on 'Allow'? If so then it shouldn't be too much of a problem

How do I expire a PHP session after 30 minutes?

This was an eye-opener for me, what Christopher Kramer wrote in 2014 on https://www.php.net/manual/en/session.configuration.php#115842

On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). [...]

React Native fetch() Network Request Failed

React Native Docs gives the answer for this.

Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

React Native Docs -> Integration With Existing Apps -> Test your integration -> Add App Transport Security exception

Get everything after and before certain character in SQL Server

 declare @T table
  (
  Col varchar(20)
  )



  insert into @T 
  Select 'images/test1.jpg'
  union all
  Select 'images/test2.png'
  union all
  Select 'images/test3.jpg'
  union all
  Select 'images/test4.jpeg'
  union all
  Select 'images/test5.jpeg'

 Select substring( LEFT(Col,charindex('.',Col)-1),charindex('/',Col)+1,len(LEFT(Col,charindex('.',Col)-1))-1 )
from @T

How to copy a row from one SQL Server table to another

As long as there are no identity columns you can just

INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

What are the different types of indexes, what are the benefits of each?

Conventional wisdom suggests that index choice should be based on cardinality. They'll say,

For a low cardinality column like GENDER, use bitmap. For a high cardinality like LAST_NAME, use b-tree.

This is not the case with Oracle, where index choice should instead be based on the type of application (OLTP vs. OLAP). DML on tables with bitmap indexes can cause serious lock contention. On the other hand, the Oracle CBO can easily combine multiple bitmap indexes together, and bitmap indexes can be used to search for nulls. As a general rule:

For an OLTP system with frequent DML and routine queries, use btree. For an OLAP system with infrequent DML and adhoc queries, use bitmap.

I'm not sure if this applies to other databases, comments are welcome. The following articles discuss the subject further:

C# Parsing JSON array of objects

Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future

 JArray array = JArray.Parse(jsonString);
 foreach (JObject obj in array.Children<JObject>())
 {
     foreach (JProperty singleProp in obj.Properties())
     {
         string name = singleProp.Name;
         string value = singleProp.Value.ToString();
         //Do something with name and value
         //System.Windows.MessageBox.Show("name is "+name+" and value is "+value);
      }
 }

This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;

Using Git with Visual Studio

In Jan 2013, Microsoft announced that they are adding full Git support into all their ALM products. They have published a plugin for Visual Studio 2012 that adds Git source control integration.

Alternatively, there is a project called Git Extensions that includes add-ins for Visual Studio 2005, 2008, 2010 and 2012, as well as Windows Explorer integration. It's regularly updated and having used it on a couple of projects, I've found it very useful.

Another option is Git Source Control Provider.

How to replace case-insensitive literal substrings in Java

For non-Unicode characters:

String result = Pattern.compile("(?i)????????", 
Pattern.UNICODE_CASE).matcher(source).replaceAll("???");

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

Cannot access a disposed object - How to fix?

Looking at the error stack trace, it seems your timer is still active. Try to cancel the timer upon closing the form (i.e. in the form's OnClose() method). This looks like the cleanest solution.

Can you hide the controls of a YouTube embed without enabling autoplay?

To remove you tube controls and title you can do something like this

_x000D_
_x000D_
<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>
_x000D_
_x000D_
_x000D_

code with output

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

Performing Breadth First Search recursively

Here is a BFS recursive traversal Python implementation, working for a graph with no cycle.

def bfs_recursive(level):
    '''
     @params level: List<Node> containing the node for a specific level.
    '''
    next_level = []
    for node in level:
        print(node.value)
        for child_node in node.adjency_list:
            next_level.append(child_node)
    if len(next_level) != 0:
        bfs_recursive(next_level)


class Node:
    def __init__(self, value):
        self.value = value
        self.adjency_list = []

Requery a subform from another form?

You must use the name of the subform control, not the name of the subform, though these are often the same:

 Forms![MainForm]![subform control name Name].Form.Requery

Or, if you are on the main form:

 Me.[subform control name Name].Form.Requery

More Info: http://www.mvps.org/access/forms/frm0031.htm

Set icon for Android application

If you have an SVG icon, you can use this script to generate your android icon set.

Load json from local file with http.get() in angular 2

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

How to view user privileges using windows cmd?

Use whoami /priv command to list all the user privileges.

GridView - Show headers on empty data source

Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check

Trust Store vs Key Store - creating with keytool

keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Guys in some PC's this issue is caused by antivirus programs AFTER upgrading to the latest android studio and gradle version. In my case I tore my system apart troubleshooting everything only to find out that Commodo Internet security was responsible for not letting the gradle daemon run.

After safelisting the process everything runs smoothly. PLEASE NOTE that everything was OK before updating. The issue came up only after the update without changing anything in the antivirus/firewall program.

What is the return value of os.system() in Python?

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

00000000    00000000
exit code   signal num

Example 1 - command exit with code 1

os.system('command') #it returns 256
256 in 16 bits -  00000001 00000000
Exit code is 00000001 which means 1

Example 2 - command exit with code 3

os.system('command') # it returns 768
768 in 16 bits  - 00000011 00000000
Exit code is 00000011 which means 3

Now try with signal - Example 3 - Write a program which sleep for long time use it as command in os.system() and then kill it by kill -15 or kill -9

os.system('command') #it returns signal num by which it is killed
15 in bits - 00000000 00001111
Signal num is 00001111 which means 15

You can have a python program as command = 'python command.py'

import sys
sys.exit(n)  # here n would be exit code

In case of c or c++ program you can use return from main() or exit(n) from any function #

Note - This is applicable on unix

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

os.wait()

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

Availability: Unix

.

How to use comparison operators like >, =, < on BigDecimal

Using com.ibm.etools.marshall.util.BigDecimalRange util class of IBM one can compare if BigDecimal in range.

boolean isCalculatedSumInRange = BigDecimalRange.isInRange(low, high, calculatedSum);

font size in html code

Try this:

<html>
  <table>
    <tr>
      <td style="padding-left: 5px;
                 padding-bottom: 3px;">
        <strong style="font-size: 35px;">Datum:</strong><br />
        November 2010 
      </td>
    </tr>
  </table>
</html>

Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.

Java - Find shortest path between 2 points in a distance weighted map

Like SplinterReality said: There's no reason not to use Dijkstra's algorithm here.

The code below I nicked from here and modified it to solve the example in the question.

import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class Vertex implements Comparable<Vertex>
{
    public final String name;
    public Edge[] adjacencies;
    public double minDistance = Double.POSITIVE_INFINITY;
    public Vertex previous;
    public Vertex(String argName) { name = argName; }
    public String toString() { return name; }
    public int compareTo(Vertex other)
    {
        return Double.compare(minDistance, other.minDistance);
    }

}


class Edge
{
    public final Vertex target;
    public final double weight;
    public Edge(Vertex argTarget, double argWeight)
    { target = argTarget; weight = argWeight; }
}

public class Dijkstra
{
    public static void computePaths(Vertex source)
    {
        source.minDistance = 0.;
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        while (!vertexQueue.isEmpty()) {
            Vertex u = vertexQueue.poll();

            // Visit each edge exiting u
            for (Edge e : u.adjacencies)
            {
                Vertex v = e.target;
                double weight = e.weight;
                double distanceThroughU = u.minDistance + weight;
                if (distanceThroughU < v.minDistance) {
                    vertexQueue.remove(v);

                    v.minDistance = distanceThroughU ;
                    v.previous = u;
                    vertexQueue.add(v);
                }
            }
        }
    }

    public static List<Vertex> getShortestPathTo(Vertex target)
    {
        List<Vertex> path = new ArrayList<Vertex>();
        for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
            path.add(vertex);

        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args)
    {
        // mark all the vertices 
        Vertex A = new Vertex("A");
        Vertex B = new Vertex("B");
        Vertex D = new Vertex("D");
        Vertex F = new Vertex("F");
        Vertex K = new Vertex("K");
        Vertex J = new Vertex("J");
        Vertex M = new Vertex("M");
        Vertex O = new Vertex("O");
        Vertex P = new Vertex("P");
        Vertex R = new Vertex("R");
        Vertex Z = new Vertex("Z");

        // set the edges and weight
        A.adjacencies = new Edge[]{ new Edge(M, 8) };
        B.adjacencies = new Edge[]{ new Edge(D, 11) };
        D.adjacencies = new Edge[]{ new Edge(B, 11) };
        F.adjacencies = new Edge[]{ new Edge(K, 23) };
        K.adjacencies = new Edge[]{ new Edge(O, 40) };
        J.adjacencies = new Edge[]{ new Edge(K, 25) };
        M.adjacencies = new Edge[]{ new Edge(R, 8) };
        O.adjacencies = new Edge[]{ new Edge(K, 40) };
        P.adjacencies = new Edge[]{ new Edge(Z, 18) };
        R.adjacencies = new Edge[]{ new Edge(P, 15) };
        Z.adjacencies = new Edge[]{ new Edge(P, 18) };


        computePaths(A); // run Dijkstra
        System.out.println("Distance to " + Z + ": " + Z.minDistance);
        List<Vertex> path = getShortestPathTo(Z);
        System.out.println("Path: " + path);
    }
}

The code above produces:

Distance to Z: 49.0
Path: [A, M, R, P, Z]

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

How to find the index of an element in an array in Java?

That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

There is also the Arrays class which shortens above code:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));

What is username and password when starting Spring Boot with Tomcat?

When overriding

spring.security.user.name=
spring.security.user.password=

in application.properties, you don't need " around "username", just use username. Another point, instead of storing raw password, encrypt it with bcrypt/scrypt and store it like

spring.security.user.password={bcrypt}encryptedPassword

How to clear all input fields in a specific div with jQuery?

$.each($('.fetch_results input'), function(idx, input){
  $(input).val('');
});

How to override Bootstrap's Panel heading background color?

Another way to change the color is remove the default class and replace , in the panel using the classes of bootstrap.

example:

<div class="panel panel-danger">
  <div class="panel-heading">
  </div>
</div>

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Find distance between two points on map using Google Map API V2

This is an old question with old answers. I want to highlight an updated way of calculating distance between two points. By now we should be familiar with the utility class, "SphericalUtil". You can retrieve the distance using that.

double distance = SphericalUtil.computeDistanceBetween(origin, dest);

Upgrade version of Pandas

Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. ...

  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...

  4. Reopen Command prompt window

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

401 Unauthorized: Access is denied due to invalid credentials

I faced similar issue.

The folder was shared and Authenticated Users permission was provided, which solved my issue.

How to add multiple files to Git at the same time

To add all the changes you've made:

git add .

To commit them:

git commit -m "MY MESSAGE HERE" #-m is the message flag

You can put those steps together like this:

git commit -a -m "MY MESSAGE HERE"

To push your committed changes from your local repository to your remote repository:

git push origin master

You might have to type in your username/password for github after this. Here's a good primer on using git. A bit old, but it covers what's going on really well.

Automatically start forever (node) on system restart

You can use the following command in your shell to start your node forever:

forever app.js //my node script

You need to keep in mind that the server on which your app is running should always be kept on.

How does the "view" method work in PyTorch?

I really liked @Jadiel de Armas examples.

I would like to add a small insight to how elements are ordered for .view(...)

  • For a Tensor with shape (a,b,c), the order of it's elements are determined by a numbering system: where the first digit has a numbers, second digit has b numbers and third digit has c numbers.
  • The mapping of the elements in the new Tensor returned by .view(...) preserves this order of the original Tensor.

Show week number with Javascript?

If you want something that works and is future-proof, use a library like MomentJS.

moment(date).week();
moment(date).isoWeek()

http://momentjs.com/docs/#/get-set/week/

Is there a C++ decompiler?

You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.

If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.

php - get numeric index of associative array

a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:

 protected function getFirstPosition(array$array, $content, $key = true) {

  $index = 0;
  if ($key) {
   foreach ($array as $key => $value) {
    if ($key == $content) {
     return $index;
    }
    $index++;
   }
  } else {
   foreach ($array as $key => $value) {
    if ($value == $content) {
     return $index;
    }
    $index++;
   }
  }
 }

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

ScrollIntoView() causing the whole page to move

You could use scrollTop instead of scrollIntoView():

var target = document.getElementById("target");
target.parentNode.scrollTop = target.offsetTop;

jsFiddle: http://jsfiddle.net/LEqjm/

If there's more than one scrollable element that you want to scroll, you'll need to change the scrollTop of each one individually, based on the offsetTops of the intervening elements. This should give you the fine-grained control to avoid the problem you're having.

EDIT: offsetTop isn't necessarily relative to the parent element - it's relative to the first positioned ancestor. If the parent element isn't positioned (relative, absolute or fixed), you may need to change the second line to:

target.parentNode.scrollTop = target.offsetTop - target.parentNode.offsetTop;

How to export dataGridView data Instantly to Excel on button click?

I'm adding this answer because none of the other methods use OpenXMLWriter, despite the fact that it is faster than OpenXML DOM and both faster and more reliable than COM/Interop, and because some of the other methods use the clipboard, which I would caution against, as it's output is unreliable.

The details can be found in my answer in the link below, however that example is for a DataTable, but you can adapt it to using a DataGridView by just changing the row/column loops to reference a dgv instead of a dt.

How to export DataTable to Excel

Postgres "psql not recognized as an internal or external command"

Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:

C:\Program Files\PostgreSQL\11\bin\bin

Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.

How to list the tables in a SQLite database file that was opened with ATTACH?

To list the tables you can also do:

SELECT name FROM sqlite_master
WHERE type='table';

How to get file name when user select a file via <input type="file" />?

I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

Here is the code.

_x000D_
_x000D_
function GetFileSizeNameAndType()_x000D_
        {_x000D_
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
        var totalFileSize = 0;_x000D_
_x000D_
        // VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
        if (fi.files.length > 0)_x000D_
        {_x000D_
            // RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
            for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
            {_x000D_
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
                var fsize = fi.files.item(i).size;_x000D_
                totalFileSize = totalFileSize + fsize;_x000D_
                document.getElementById('fp').innerHTML =_x000D_
                document.getElementById('fp').innerHTML_x000D_
                +_x000D_
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
                +_x000D_
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
                +_x000D_
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
            }_x000D_
        }_x000D_
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
    }
_x000D_
    <p>_x000D_
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
    </p>_x000D_
_x000D_
    <div id="fp"></div>_x000D_
    <p>_x000D_
        <div id="divTotalSize"></div>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

It'll perform file outputs like these on selecting Snapshot of a sample output of this code

Style disabled button with CSS

Need to apply css as belows:

button:disabled,button[disabled]{
    background-color: #cccccc;
    cursor:not-allowed !important;
  }

How do you align left / right a div without using float?

you could use things like display: inline-block but I think you would need to set up another div to move it over, if there is nothing going to the left of the button you could use margins to move it into place.

Alternatively but not a good solution, you could position tags; put the encompassing div as position: relative and then the div of the button as position: absolute; right: 0, but like I said this is probably not the best solution

HTML

<div class="parent">
  <div>Left Div</div>
  <div class="right">Right Div</div>
</div>

CSS

.parent {
  position: relative;
}
.right {
    position: absolute;
    right: 0;
}

Convert Rows to columns using 'Pivot' in SQL Server

Here is a revision of @Tayrn answer above that might help you understand pivoting a little easier:

This may not be the best way to do this, but this is what helped me wrap my head around how to pivot tables.

ID = rows you want to pivot

MY_KEY = the column you are selecting from your original table that contains the column names you want to pivot.

VAL = the value you want returning under each column.

MAX(VAL) => Can be replaced with other aggregiate functions. SUM(VAL), MIN(VAL), ETC...

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(MY_KEY) 
                from yt
                group by MY_KEY
                order by MY_KEY ASC
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
set @query = 'SELECT ID,' + @cols + ' from 
         (
            select ID, MY_KEY, VAL 
            from yt
        ) x
        pivot 
        (
            sum(VAL)
            for MY_KEY in (' + @cols + ')
        ) p '

        execute(@query);

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

Change/Get check state of CheckBox

This is an example of how I use this kind of thing:

HTML :

<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">

JAVASCRIPT :

function ThisIsTheFunction(temp,temp2) {
  if(temp2 == true) {
    document.getElementById(temp).style.visibility = "visible";
  } else {
    document.getElementById(temp).style.visibility = "hidden";
  }
}

How to make div go behind another div?

container can not come front to inner container. but try this below :

Css :
----------------------
.container { position:relative; }
    .div1 { width:100px; height:100px; background:#9C3; position:absolute; 
            z-index:1000; left:50px; top:50px; }
    .div2 { width:200px; height:200px; background:#900; }

HTMl : 
-----------------------
<div class="container">
    <div class="div1">
       Div1 content here .........
    </div>
    <div class="div2">
       Div2 contenet here .........
    </div>
</div>

How to set column header text for specific column in Datagridview C#

there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

    public Form1()
    {
        InitializeComponent();

        grid.Columns[0].HeaderText = "First Column"; 
        //..............
    }

More details are here at MSDN. More details about DataGrid are here.

How can I get the value of a registry key from within a batch script?

This works for me:

@echo OFF

setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command Processor"
set VALUE_NAME=DefaultColor

FOR /F "usebackq skip=4 tokens=1-3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
)

usebackq is needed since the command to REG QUERY uses double quotes.

skip=4 ignores all the output except for the line that has the value name, type and value, if it exists.

2^>nul prevents the error text from appearing. ^ is the escape character that lets you put the > in the for command.

When I run the script above as given, I get this output:

Value Name = DefaultColor
Value Type = REG_DWORD
Value Value = 0x0

If I change the value of VALUE_NAME to BogusValue then I get this:

"HKEY_CURRENT_USER\Software\Microsoft\Command Processor"\BogusValue not found.

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

A non-blocking read on a subprocess.PIPE in Python

Try the asyncproc module. For example:

import os
from asyncproc import Process
myProc = Process("myprogram.app")

while True:
    # check to see if process has ended
    poll = myProc.wait(os.WNOHANG)
    if poll != None:
        break
    # print any new output
    out = myProc.read()
    if out != "":
        print out

The module takes care of all the threading as suggested by S.Lott.

How do I fix the indentation of an entire file in Vi?

if you do not want to use :set paste, middle-click, set nopaste, you can also paste the content of the clipboard:

"*p
"+p

That way you don't have to leave normal mode. if you have to paste + or * depends on how you selected the text, see :help quoteplus.

There has been an error processing your request, Error log record number

Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server,

solution -1 :- Rename pub/local.xml.sample into local.xml or pub/local.xml into local.xml.sample if this is not work try solution 2

solution 2 :- go to php.ini file and increase max_execution time and fresh install magento confirm issue resolved

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

How can I clear the content of a file?

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

Where is adb.exe in windows 10 located?

Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe.

If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.

I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !

HTML inside Twitter Bootstrap popover

Add this to the bottom of your popper.js file:

Popper.Defaults.modifiers.computeStyle.gpuAcceleration = !(window.devicePixelRatio < 1.5 && /Win/.test(navigator.platform));

Source: https://github.com/twbs/bootstrap/issues/23590

Disabling right click on images using jquery

Would it be possible to leave the ability to right click and download just when done a separate watermark is placed on the image. Of course this won't prevent screen shots but thought it may be a good middle ground.

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Need to perform Wildcard (*,?, etc) search on a string using Regex

d* means that it should match zero or more "d" characters. So any string is a valid match. Try d+ instead!

In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like * becomes .* and ? becomes .?. Then your expression above becomes d.*

In Python, how do I use urllib to see if a website is 404 or 200?

For Python 3:

import urllib.request, urllib.error

url = 'http://www.google.com/asdfsf'
try:
    conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
    print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
    print('URLError: {}'.format(e.reason))
else:
    # 200
    # ...
    print('good')

How do I get started with Node.js

Use the source, Luke.

No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.

Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.

Cannot add or update a child row: a foreign key constraint fails

That error occurs when you want to add a foreign key with values that don't exist in the primary key of the parent table. You must be sure that the new foreign key UserID in table2 has values that exist in the table1 primary key, sometimes by default it is null or equal to 0.

You could first update all the fields of the foreign key in table2 with a value that exists in the primary key of table1.

update table2 set UserID = 1 where UserID is null

If you want to add different UserIDs you must modify each row with the values you want.

How to emit an event from parent to child?

In a parent component you can use @ViewChild() to access child component's method/variable.

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponent: NumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }
} 

Update:

Angular 8 onwards -

@ViewChild(NumberComponent, { static: false })

Traverse a list in reverse order in Python

You can use a negative index in an ordinary for loop:

>>> collection = ["ham", "spam", "eggs", "baked beans"]
>>> for i in range(1, len(collection) + 1):
...     print(collection[-i])
... 
baked beans
eggs
spam
ham

To access the index as though you were iterating forward over a reversed copy of the collection, use i - 1:

>>> for i in range(1, len(collection) + 1):
...     print(i-1, collection[-i])
... 
0 baked beans
1 eggs
2 spam
3 ham

To access the original, un-reversed index, use len(collection) - i:

>>> for i in range(1, len(collection) + 1):
...     print(len(collection)-i, collection[-i])
... 
3 baked beans
2 eggs
1 spam
0 ham

How to get column by number in Pandas?

One is a column (aka Series), while the other is a DataFrame:

In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])

In [2]: df
Out[2]:
   a  b
0  1  2
1  3  4

The column 'b' (aka Series):

In [3]: df['b']
Out[3]:
0    2
1    4
Name: b, dtype: int64

The subdataframe with columns (position) in [1]:

In [4]: df[[1]]
Out[4]:
   b
0  2
1  4

Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:

In [5]: df.iloc[:, [1]]
Out[5]:
   b
0  2
1  4

In [6]: df.loc[:, ['b']]
Out[6]:
   b
0  2
1  4

In [7]: df.loc[:, 'b']
Out[7]:
0    2
1    4
Name: b, dtype: int64

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Difference between "read commited" and "repeatable read"

My observation on initial accepted solution.

Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory

How to use (install) dblink in PostgreSQL?

It can be added by using:

$psql -d databaseName -c "CREATE EXTENSION dblink"

Linq to SQL how to do "where [column] in (list of values)"

I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat. The Concat method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:

The Method

// Given an array of id's
var ids = new Guid[] { ... };

// and a DataContext
var dc = new MyDataContext();

// start the queryable
var query = (
    from thing in dc.Things
    where thing.Id == ids[ 0 ]
    select thing 
);

// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
    // select that thing and concat to queryable
    query.Concat(
        from thing in dc.Things
        where thing.Id == ids[ i ]
        select thing
    );
}

Performance Test

This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.

I set up a test where I did 100 trials each of Concat and Contains where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat method comes out 5 - 10% faster, although one time the Contains method won by just a smidgen.

Is a Java hashmap search really O(1)?

This basically goes for most hash table implementations in most programming languages, as the algorithm itself doesn't really change.

If there are no collisions present in the table, you only have to do a single look-up, therefore the running time is O(1). If there are collisions present, you have to do more than one look-up, which drives down the performance towards O(n).

How do DATETIME values work in SQLite?

SQlite does not have a specific datetime type. You can use TEXT, REAL or INTEGER types, whichever suits your needs.

Straight from the DOCS

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

SQLite built-in Date and Time functions can be found here.

Pandas: Subtracting two date columns and the result being an integer

I feel that the overall answer does not handle if the dates 'wrap' around a year. This would be useful in understanding proximity to a date being accurate by day of year. In order to do these row operations, I did the following. (I had this used in a business setting in renewing customer subscriptions).

def get_date_difference(row, x, y):
    try:
        # Calcuating the smallest date difference between the start and the close date
        # There's some tricky logic in here to calculate for determining date difference
        # the other way around (Dec -> Jan is 1 month rather than 11)

        sub_start_date = int(row[x].strftime('%j')) # day of year (1-366)
        close_date = int(row[y].strftime('%j')) # day of year (1-366)

        later_date_of_year = max(sub_start_date, close_date) 
        earlier_date_of_year = min(sub_start_date, close_date)
        days_diff = later_date_of_year - earlier_date_of_year

# Calculates the difference going across the next year (December -> Jan)
        days_diff_reversed = (365 - later_date_of_year) + earlier_date_of_year
        return min(days_diff, days_diff_reversed)

    except ValueError:
        return None

Then the function could be:

dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

When I get this kind of error I had to update the data type by a notch. For Example, if I have it as "tiny int" change it to "small int" ~ Nita

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

'gulp' is not recognized as an internal or external command

Sorry that was a typo. You can either add node_modules to the end of your user's global path variable, or maybe check the permissions associated with that folder (node _modules). The error doesn't seem like the last case, but I've encountered problems similar to yours. I find the first solution enough for most cases. Just go to environment variables and add the path to node_modules to the last part of your user's path variable. Note I'm saying user and not system.

Just add a semicolon to the end of the variable declaration and add the static path to your node_module folder. ( Ex c:\path\to\node_module)

Alternatively you could:

In your CMD

PATH=%PATH%;C:\\path\to\node_module

EDIT

The last solution will work as long as you don't close your CMD. So, use the first solution for a permanent change.

How do I compile C++ with Clang?

Also, for posterity -- Clang (like GCC) accepts the -x switch to set the language of the input files, for example,

$ clang -x c++ some_random_file.txt

This mailing list thread explains the difference between clang and clang++ well: Difference between clang and clang++

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

Can Javascript read the source of any web page?

You can generate a XmlHttpRequest and request the page,and then use getResponseText() to get the content.

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

IIS: Display all sites and bindings in PowerShell

function Get-ADDWebBindings {
param([string]$Name="*",[switch]$http,[switch]$https)
    try {
    if (-not (Get-Module WebAdministration)) { Import-Module WebAdministration }
    Get-WebBinding | ForEach-Object { $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1' } | Sort | Get-Unique | Where-Object {$_ -like $Name} | ForEach-Object {
        $n=$_
        Get-WebBinding | Where-Object { ($_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1') -like $n } | ForEach-Object {
            if ($http -or $https) {
                if ( ($http -and ($_.protocol -like "http")) -or ($https -and ($_.protocol -like "https")) ) {
                    New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
                }
            } else {
                New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
            }
        }
    }
    }
    catch {
       $false
    }
}

Access host database from a docker container

Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways

  1. Sharing host network --net=host:

    docker run -it --net=host  myimage
    
  2. Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface

    user@ubuntu:~$ ifconfig
    docker0   Link encap:Ethernet  HWaddr 02:42:a4:a2:b2:f1  
      inet addr:172.17.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
      inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
    

Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.

  docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage

NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:

  1. Edit postgresql.conf to listen on all addresses. By default it will point to localhost.

    listen_addresses = '*'
    
  2. Edit pg_hba.conf to allow connections from all addresses. Add on the last line:

    host     all             all             0.0.0.0/0               md5
    

IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.

I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password) which should improve user experience.

From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.

Seeing your comment, this is how I would go about it:

  • Must be eight characters Long: You do not need a regex for this. Using the .Length property should be enough.

  • Including one uppercase letter: You can use the [A-Z]+ regular expression. If the string contains at least one upper case letter, this regular expression will yield true.

  • One special character: You can use either the \W which will match any character which is not a letter or a number or else, you can use something like so [!@#] to specify a custom list of special characters. Note though that characters such as $, ^, ( and ) are special characters in the regular expression language, so they need to be escaped like so: \$. So in short, you might use the \W.

  • Alphanumeric characters: Using the \w+ should match any letter and number and underscore.

Take a look at this tutorial for more information.

How to properly ignore exceptions

When you just want to do a try catch without handling the exception, how do you do it in Python?

This will help you to print what the exception is:( i.e. try catch without handling the exception and print the exception.)

import sys
try:
    doSomething()
except:
    print "Unexpected error:", sys.exc_info()[0]

Add table row in jQuery

This could also be done :

$("#myTable > tbody").html($("#myTable > tbody").html()+"<tr><td>my data</td><td>more data</td></tr>")

How do I search for files in Visual Studio Code?

Also works in ubuntu with Ctrl+E

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.

For example:

| v   | a   |  b  |   c |
+-----+-----+-----+-----+
| 1   | 1   |  1  |   1 |
| 10  | 10  | 10  |  10 |
| 100 | 100 | 100 | 100 |

Here a, b and c are using TINYINT(1), TINYINT(2) and TINYINT(3) respectively. As you can see, it pads the values on the left side using the display width.

It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1) still accepts [-128 .. 127].

How to force C# .net app to run only one instance in Windows?

another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public Main()
    {
        InitializeComponent();

        Process current = Process.GetCurrentProcess();
        string currentmd5 = md5hash(current.MainModule.FileName);
        Process[] processlist = Process.GetProcesses();
        foreach (Process process in processlist)
        {
            if (process.Id != current.Id)
            {
                try
                {
                    if (currentmd5 == md5hash(process.MainModule.FileName))
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        Environment.Exit(0);
                    }
                }
                catch (/* your exception */) { /* your exception goes here */ }
            }
        }
    }

    private string md5hash(string file)
    {
        string check;
        using (FileStream FileCheck = File.OpenRead(file))
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] md5Hash = md5.ComputeHash(FileCheck);
            check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
        }

        return check;
    }

it checks only md5 sums by process id.

if an instance of this application was found, it focuses the running application and exit itself.

you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.

may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.

python pandas dataframe to dictionary

Simplest solution:

df.set_index('id').T.to_dict('records')

Example:

df= pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
df.set_index('id').T.to_dict('records')

If you have multiple values, like val1, val2, val3,etc and u want them as lists, then use the below code:

df.set_index('id').T.to_dict('list')