Programs & Examples On #Certify

Android adding simple animations while setvisibility(view.Gone)

I was able to show/hide a menu this way:

MenuView.java (extends FrameLayout)

private final int ANIMATION_DURATION = 500;

public void showMenu()
{
    setVisibility(View.VISIBLE);
    animate()
            .alpha(1f)
            .setDuration(ANIMATION_DURATION)
            .setListener(null);
}

private void hideMenu()
{
    animate()
            .alpha(0f)
            .setDuration(ANIMATION_DURATION)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    setVisibility(View.GONE);
                }
            });
}

Source

Closing Bootstrap modal onclick

Close the modal box using javascript

$('#product-options').modal('hide');

Open the modal box using javascript

$('#product-options').modal('show');

Toggle the modal box using javascript

$('#myModal').modal('toggle');

Means close the modal if it's open and vice versa.

What version of javac built my jar?

There is no need to unpack the JAR (if one of the class names is known or is looked up e.g. using 7zip), so on Windows the following would be sufficient:

javap -cp log4j-core-2.5.jar -verbose org.apache.logging.log4j.core.Logger | findstr major

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

How to clean up R memory (without the need to restart my PC)?

There is only so much you can do with rm() and gc(). As suggested by Gavin Simpson, even if you free the actual memory in R, Windows often won't reclaim it until you close R or it is needed because all the apparent Windows memory fills up.

This usually isn't a problem. However, if you are running large loops this can sometimes lead to fragmented memory in the long term, such that even if you free the memory and restart R - the fragmented memory may prevent you allocating large chunks of memory. Especially if other applications were allocated fragmented memory while you were running R. rm() and gc() may delay the inevitable, but more RAM is better.

Android - Handle "Enter" in an EditText

I had a similar purpose. I wanted to resolve pressing the "Enter" key on the keyboard (which I wanted to customize) in an AutoCompleteTextView which extends TextView. I tried different solutions from above and they seemed to work. BUT I experienced some problems when I switched the input type on my device (Nexus 4 with AOKP ROM) from SwiftKey 3 (where it worked perfectly) to the standard Android keyboard (where instead of handling my code from the listener, a new line was entered after pressing the "Enter" key. It took me a while to handle this problem, but I don't know if it will work under all circumstances no matter which input type you use.

So here's my solution:

Set the input type attribute of the TextView in the xml to "text":

android:inputType="text"

Customize the label of the "Enter" key on the keyboard:

myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);

Set an OnEditorActionListener to the TextView:

myTextView.setOnEditorActionListener(new OnEditorActionListener()
{
    @Override
    public boolean onEditorAction(TextView v, int actionId,
        KeyEvent event)
    {
    boolean handled = false;
    if (event.getAction() == KeyEvent.KEYCODE_ENTER)
    {
        // Handle pressing "Enter" key here

        handled = true;
    }
    return handled;
    }
});

I hope this can help others to avoid the problems I had, because they almost drove me nuts.

What is the most accurate way to retrieve a user's correct IP address in PHP?

I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.

Is there a performance difference between i++ and ++i in C?

I can think of a situation where postfix is slower than prefix increment:

Imagine a processor with register A is used as accumulator and it's the only register used in many instructions (some small microcontrollers are actually like this).

Now imagine the following program and their translation into a hypothetical assembly:

Prefix increment:

a = ++b + c;

; increment b
LD    A, [&b]
INC   A
ST    A, [&b]

; add with c
ADD   A, [&c]

; store in a
ST    A, [&a]

Postfix increment:

a = b++ + c;

; load b
LD    A, [&b]

; add with c
ADD   A, [&c]

; store in a
ST    A, [&a]

; increment b
LD    A, [&b]
INC   A
ST    A, [&b]

Note how the value of b was forced to be reloaded. With prefix increment, the compiler can just increment the value and go ahead with using it, possibly avoid reloading it since the desired value is already in the register after the increment. However, with postfix increment, the compiler has to deal with two values, one the old and one the incremented value which as I show above results in one more memory access.

Of course, if the value of the increment is not used, such as a single i++; statement, the compiler can (and does) simply generate an increment instruction regardless of postfix or prefix usage.


As a side note, I'd like to mention that an expression in which there is a b++ cannot simply be converted to one with ++b without any additional effort (for example by adding a - 1). So comparing the two if they are part of some expression is not really valid. Often, where you use b++ inside an expression you cannot use ++b, so even if ++b were potentially more efficient, it would simply be wrong. Exception is of course if the expression is begging for it (for example a = b++ + 1; which can be changed to a = ++b;).

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

How to get access to HTTP header information in Spring MVC REST controller?

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.

Naming returned columns in Pandas aggregate function?

I agree with the OP that it seems more natural and consistent to name and define the output columns in the same place (e.g. as is done with tidyverse's summarize in R), but a work-around in pandas for now is to create the new columns with desired names via assign before doing the aggregation:

data.assign(
    f=data['column1'],
    mean=data['column2'],
    std=data['column2']
).groupby('Country').agg(dict(f=sum, mean=np.mean, std=np.std)).reset_index()

(Using reset_index turns 'Country', 'f', 'mean', and 'std' all into regular columns with a separate integer index.)

Drawing an SVG file on a HTML5 canvas

As Simon says above, using drawImage shouldn't work. But, using the canvg library and:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);

This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6. Refer https://people.csail.mit.edu/hubert/pyaudio/

Please suggest if there is any alternate way to install PyAudio on Python 3.8.2

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Can .NET load and parse a properties file equivalent to Java Properties class?

Final class. Thanks @eXXL.

public class Properties
{
    private Dictionary<String, String> list;
    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore dublicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }


}

Sample use:

//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()

Is there a limit on an Excel worksheet's name length?

The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)

MySQL 'create schema' and 'create database' - Is there any difference

Strictly speaking, the difference between Database and Schema is inexisting in MySql.

However, this is not the case in other database engines such as SQL Server. In SQL server:,

Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)

By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:

SELECT *
FROM your_table

which is equivalent to:

SELECT *
FROM dbo.your_table

Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.

For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).

The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).

There are special schemas in SQL Server. To quote the same book:

There are several built-in database schemas, and they can't be dropped or altered:

1) dbo, the default schema.

2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.

3) INFORMATION_SCHEMA, used by the Information Schema Views

4) sys, reserved for SQL Server internal use exclusively

Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.

Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts (just an example, you get the idea).

Finally, and quoting the same book again:

It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition

How can I convert an HTML table to CSV?

Here's a short Python program I wrote to complete this task. It was written in a couple of minutes, so it can probably be made better. Not sure how it'll handle nested tables (probably it'll do bad stuff) or multiple tables (probably they'll just appear one after another). It doesn't handle colspan or rowspan. Enjoy.

from HTMLParser import HTMLParser
import sys
import re


class HTMLTableParser(HTMLParser):
    def __init__(self, row_delim="\n", cell_delim="\t"):
        HTMLParser.__init__(self)
        self.despace_re = re.compile(r'\s+')
        self.data_interrupt = False
        self.first_row = True
        self.first_cell = True
        self.in_cell = False
        self.row_delim = row_delim
        self.cell_delim = cell_delim

    def handle_starttag(self, tag, attrs):
        self.data_interrupt = True
        if tag == "table":
            self.first_row = True
            self.first_cell = True
        elif tag == "tr":
            if not self.first_row:
                sys.stdout.write(self.row_delim)
            self.first_row = False
            self.first_cell = True
            self.data_interrupt = False
        elif tag == "td" or tag == "th":
            if not self.first_cell:
                sys.stdout.write(self.cell_delim)
            self.first_cell = False
            self.data_interrupt = False
            self.in_cell = True

    def handle_endtag(self, tag):
        self.data_interrupt = True
        if tag == "td" or tag == "th":
            self.in_cell = False

    def handle_data(self, data):
        if self.in_cell:
            #if self.data_interrupt:
            #   sys.stdout.write(" ")
            sys.stdout.write(self.despace_re.sub(' ', data).strip())
            self.data_interrupt = False


parser = HTMLTableParser() 
parser.feed(sys.stdin.read()) 

Deserializing a JSON into a JavaScript object

And if you also want the deserialised object to have functions, you could use my small tool: https://github.com/khayll/jsmix

//first you'll need to define your model
var GraphNode = function() {};
GraphNode.prototype.getType = function() {
   return this.$type;
}

var Adjacency = function() {};
Adjacency.prototype.getData =n function() {
    return this.data;
}

//then you could say:
var result = JSMix(jsonData)
    .withObject(GraphNode.prototype, "*")
    .withObject(Adjacency.prototype, "*.adjacencies")
    .build();

//and use them
console.log(result[1][0].getData());

Get file from project folder java

Given a file application.yaml in test/resources

ll src/test/resources/
total 6
drwxrwx--- 1 root vboxsf 4096 Oct  6 12:23 ./
drwxrwx--- 1 root vboxsf    0 Sep 29 17:05 ../
-rwxrwx--- 1 root vboxsf  142 Sep 22 23:59 application.properties*
-rwxrwx--- 1 root vboxsf   78 Oct  6 12:23 application.yaml*
-rwxrwx--- 1 root vboxsf    0 Sep 22 17:31 db.properties*
-rwxrwx--- 1 root vboxsf  618 Sep 22 23:54 log4j2.json*

From the test context, I can get the file with

String file = getClass().getClassLoader().getResource("application.yaml").getPath(); 

which will actually point to the file in test-classes

ll target/test-classes/
total 10
drwxrwx--- 1 root vboxsf 4096 Oct  6 18:49 ./
drwxrwx--- 1 root vboxsf 4096 Oct  6 18:32 ../
-rwxrwx--- 1 root vboxsf  142 Oct  6 17:35 application.properties*
-rwxrwx--- 1 root vboxsf   78 Oct  6 17:35 application.yaml*
drwxrwx--- 1 root vboxsf    0 Oct  6 18:50 com/
-rwxrwx--- 1 root vboxsf    0 Oct  6 17:35 db.properties*
-rwxrwx--- 1 root vboxsf  618 Oct  6 17:35 log4j2.json*

"R cannot be resolved to a variable"?

for me, the best solution to suggest to people that have problems with the "R" file would be to try the next steps (order doesn't matter) :

  1. update ADT & SDK , Eclipse and Java (both 1.6 and the latest one).

    EDIT: now the ADT supports Java 1.7 . link here.

  2. remove gen folder , and create it again .

  3. do a clean-project.

  4. right click the project and choose android-tools -> fix-project-properties .

  5. right click the project and choose properties -> java-build-path -> order-and-export. make sure the order is :

    • Android 4.4 (always the latest version)

    • Android private libraries

    • android dependencies

    • your library project/s if needed

    • yourAppProject/gen

    • yourAppProject/src

  6. make sure all files in the res folder's subfolders have names that are ok : only lowercase letters, digits and underscore ("_") .

  7. always make sure the targetSdk is pointed to the latest API (currently 19) , and set it in the project.properties file

  8. try to run Lint and read its warnings. they might help you out.

  9. make sure your project compiles on 1.6 java and not a different version.

  10. restart eclipse.

Can one class extend two classes?

Familiar with multilevel hierarchy?

You can use subclass as superclass to your another class.

You can try this.

public class PreferenceActivity extends AbstractBillingActivity {}

then

public class Preferences extends PreferenceActivity {}

In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

Environment Specific application.properties file in Spring Boot application

Spring Boot already has support for profile based properties.

Simply add an application-[profile].properties file and specify the profiles to use using the spring.profiles.active property.

-Dspring.profiles.active=local

This will load the application.properties and the application-local.properties with the latter overriding properties from the first.

support FragmentPagerAdapter holds reference to old fragments

Do not try to interact between fragments in ViewPager. You cannot guarantee that other fragment attached or even exists. Istead of changing actionbar title from fragment, you can do it from your activity. Use standart interface pattern for this:

public interface UpdateCallback
{
    void update(String name);
}

public class MyActivity extends FragmentActivity implements UpdateCallback
{
    @Override
    public void update(String name)
    {
        getSupportActionBar().setTitle(name);
    }

}

public class MyFragment extends Fragment
{
    private UpdateCallback callback;

    @Override
    public void onAttach(SupportActivity activity)
    {
        super.onAttach(activity);
        callback = (UpdateCallback) activity;
    }

    @Override
    public void onDetach()
    {
        super.onDetach();
        callback = null;
    }

    public void updateActionbar(String name)
    {
        if(callback != null)
            callback.update(name);
    }
}

Java JTextField with input hint

Take a look at this one: http://code.google.com/p/xswingx/

It is not very difficult to implement it by yourself, btw. A couple of listeners and custom renderer and voila.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Javascript Image Resize

Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.

Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?

This should work:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

JavaScript click event listener on class

* This was edited to allow for children of the target class to trigger the events. See bottom of the answer for details. *

An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on function where you can pass in a selector for a child element that the event is listening on.

var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children

base.addEventListener('click', function(event) {
  // find the closest parent of the event target that
  // matches the selector
  var closest = event.target.closest(selector);
  if (closest && base.contains(closest)) {
    // handle class event
  }
});

Fiddle: https://jsfiddle.net/u6oje7af/94/

This will listen for clicks on children of the base element and if the target of a click has a parent matching the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).

This depends on the events propagating, so if you stopPropagation on the event somewhere else, this may not work. Also, the closest function has some compatibility issues with IE apparently (what doesn't?).

This could be made into a function if you need to do this type of action listening repeatedly, like

function addChildEventListener(base, eventName, selector, handler) {
  base.addEventListener(eventName, function(event) {
    var closest = event.target.closest(selector);
    if (closest && base.contains(closest)) {
      // passes the event to the handler and sets `this`
      // in the handler as the closest parent matching the
      // selector from the target element of the event
      handler.call(closest, event);
    }
  });
}

=========================================
EDIT: This post originally used the matches function for DOM elements on the event target, but this restricted the targets of events to the direct class only. It has been updated to use the closest function instead, allowing for events on children of the desired class to trigger the events as well. The original matches code can be found at the original fiddle: https://jsfiddle.net/u6oje7af/23/

CSS : center form in page horizontally and vertically

The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:

HTML

<body>
    <div class="login_div">
        <form class="login_form" action="#">
        </form>
    </div>
</body>

CSS

.login_div {
    position: absolute;

    width: 300px;
    height: 300px;

    /* Center form on page horizontally & vertically */
    top: 50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -150px;
}

.login_form {
    width: 300px;
    height: 300px;

    background: gray;
    border-radius: 10px;

    margin: 0;
    padding: 0;
}

JSFiddle

Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!

Can't get value of input type="file"?

You can get it by using document.getElementById();

var fileVal=document.getElementById("some Id");
alert(fileVal.value);

will give the value of file,but it gives with fakepath as follows

c:\fakepath\filename

How to check if a process is in hang state (Linux)

you could check the files

/proc/[pid]/task/[thread ids]/status

HTML5 Canvas and Anti-aliasing

Anti-aliasing cannot be turned on or off, and is controlled by the browser.

Can I turn off antialiasing on an HTML <canvas> element?

How can I make an EXE file from a Python program?

Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.


py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Best way to test for a variable's existence in PHP; isset() is clearly broken

I have to say in all my years of PHP programming, I have never encountered a problem with isset() returning false on a null variable. OTOH, I have encountered problems with isset() failing on a null array entry - but array_key_exists() works correctly in that case.

For some comparison, Icon explicitly defines an unused variable as returning &null so you use the is-null test in Icon to also check for an unset variable. This does make things easier. On the other hand, Visual BASIC has multiple states for a variable that doesn't have a value (Null, Empty, Nothing, ...), and you often have to check for more than one of them. This is known to be a source of bugs.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

I have the same problem, i read the url with an properties file:

String configFile = System.getenv("system.Environment");
        if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
            configFile = "dev.properties";
        }
        // Load properties 
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream("/" + configFile));
       //read url from file
        apiUrl = properties.getProperty("url").trim();
            URL url = new URL(apiUrl);
            //throw exception here
    URLConnection conn = url.openConnection();

dev.properties

url = "https://myDevServer.com/dev/api/gate"

it should be

dev.properties

url = https://myDevServer.com/dev/api/gate

without "" and my problem is solved.

According to oracle documentation

  • Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

So it means it is not parsed inside the string.

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Java Thread Example?

Here is a simple example:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

And some output:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

And the output:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

Now you can see each thread executing, giving up control early, and the next executing.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Have a look at wxArt2d it is a complete framework for 2d editing and plotting. See the screenshots for more examples.

Some interesting features:

  • Reading and writing SVG and CVG
  • Several views of the same document
  • Changes are updated when idle
  • Optimized drawing of 2d objects

Link to download apache http server for 64bit windows.

you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down

ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP

Export and Import all MySQL databases at one time

Export all databases in Ubuntu

1 - mysqldump -u root -p --databases database1 database2 > ~/Desktop/databases_1_2.sql

OR

2 - mysqldump -u root -p --all_databases > ~/Desktop/all_databases.sql

enter image description here

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.

Extract hostname name from string

// use this if you know you have a subdomain
// www.domain.com -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,"");
}

How to convert hex strings to byte values in Java

Since there was no answer for hex string to single byte conversion, here is mine:

private static byte hexStringToByte(String data) {
    return (byte) ((Character.digit(data.charAt(0), 16) << 4)
                  | Character.digit(data.charAt(1), 16));
}

Sample usage:

hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16

Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.

// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201

How can I append a query parameter to an existing URL?

Kotlin & clean, so you don't have to refactor before code review:

private fun addQueryParameters(url: String?): String? {
        val uri = URI(url)

        val queryParams = StringBuilder(uri.query.orEmpty())
        if (queryParams.isNotEmpty())
            queryParams.append('&')

        queryParams.append(URLEncoder.encode("$QUERY_PARAM=$param", Xml.Encoding.UTF_8.name))
        return URI(uri.scheme, uri.authority, uri.path, queryParams.toString(), uri.fragment).toString()
    }

Disable asp.net button after click to prevent double clicking

This solution works if you are using asp.net validators:

<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
    Page_ClientValidate(group);
    if (Page_IsValid)
    {
        sender.disabled = "disabled";
        __doPostBack(sender.name, '');
    }
}</script>

and change the button:

<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />

How to check if a String contains another String in a case insensitive manner in Java?

String container = " Case SeNsitive ";
String sub = "sen";
if (rcontains(container, sub)) {
    System.out.println("no case");
}

public static Boolean rcontains(String container, String sub) {

    Boolean b = false;
    for (int a = 0; a < container.length() - sub.length() + 1; a++) {
        //System.out.println(sub + " to " + container.substring(a, a+sub.length()));
        if (sub.equalsIgnoreCase(container.substring(a, a + sub.length()))) {
            b = true;
        }
    }
    return b;
}

Basically, it is a method that takes two strings. It is supposed to be a not-case sensitive version of contains(). When using the contains method, you want to see if one string is contained in the other.

This method takes the string that is "sub" and checks if it is equal to the substrings of the container string that are equal in length to the "sub". If you look at the for loop, you will see that it iterates in substrings (that are the length of the "sub") over the container string.

Each iteration checks to see if the substring of the container string is equalsIgnoreCase to the sub.

How to get the caller's method name in the called method?

I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

Could not find a part of the path ... bin\roslyn\csc.exe

I experienced this error on a Jenkins build server running MSBuild, which outputs the build files to a separate folder location (_PublishedWebsites). Exactly the same - the roslyn folder was not in the bin directory, and all the roslyn files were lumped in with the bin files.

@igor-semin 's answer was the only thing that worked for me (as I am using the C# 6 language features, I cannot simply uninstall the nuget packages as per other answers), but as I am also running CodeAnalysis, I was getting another error on my deployment target server:

An attempt to override an existing mapping was detected for type Microsoft.CodeAnalysis.ICompilationUnitSyntax with name "", currently mapped to type Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax, to type Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax.

The reason for this is that as the roslyn files are getting dumped into the main bin directory, when you run the xcopy to recreate them in the nested roslyn folder, you now have 2 copies of these files being compiled and there is a clash between them. After much frustration I decided on a 'hack' fix - an additional post-build task to delete these files from the bin directory, removing the conflict.

The .csproj of my offending projects now looks like:

................... more here ......................

 <PropertyGroup>
   <PostBuildEvent>
   if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
   start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
 </PostBuildEvent>
</PropertyGroup>
<Target Name="DeleteDuplicateAnalysisFiles" AfterTargets="AfterBuild">
   <!-- Jenkins now has copies of the following files in both the bin directory and the 'bin\rosyln' directory. Delete from bin. -->
   <ItemGroup>
     <FilesToDelete Include="$(WebProjectOutputDir)\bin\Microsoft.CodeAnalysis*.dll" />
   </ItemGroup>
   <Delete Files="@(FilesToDelete)" />
</Target>

................... more here ......................

How can I start PostgreSQL on Windows?

Go inside bin folder in C drive where Postgres is installed. run following command in git bash or Command prompt:

pg_ctl.exe restart -D "<path upto data>"

Ex:

pg_ctl.exe restart -D  "C:\Program Files\PostgreSQL\9.6\data"

Another way: type "services.msc" in run popup(windows + R). This will show all services running Select Postgres service from list and click on start/stop/restart.

Thanks

submitting a form when a checkbox is checked

Submit form when your checkbox is checked

$(document).ready(function () {   
$("#yoursubmitbuttonid").click(function(){           
                if( $(".yourcheckboxclass").is(":checked") )
                {
                    $("#yourformId").submit();

                }else{
                    alert("Please select !!!");
                    return false;
                }
                return false;
            }); 
});

How to create a list of objects?

if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:

my_list.append(my_object)

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

"unexpected token import" in Nodejs5 and babel?

Involve following steps to resolve the issue:

1) Install the CLI and env preset

$ npm install --save-dev babel-cli babel-preset-env

2) Create a .babelrc file

{
  "presets": ["env"]
}

3) configure npm start in package.json

"scripts": {
    "start": "babel-node ./server/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

4) then start app

$ npm start

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME Versus HTTP_HOST.

It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME.

So you either go with that or you check the host name against a white list:

$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

How to reverse apply a stash?

git stash[save] takes your working directory state, and your index state, and stashes them away, setting index and working area to HEAD version.

git stash apply brings back those changes, so git reset --hard would remove them again.

git stash pop brings back those changes and removes top stashed change, so git stash [save] would return to previous (pre-pop) state in this case.

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • jQuery UI: Datepicker set year range dropdown to 100 years

    I did this:

    var dateToday = new Date();
    var yrRange = dateToday.getFullYear() + ":" + (dateToday.getFullYear() + 50);
    and then
    yearRange : yrRange
    

    where 50 is the range from current year.

    Change x axes scale in matplotlib

    Try using matplotlib.pyplot.ticklabel_format:

    import matplotlib.pyplot as plt
    ...
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
    

    This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

    How to count lines of Java code using IntelliJ IDEA?

    Just like Neil said:

    Ctrl-Shift-F -> Text to find = '\n' -> Find.

    With only one improvement, if you enter "\n+", you can search for non-empty lines

    If lines with only whitespace can be considered empty too, then you can use the regex "(\s*\n\s*)+" to not count them.

    Correct use of flush() in JPA/Hibernate

    Probably the exact details of em.flush() are implementation-dependent. In general anyway, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction. For example, you call em.persist(), Hibernate remembers it has to make a database INSERT, but does not actually execute the instruction until you commit the transaction. Afaik, this is mainly done for performance reasons.

    In some cases anyway you want the SQL instructions to be executed immediately; generally when you need the result of some side effects, like an autogenerated key, or a database trigger.

    What em.flush() does is to empty the internal SQL instructions cache, and execute it immediately to the database.

    Bottom line: no harm is done, only you could have a (minor) performance hit since you are overriding the JPA provider decisions as regards the best timing to send SQL instructions to the database.

    How to upgrade rubygems

    Install rubygems-update

    gem install rubygems-update
    update_rubygems
    gem update --system
    

    run this commands as root or use sudo.

    How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

    Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:

    Application.ScreenUpdating = True
    Cells(2, 1).Select
    ActiveWindow.FreezePanes = True
    

    Now it works fine.

    Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

    Simple Steps

    1. 1 Open SQL Server Configuration Manager
    2. Under SQL Server Services Select Your Server
    3. Right Click and Select Properties
    4. Log on Tab Change Built-in-account tick
    5. in the drop down list select Network Service
    6. Apply and start The service

    Alternate output format for psql

    I just needed to spend more time staring at the documentation. This command:

    \x on
    

    will do exactly what I wanted. Here is some sample output:

    select * from dda where u_id=24 and dda_is_deleted='f';
    -[ RECORD 1 ]------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    dda_id             | 1121
    u_id               | 24
    ab_id              | 10304
    dda_type           | CHECKING
    dda_status         | PENDING_VERIFICATION
    dda_is_deleted     | f
    dda_verify_op_id   | 44938
    version            | 2
    created            | 2012-03-06 21:37:50.585845
    modified           | 2012-03-06 21:37:50.593425
    c_id               | 
    dda_nickname       | 
    dda_account_name   | 
    cu_id              | 1
    abd_id             | 
    

    Getting a better understanding of callback functions in JavaScript

    Callbacks are about signals and "new" is about creating object instances.

    In this case it would be even more appropriate to execute just "callback();" than "return new callback()" because you aren't doing anything with a return value anyway.

    (And the arguments.length==3 test is really clunky, fwiw, better to check that callback param exists and is a function.)

    firefox proxy settings via command line

    You can easily launch Firefox from the command line with a proxy server using the -proxy-server option.

    This works on Mac, Windows and Linux.

    path_to_firefox/firefox.exe -proxy-server %proxy_URL%

    Mac Example:

    /Applications/Firefox.app/Contents/MacOS/firefox -proxy-server proxy.example.com

    How do I search for an object by its ObjectId in the mongo console?

    I just had this issue and was doing exactly as was documented and it still was not working.

    Look at your error message and make sure you do not have any special characters copied in. I was getting the error

    SyntaxError: illegal character @(shell):1:43
    

    When I went to character 43 it was just the start of my object ID, after the open quotes, exactly as I pasted it in. I put my cursor there and hit backspace nothing appeared to happen when it should have removed the open quote. I hit backspace again and it removed the open quote, then I put the quote back in and executed the query and it worked, despite looking exactly the same.

    I was doing development in WebMatrix and copied the object id from the console. Whenever you copy from the console in WebMatrix you're likely to pick up some invisible characters that will cause errors.

    How to cast ArrayList<> from List<>

    The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>

    Wavy shape with css

    My pure CSS implementation based on above with 100% width. Hope it helps!

    _x000D_
    _x000D_
    #wave-container {_x000D_
      width: 100%;_x000D_
      height: 100px;_x000D_
      overflow: hidden;_x000D_
    }_x000D_
    _x000D_
    #wave {_x000D_
      display: block;_x000D_
      position: relative;_x000D_
      height: 40px;_x000D_
      background: black;_x000D_
    }_x000D_
    _x000D_
    #wave:before {_x000D_
      content: "";_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      border-radius: 100%;_x000D_
      width: 100%;_x000D_
      height: 300px;_x000D_
      background-color: white;_x000D_
      right: -25%;_x000D_
      top: 20px_x000D_
    }_x000D_
    _x000D_
    #wave:after {_x000D_
      content: "";_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      border-radius: 100%;_x000D_
      width: 100%;_x000D_
      height: 300px;_x000D_
      background-color: black;_x000D_
      left: -25%;_x000D_
      top: -240px;_x000D_
    }
    _x000D_
    <div id="wave-container">_x000D_
      <div id="wave">_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Find Locked Table in SQL Server

    You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

    select  
        object_name(p.object_id) as TableName, 
        resource_type, resource_description
    from
        sys.dm_tran_locks l
        join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
    

    Mail not sending with PHPMailer over SSL using SMTP

    Don't use SSL on port 465, it's been deprecated since 1998 and is only used by Microsoft products that didn't get the memo; use TLS on port 587 instead: So, the code below should work very well for you.

    mail->IsSMTP(); // telling the class to use SMTP
    $mail->Host       = "smtp.gmail.com"; // SMTP server
    
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
    $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
    $mail->Port       = 587;                   // set the SMTP port for the 
    

    Javascript - remove an array item by value

    You'll want to use .indexOf() and .splice(). Something like:

    tag_story.splice(tag_story.indexOf(90),1);
    

    How to Install Windows Phone 8 SDK on Windows 7

    You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

    Why compile Python code?

    There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.

    With any interpeted language when the file is used the process looks something like this:
    1. File is processed by the interpeter.
    2. File is compiled
    3. Compiled code is executed.

    obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.

    Heres an interesting blog post explaining the differences http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html
    And here's an entry that explains the Python compile process http://effbot.org/zone/python-compile.htm

    What are NR and FNR and what does "NR==FNR" imply?

    There are awk built-in variables.

    NR - It gives the total number of records processed.

    FNR - It gives the total number of records for each input file.

    How do I get IntelliJ to recognize common Python modules?

    Have you set up a python interpreter facet?

    Open Project Structure CTRL+ALT+SHIFT+S

    Project settings -> Facets -> expand Python click on child -> Python Interpreter

    Then:

    Project settings -> Modules -> Expand module -> Python -> Dependencies -> select Python module SDK

    Couldn't load memtrack module Logcat Error

    I had this issue too, also running on an emulator.. The same message was showing up on Logcat, but it wasn't affecting the functionality of the app. But it was annoying, and I don't like seeing errors on the log that I don't understand.

    Anyway, I got rid of the message by increasing the RAM on the emulator.

    Get current controller in view

    You can use any of the below code to get the controller name

    @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    

    If you are using MVC 3 you can use

    @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
    

    Getting the textarea value of a ckeditor textarea with javascript

    At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:

    CKEDITOR.on("instanceCreated", function(event) {
        event.editor.on("change", function () {
            $("#trackingDiv").html(event.editor.getData());
        });
    });
    

    I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.

    How can I get the name of an object in Python?

    This one-liner works, for all types of objects, as long as they are in globals() dict, which they should be:

    def name_of_global_obj(xx):
        return [objname for objname, oid in globals().items()
                if id(oid)==id(xx)][0]
    

    or, equivalently:

    def name_of_global_obj(xx):
        for objname, oid in globals().items():
            if oid is xx:
                return objname
    

    Run a shell script with an html button

    As stated by Luke you need to use a server side language, like php. This is a really simple php example:

    <?php
    if ($_GET['run']) {
      # This code will run if ?run=true is set.
      exec("/path/to/name.sh");
    }
    ?>
    
    <!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
    <a href="?run=true">Click Me!</a>
    

    Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

    How to reload page every 5 seconds?

    setTimeout(function () { location.reload(1); }, 5000);
    

    But as development tools go, you are probably better off with https://addons.mozilla.org/en-US/firefox/addon/115

    Scala how can I count the number of occurrences in a list

    If you want to use it like list.count(2) you have to implement it using an Implicit Class.

    implicit class Count[T](list: List[T]) {
      def count(n: T): Int = list.count(_ == n)
    }
    
    List(1,2,4,2,4,7,3,2,4).count(2)  // returns 3
    List(1,2,4,2,4,7,3,2,4).count(5)  // returns 0
    

    How to export html table to excel or pdf in php

    Either you can use CSV functions or PHPExcel

    or you can try like below

    <?php
    $file="demo.xls";
    $test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=$file");
    echo $test;
    ?>
    

    The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

    Cropping an UIImage

    Look at https://github.com/vvbogdan/BVCropPhoto

    - (UIImage *)croppedImage {
        CGFloat scale = self.sourceImage.size.width / self.scrollView.contentSize.width;
    
        UIImage *finalImage = nil;
        CGRect targetFrame = CGRectMake((self.scrollView.contentInset.left + self.scrollView.contentOffset.x) * scale,
                (self.scrollView.contentInset.top + self.scrollView.contentOffset.y) * scale,
                self.cropSize.width * scale,
                self.cropSize.height * scale);
    
        CGImageRef contextImage = CGImageCreateWithImageInRect([[self imageWithRotation:self.sourceImage] CGImage], targetFrame);
    
        if (contextImage != NULL) {
            finalImage = [UIImage imageWithCGImage:contextImage
                                             scale:self.sourceImage.scale
                                       orientation:UIImageOrientationUp];
    
            CGImageRelease(contextImage);
        }
    
        return finalImage;
    }
    
    
    - (UIImage *)imageWithRotation:(UIImage *)image {
    
    
        if (image.imageOrientation == UIImageOrientationUp) return image;
        CGAffineTransform transform = CGAffineTransformIdentity;
    
        switch (image.imageOrientation) {
            case UIImageOrientationDown:
            case UIImageOrientationDownMirrored:
                transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
                transform = CGAffineTransformRotate(transform, M_PI);
                break;
    
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
                transform = CGAffineTransformTranslate(transform, image.size.width, 0);
                transform = CGAffineTransformRotate(transform, M_PI_2);
                break;
    
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
                transform = CGAffineTransformTranslate(transform, 0, image.size.height);
                transform = CGAffineTransformRotate(transform, -M_PI_2);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationUpMirrored:
                break;
        }
    
        switch (image.imageOrientation) {
            case UIImageOrientationUpMirrored:
            case UIImageOrientationDownMirrored:
                transform = CGAffineTransformTranslate(transform, image.size.width, 0);
                transform = CGAffineTransformScale(transform, -1, 1);
                break;
    
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRightMirrored:
                transform = CGAffineTransformTranslate(transform, image.size.height, 0);
                transform = CGAffineTransformScale(transform, -1, 1);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationDown:
            case UIImageOrientationLeft:
            case UIImageOrientationRight:
                break;
        }
    
        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                CGImageGetBitsPerComponent(image.CGImage), 0,
                CGImageGetColorSpace(image.CGImage),
                CGImageGetBitmapInfo(image.CGImage));
        CGContextConcatCTM(ctx, transform);
        switch (image.imageOrientation) {
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
                // Grr...
                CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.height, image.size.width), image.CGImage);
                break;
    
            default:
                CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
                break;
        }
    
        // And now we just create a new UIImage from the drawing context
        CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
        UIImage *img = [UIImage imageWithCGImage:cgimg];
        CGContextRelease(ctx);
        CGImageRelease(cgimg);
        return img;
    
    }
    

    How can I implement rate limiting with Apache? (requests per second)

    Sadly, mod_evasive won't work as expected when used in non-prefork configurations (recent apache setups are mainly MPM)

    How to correctly set Http Request Header in Angular 2

    This should be easily resolved by importing headers from Angular:

    import { Http, Headers } from "@angular/http";
    

    Sending Multipart File as POST parameters with RestTemplate requests

    I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:

    pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-version}</version>
    </dependency>
    

    web.xml - Add multipart filter and mapping

    <filter>
      <filter-name>multipartFilter</filter-name>
      <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>multipartFilter</filter-name>
      <url-pattern>/springrest/*</url-pattern>
    </filter-mapping>
    

    app-context.xml - Add multipart resolver

    <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="maxUploadSize">
            <beans:value>10000000</beans:value>
        </beans:property>
    </beans:bean>
    

    Your Controller

    @RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
    public @ResponseBody boolean saveStationImage(
            @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
            @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri, 
            @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType, 
            @RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
        // Do something with file
        // Return results
    }
    

    Your client

    public static Boolean updateStationImage(StationImage stationImage) {
        if(stationImage == null) {
            Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
            return null;
        }
    
        Log.d(TAG, "Uploading: " + stationImage.getImageUri());
        try {
            RestTemplate restTemplate = new RestTemplate();
            FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
            formConverter.setCharset(Charset.forName("UTF8"));
            restTemplate.getMessageConverters().add(formConverter);
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    
            restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
    
            MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
    
            parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
            parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
            parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
            parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());
    
            return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
    
            Log.e(TAG + ":addStationImage", sw.toString());
        }
    
        return false;
    }
    

    That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.

    How can I customize the tab-to-space conversion factor?

    Well, if you like the developer way, Visual Studio Code allows you to specify the different file types for the tabSize. Here is the example of my settings.json with default four spaces and JavaScript/JSON two spaces:

    {
      // I want my default to be 4, but JavaScript/JSON to be 2
      "editor.tabSize": 4,
      "[javascript]": {
        "editor.tabSize": 2
      },
      "[json]": {
        "editor.tabSize": 2
      },
    
      // This one forces the tab to be **space**
      "editor.insertSpaces": true
    }
    

    PS: Well, if you do not know how to open this file (specially in a new version of Visual Studio Code), you can:

    1. Left-bottom gear →
    2. Settings → top right Open Settings

     

    Enter image description here

    is there a 'block until condition becomes true' function in java?

    You could use a semaphore.

    While the condition is not met, another thread acquires the semaphore.
    Your thread would try to acquire it with acquireUninterruptibly()
    or tryAcquire(int permits, long timeout, TimeUnit unit) and would be blocked.

    When the condition is met, the semaphore is also released and your thread would acquire it.

    You could also try using a SynchronousQueue or a CountDownLatch.

    How do I run a docker instance from a DockerFile?

    Download the file and from the same directory run docker build -t nodebb .

    This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

    How to add a border to a widget in Flutter?

    Using BoxDecoration() is the best way to show border.

    Container(
      decoration: BoxDecoration(
        border: Border.all(
        color: Color(0xff000000),
        width: 4,
      )),
      child: //Your child widget
    ),
    

    You can also view full format here

    VBA Excel 2-Dimensional Arrays

    You need ReDim:

    m = 5
    n = 8
    Dim my_array()
    ReDim my_array(1 To m, 1 To n)
    For i = 1 To m
      For j = 1 To n
        my_array(i, j) = i * j
      Next
    Next
    
    For i = 1 To m
      For j = 1 To n
        Cells(i, j) = my_array(i, j)
      Next
    Next
    

    As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:

    Dim r1 As Range
    Dim r2 As Range
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    
    Set ws1 = Worksheets("Sheet1")
    Set ws2 = Worksheets("Sheet2")
    totalRow = ws1.Range("A1").End(xlDown).Row
    totalCol = ws1.Range("A1").End(xlToRight).Column
    
    Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
    Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
    r2.Value = r1.Value
    

    Passing arguments to AsyncTask, and returning results

    I sort of agree with leander on this one.

    call:

    new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
    

    task:

    public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
            @Override
            protected ArrayList<String> doInBackground(String... args) {
               ...
            }
    
            @Override
            protected void onPostExecute(ArrayList<String> result) {
               ... //do something with the result list here
            }
    }
    

    Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);

    public class calc_stanica extends AsyncTask<String, Void, Boolean> {
            private List<String> resultList;
    
            @Override
            protected boolean doInBackground(String... args) {
               ...
            }
    
            @Override
            protected void onPostExecute(boolean success) {
               ... //if successfull, do something with the result list here
            }
    }
    

    u'\ufeff' in Python string

    The content you're scraping is encoded in unicode rather than ascii text, and you're getting a character that doesn't convert to ascii. The right 'translation' depends on what the original web page thought it was. Python's unicode page gives the background on how it works.

    Are you trying to print the result or stick it in a file? The error suggests it's writing the data that's causing the problem, not reading it. This question is a good place to look for the fixes.

    Function to calculate distance between two coordinates

    Adding this for Node.JS users. You can use the haversine-distance module to do this so you won't need to handle the calculations on your own. See the npm page for more information.

    To install:

    npm install --save haversine-distance

    You can use the module as follows:

    var haversine = require("haversine-distance");
    
    //First point in your haversine calculation
    var point1 = { lat: 6.1754, lng: 106.8272 }
    
    //Second point in your haversine calculation
    var point2 = { lat: 6.1352, lng: 106.8133 }
    
    var haversine_m = haversine(point1, point2); //Results in meters (default)
    var haversine_km = haversine_m /1000; //Results in kilometers
    
    console.log("distance (in meters): " + haversine_m + "m");
    console.log("distance (in kilometers): " + haversine_km + "km");
    

    Powershell script to check if service is started, if not then start it

    Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.

    I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".

    $Service = 'ServiceName'
    while ((Get-Service $Service).Status -eq 'Stopped') 
    {
        Start-Service $Service -ErrorAction SilentlyContinue
        Start-Sleep 10
    } 
    Return "$($Service) has STARTED"
    

    Generate unique random numbers between 1 and 100

    Using a Set is your fastest option. Here is a generic function for getting a unique random that uses a callback generator. Now it's fast and reusable.

    _x000D_
    _x000D_
    // Get a unique 'anything'_x000D_
    let unique = new Set()_x000D_
    _x000D_
    function getUnique(generator) {_x000D_
      let number = generator()_x000D_
      while (!unique.add(number)) {_x000D_
        number = generator()_x000D_
      }_x000D_
      return number;_x000D_
    }_x000D_
    _x000D_
    // The generator.  Return anything, not just numbers._x000D_
    const between_1_100 = () => 1 + Math.floor(Math.random() * 100)_x000D_
    _x000D_
    // Test it_x000D_
    for (var i = 0; i < 8; i++) {_x000D_
      const aNumber = getUnique(between_1_100)_x000D_
    }_x000D_
    // Dump the 'stored numbers'_x000D_
    console.log(Array.from(unique))
    _x000D_
    _x000D_
    _x000D_

    Cannot install Aptana Studio 3.6 on Windows

    I'm using Win 8.1, and have installed Aptana easily, and use for PHP programming without any issues. And just experimented with Ruble enhancement to the UI. All seems to work just fine.

    3.6.0.201407100658

    How can I set the max-width of a table cell using percentages?

    the percent should be relative to an absolute size, try this :

    _x000D_
    _x000D_
    table {
      width:200px;
    }
    
    td {
      width:65%;
      border:1px solid black;
    }
    _x000D_
    <table>
      <tr>
        <td>Testasdas 3123 1 dasd as da</td>
        <td>A long string blah blah blah</td>
      </tr>
    </table>
        
    _x000D_
    _x000D_
    _x000D_

    Twitter Bootstrap vs jQuery UI?

    We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.

    Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.

    So I see no point in using something that will eventually be outdated...

    Find an object in array?

    Another way to get access to array.index(of: Any) is by declaring your object

    import Foundation
    class Model: NSObject {  }
    

    Is there a way to run Bash scripts on Windows?

    Best option? Windows 10. Native Bash support!

    How to open, read, and write from serial port in C?

    For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
    This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
    It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

    This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
    The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
    The program then enters an infinite loop to receive and display data from the serial terminal.
    By default the received data is displayed as hexadecimal byte values.

    To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

     cc -DDISPLAY_STRING demo.c
    

    If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


    #define TERMINAL    "/dev/ttyUSB0"
    
    #include <errno.h>
    #include <fcntl.h> 
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <termios.h>
    #include <unistd.h>
    
    int set_interface_attribs(int fd, int speed)
    {
        struct termios tty;
    
        if (tcgetattr(fd, &tty) < 0) {
            printf("Error from tcgetattr: %s\n", strerror(errno));
            return -1;
        }
    
        cfsetospeed(&tty, (speed_t)speed);
        cfsetispeed(&tty, (speed_t)speed);
    
        tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
        tty.c_cflag &= ~CSIZE;
        tty.c_cflag |= CS8;         /* 8-bit characters */
        tty.c_cflag &= ~PARENB;     /* no parity bit */
        tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
        tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */
    
        /* setup for non-canonical mode */
        tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
        tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
        tty.c_oflag &= ~OPOST;
    
        /* fetch bytes as they become available */
        tty.c_cc[VMIN] = 1;
        tty.c_cc[VTIME] = 1;
    
        if (tcsetattr(fd, TCSANOW, &tty) != 0) {
            printf("Error from tcsetattr: %s\n", strerror(errno));
            return -1;
        }
        return 0;
    }
    
    void set_mincount(int fd, int mcount)
    {
        struct termios tty;
    
        if (tcgetattr(fd, &tty) < 0) {
            printf("Error tcgetattr: %s\n", strerror(errno));
            return;
        }
    
        tty.c_cc[VMIN] = mcount ? 1 : 0;
        tty.c_cc[VTIME] = 5;        /* half second timer */
    
        if (tcsetattr(fd, TCSANOW, &tty) < 0)
            printf("Error tcsetattr: %s\n", strerror(errno));
    }
    
    
    int main()
    {
        char *portname = TERMINAL;
        int fd;
        int wlen;
        char *xstr = "Hello!\n";
        int xlen = strlen(xstr);
    
        fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
        if (fd < 0) {
            printf("Error opening %s: %s\n", portname, strerror(errno));
            return -1;
        }
        /*baudrate 115200, 8 bits, no parity, 1 stop bit */
        set_interface_attribs(fd, B115200);
        //set_mincount(fd, 0);                /* set to pure timed read */
    
        /* simple output */
        wlen = write(fd, xstr, xlen);
        if (wlen != xlen) {
            printf("Error from write: %d, %d\n", wlen, errno);
        }
        tcdrain(fd);    /* delay for output */
    
    
        /* simple noncanonical input */
        do {
            unsigned char buf[80];
            int rdlen;
    
            rdlen = read(fd, buf, sizeof(buf) - 1);
            if (rdlen > 0) {
    #ifdef DISPLAY_STRING
                buf[rdlen] = 0;
                printf("Read %d: \"%s\"\n", rdlen, buf);
    #else /* display hex */
                unsigned char   *p;
                printf("Read %d:", rdlen);
                for (p = buf; rdlen-- > 0; p++)
                    printf(" 0x%x", *p);
                printf("\n");
    #endif
            } else if (rdlen < 0) {
                printf("Error from read: %d: %s\n", rdlen, strerror(errno));
            } else {  /* rdlen == 0 */
                printf("Timeout from read\n");
            }               
            /* repeat read to get full message */
        } while (1);
    }
    

    For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


    What is the advantage of using REST instead of non-REST HTTP?

    It's written down in the Fielding dissertation. But if you don't want to read a lot:

    • increased scalability (due to stateless, cache and layered system constraints)
    • decoupled client and server (due to stateless and uniform interface constraints)
      • reusable clients (client can use general REST browsers and RDF semantics to decide which link to follow and how to display the results)
      • non breaking clients (clients break only by application specific semantics changes, because they use the semantics instead of some API specific knowledge)

    Pass request headers in a jQuery AJAX GET call

    Use beforeSend:

    $.ajax({
             url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
             data: { signature: authHeader },
             type: "GET",
             beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
             success: function() { alert('Success!' + authHeader); }
          });
    

    http://api.jquery.com/jQuery.ajax/

    http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

    What's the canonical way to check for type in Python?

    After the question was asked and answered, type hints were added to Python. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this allows for types to be checked. Example of type hint syntax:

    def foo(i: int):
        return i
    
    foo(5)
    foo('oops')
    

    In this case we want an error to be triggered for foo('oops') since the annotated type of the argument is int. The added type hint does not cause an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors.

    One of these other programs that can be used to find the type error is mypy:

    mypy script.py
    script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
    

    (You might need to install mypy from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".)

    Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly list type or is anything iterable sufficient?).

    The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.

    Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.

    The typing package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as Iterable and Callable for hints to specify the need for any type with those behaviors.

    While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some.

    Is there a way to reset IIS 7.5 to factory settings?

    This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx

    It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).

    Tomcat Server not starting with in 45 seconds

    Try remove all breakpoints.Also you can increase start up time.

    Open the Servers view -> double click tomcat -> drop down the Timeouts section

    enter image description here

    How do I use a custom Serializer with Jackson?

    I tried doing this too, and there is a mistake in the example code on the Jackson web page that fails to include the type (.class) in the call to addSerializer() method, which should read like this:

    simpleModule.addSerializer(Item.class, new ItemSerializer());
    

    In other words, these are the lines that instantiate the simpleModule and add the serializer (with the prior incorrect line commented out):

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                              new Version(1,0,0,null));
    // simpleModule.addSerializer(new ItemSerializer());
    simpleModule.addSerializer(Item.class, new ItemSerializer());
    mapper.registerModule(simpleModule);
    

    FYI: Here is the reference for the correct example code: http://wiki.fasterxml.com/JacksonFeatureModules

    How to decrypt a password from SQL server?

    I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.

    If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.

    This is how you could verify a usered entered table

    SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
    

    Replace userEnteredValue with (big surprise) the value that the user entered :)

    How to unpack an .asar file?

    From the asar documentation

    (the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

    Extract the whole archive:

    npx asar extract app.asar destfolder 
    

    Extract a particular file:

    npx asar extract-file app.asar main.js
    

    how to get all markers on google-maps-v3

    If you mean "how can I get a reference to all markers on a given map" - then I think the answer is "Sorry, you have to do it yourself". I don't think there is any handy "maps.getMarkers()" type function: you have to keep your own references as the points are created:

    var allMarkers = [];
    ....
    // Create some markers
    for(var i = 0; i < 10; i++) {
        var marker = new google.maps.Marker({...});
        allMarkers.push(marker);
    }
    ...
    

    Then you can loop over the allMarkers array to and do whatever you need to do.

    Remove a character at a certain position in a string - javascript

    Turn the string into array, cut a character at specified index and turn back to string

    let str = 'Hello World'.split('')
    
    str.splice(3, 1)
    str = str.join('')
    
    // str = 'Helo World'.
    

    Radio buttons not checked in jQuery

    If my firebug profiler work fine (and i know how to use it well), this:

    $('#communitymode').attr('checked')
    

    is faster than

    $('#communitymode').is('checked')
    

    You can try on this page :)

    And then you can use it like

    if($('#communitymode').attr('checked')===true) { 
    // do something
    }
    

    How to create an empty array in PHP with predefined size?

    There is no way to create an array of a predefined size without also supplying values for the elements of that array.


    The best way to initialize an array like that is array_fill. By far preferable over the various loop-and-insert solutions.

    $my_array = array_fill(0, $size_of_the_array, $some_data);
    

    Every position in the $my_array will contain $some_data.

    The first zero in array_fill just indicates the index from where the array needs to be filled with the value.

    How can I combine two HashMap objects containing the same types?

    map3 = new HashMap<>();
    
    map3.putAll(map1);
    map3.putAll(map2);
    

    Working with Enums in android

    Android's preferred approach is int constants enforced with @IntDef:

    public static final int GENDER_MALE = 1;
    public static final int GENDER_FEMALE = 2;
    
    @Retention(RetentionPolicy.SOURCE)
    @IntDef ({GENDER_MALE, GENDER_FEMALE})
    public @interface Gender{}
    
    // Example usage...
    void exampleFunc(@Gender int gender) {
      switch(gender) {
      case GENDER_MALE:
    
         break;
      case GENDER_FEMALE:
         // TODO
         break;
      }
    }
    

    Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

    PHP UML Generator

    There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.

    Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.

    How to slice a Pandas Data Frame by position?

    You can also do as a convenience:

    df[:10]

    TypeError: unsupported operand type(s) for -: 'str' and 'int'

    1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

    2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

      def cat_n_times(s, n):
          for i in range(n):
              print(s) 
      
      text = input("What would you like the computer to repeat back to you: ")
      num = int(input("How many times: ")) # Convert to an int immediately.
      
      cat_n_times(text, num)
      
    3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

    Declare an array in TypeScript

    Here are the different ways in which you can create an array of booleans in typescript:

    let arr1: boolean[] = [];
    let arr2: boolean[] = new Array();
    let arr3: boolean[] = Array();
    
    let arr4: Array<boolean> = [];
    let arr5: Array<boolean> = new Array();
    let arr6: Array<boolean> = Array();
    
    let arr7 = [] as boolean[];
    let arr8 = new Array() as Array<boolean>;
    let arr9 = Array() as boolean[];
    
    let arr10 = <boolean[]> [];
    let arr11 = <Array<boolean>> new Array();
    let arr12 = <boolean[]> Array();
    
    let arr13 = new Array<boolean>();
    let arr14 = Array<boolean>();
    

    You can access them using the index:

    console.log(arr[5]);
    

    and you add elements using push:

    arr.push(true);
    

    When creating the array you can supply the initial values:

    let arr1: boolean[] = [true, false];
    let arr2: boolean[] = new Array(true, false);
    

    How to replace a set of tokens in a Java String?

    It depends of where the actual data that you want to replace is located. You might have a Map like this:

    Map<String, String> values = new HashMap<String, String>();
    

    containing all the data that can be replaced. Then you can iterate over the map and change everything in the String as follows:

    String s = "Your String with [Fields]";
    for (Map.Entry<String, String> e : values.entrySet()) {
      s = s.replaceAll("\\[" + e.getKey() + "\\]", e.getValue());
    }
    

    You could also iterate over the String and find the elements in the map. But that is a little bit more complicated because you need to parse the String searching for the []. You could do it with a regular expression using Pattern and Matcher.

    Convert seconds to Hour:Minute:Second

    If you need to do that in javascript, you can do it in just one line of code as answered here Convert seconds to HH-MM-SS with JavaScript. Replace SECONDS with what you want to convert.

    var time = new Date(SECONDS * 1000).toISOString().substr(11, 8);
    

    Why is there no String.Empty in Java?

    Use org.apache.commons.lang.StringUtils.EMPTY

    Convert DataTable to CSV stream

    BFree's answer worked for me. I needed to post the stream right to the browser. Which I'd imagine is a common alternative. I added the following to BFree's Main() code to do this:

    //StreamReader reader = new StreamReader(stream);
    //Console.WriteLine(reader.ReadToEnd());
    
    string fileName = "fileName.csv";
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
    stream.Position = 0;
    stream.WriteTo(HttpContext.Current.Response.OutputStream);
    

    How to get the GL library/headers?

    In Visual Studio :

    //OpenGL
    #pragma comment(lib, "opengl32")
    #pragma comment(lib, "glu32")
    #include <gl/gl.h>
    #include <gl/glu.h>
    

    Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

    Copying a local file from Windows to a remote server using scp

    Drive letters can be used in the target like

    scp some_file user@host:/c/temp
    

    where c is the drive letter. It's treated like a directory.

    Maybe this works on the source, too.

    Left/Right float button inside div

    You can use justify-content: space-between in .test like so:

    _x000D_
    _x000D_
    .test {_x000D_
      display: flex;_x000D_
      justify-content: space-between;_x000D_
      width: 20rem;_x000D_
      border: .1rem red solid;_x000D_
    }
    _x000D_
    <div class="test">_x000D_
      <button>test</button>_x000D_
      <button>test</button>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_


    For those who want to use Bootstrap 4 can use justify-content-between:

    _x000D_
    _x000D_
    div {_x000D_
      width: 20rem;_x000D_
      border: .1rem red solid;_x000D_
    }
    _x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
    <div class="d-flex justify-content-between">_x000D_
      <button>test</button>_x000D_
      <button>test</button>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Proper usage of Java -D command-line parameters

    You're giving parameters to your program instead to Java. Use

    java -Dtest="true" -jar myApplication.jar 
    

    instead.

    Consider using

    "true".equalsIgnoreCase(System.getProperty("test"))
    

    to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

    System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
    

    is right (providing default true). A shorter possibility is

    !"false".equalsIgnoreCase(System.getProperty("test"))
    

    but not using double negation doesn't make it less hard to misunderstand.

    How to use multiple LEFT JOINs in SQL?

    The required SQL will be some like:-

    SELECT * FROM cd
    LEFT JOIN ab ON ab.sht = cd.sht
    LEFT JOIN aa ON aa.sht = cd.sht
    ....
    

    Hope it helps.

    Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

    Try

    Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))
    

    How to kill all processes matching a name?

    try kill -s 9 `ps -ef |grep "Nov 11" |grep -v grep | awk '{print $2}'` To kill processes of November 11 or kill -s 9 `ps -ef |grep amarok|grep -v grep | awk '{print $2}'` To kill processes that contain the word amarok

    How can I change an element's class with JavaScript?

    classList DOM API:

    A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

    _x000D_
    _x000D_
    const el = document.getElementById("main");_x000D_
    console.log(el.classList);
    _x000D_
    <div class="content wrapper animated" id="main"></div>
    _x000D_
    _x000D_
    _x000D_

    We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

    Example:

    _x000D_
    _x000D_
    const el = document.getElementById('container');_x000D_
    _x000D_
    _x000D_
    function addClass () {_x000D_
       el.classList.add('newclass');_x000D_
    }_x000D_
    _x000D_
    _x000D_
    function replaceClass () {_x000D_
         el.classList.replace('foo', 'newFoo');_x000D_
    }_x000D_
    _x000D_
    _x000D_
    function removeClass () {_x000D_
           el.classList.remove('bar');_x000D_
    }
    _x000D_
    button{_x000D_
      margin: 20px;_x000D_
    }_x000D_
    _x000D_
    .foo{_x000D_
      color: red;_x000D_
    }_x000D_
    _x000D_
    .newFoo {_x000D_
      color: blue;_x000D_
    }_x000D_
    _x000D_
    .bar{_x000D_
      background-color:powderblue;_x000D_
    }_x000D_
    _x000D_
    .newclass{_x000D_
      border: 2px solid green;_x000D_
    }
    _x000D_
    <div class="foo bar" id="container">_x000D_
      "Sed ut perspiciatis unde omnis _x000D_
      iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
      totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
      quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
      voluptatem quia voluptas _x000D_
     </div>_x000D_
      _x000D_
    <button onclick="addClass()">AddClass</button>_x000D_
      _x000D_
    <button onclick="replaceClass()">ReplaceClass</button>_x000D_
      _x000D_
    <button onclick="removeClass()">removeClass</button>_x000D_
      
    _x000D_
    _x000D_
    _x000D_

    Get the date (a day before current time) in Bash

    if you have GNU date and i understood you correctly

    $ date +%Y:%m:%d -d "yesterday"
    2009:11:09
    

    or

    $ date +%Y:%m:%d -d "1 day ago"
    2009:11:09
    

    JQuery wait for page to finish loading before starting the slideshow?

    If you pass jQuery a function, it will not run until the page has loaded:

    <script type="text/javascript">
    $(function() {
        //your header rotation code goes here
    });
    </script>
    

    Why do I always get the same sequence of random numbers with rand()?

    This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:

    Declaration:

    void srand(unsigned int seed); 
    

    This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.

    How to stop C# console applications from closing automatically?

    Use:

    Console.ReadKey();
    

    For it to close when someone presses any key, or:

    Console.ReadLine();
    

    For when the user types something and presses enter.

    Getting only 1 decimal place

    >>> "{:.1f}".format(45.34531)
    '45.3'
    

    Or use the builtin round:

    >>> round(45.34531, 1)
    45.299999999999997
    

    How to query nested objects?

    db.messages.find( { headers : { From: "[email protected]" } } )

    This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


    db.messages.find( { 'headers.From': "[email protected]" } )

    This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


    Dot-notation docs

    java.io.IOException: Invalid Keystore format

    (Re)installing the latest JDK (e.g. Oracle's) fixed it for me.

    Prior to installing the latest JDK, when I executed the following command in Terminal.app:

    keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
    

    It resulted in:

    keytool error: java.io.IOException: Invalid keystore format
    java.io.IOException: Invalid keystore format
        at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
        at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
        at java.security.KeyStore.load(KeyStore.java:1445)
        at sun.security.tools.keytool.Main.doCommands(Main.java:792)
        at sun.security.tools.keytool.Main.run(Main.java:340)
        at sun.security.tools.keytool.Main.main(Main.java:333)
    

    But, after installing the latest Oracle JDK and restarting Terminal, executing the following command:

    keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
    

    Results in:

    Enter keystore password:  
    

    Which indicates that the keytool on path can access the keystore.

    What is the reason for the error message "System cannot find the path specified"?

    There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

    The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

    But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

    32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

    For more details see the Microsoft documentation about File System Redirector.

    So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

    The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

    @echo off
    set "SystemPath=%SystemRoot%\System32"
    if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
    

    Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

    How it works?

    There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

    But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

    Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

    Run a command shell in jenkins

    Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

    *Don't write bin at the end

    scrollable div inside container

    Is this what you are wanting?

    _x000D_
    _x000D_
    <body>_x000D_
      <div id="div1" style="height: 500px;">_x000D_
        <div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
          <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </body>
    _x000D_
    _x000D_
    _x000D_

    http://jsfiddle.net/fMs67/1/

    DateTime to javascript date

    With Moment.js simply use:

    var jsDate = moment(netDateTime).toDate();
    

    Where netDateTime is your DateTime variable serialized, something like "/Date(1456956000000+0200)/".

    Display string as html in asp.net mvc view

    You should be using IHtmlString instead:

    IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>");
    

    Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:

    @Html.Raw(str)
    

    Compared to:

    @str
    

    Also, I also think it's a bit safer vs. using @Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).

    I generally try to avoid using Html.Raw() whenever possible.

    One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.

    First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.

    Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like @Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.

    How to clone an InputStream?

    You can't clone it, and how you are going to solve your problem depends on what the source of the data is.

    One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.

    Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.

    Matching an optional substring in a regex

    This ought to work:

    ^\d+\s?(\([^\)]+\)\s?)?Z$
    

    Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:

    First the beginning:

    ^ = beginning of string
    \d+ = one or more decimal characters
    \s? = one optional whitespace
    

    Then this part:

    (\([^\)]+\)\s?)?
    

    Is actually:

    (.............)?
    

    Which makes the following contents optional, only if it exists fully

    \([^\)]+\)\s?
    
    \( = an opening bracket
    [^\)]+ = a series of at least one character that is not a closing bracket
    \) = followed by a closing bracket
    \s? = followed by one optional whitespace
    

    And the end is made up of

    Z$
    

    Where

    Z = your constant string
    $ = the end of the string
    

    SQL query to find third highest salary in company

    We can find the Top nth Salary with this Query.

    WITH EMPCTE AS ( SELECT E.*, DENSE_RANK() OVER(ORDER BY SALARY DESC) AS DENSERANK FROM EMPLOYEES E ) SELECT * FROM EMPCTE WHERE DENSERANK=&NUM

    Postgres and Indexes on Foreign Keys and Primary Keys

    This function, based on the work by Laurenz Albe at https://www.cybertec-postgresql.com/en/index-your-foreign-key/, list all the foreign keys with missing indexes. The size of the table is shown, as for small tables the scanning performance could be superior to the index one.

    --
    -- function:    fkeys_missing_indexes
    -- purpose:     list all foreing keys in the database without and index in the source table.
    -- author:      Laurenz Albe
    -- see:         https://www.cybertec-postgresql.com/en/index-your-foreign-key/
    --
    create or replace function oftool_fkey_missing_indexes () 
    returns table (
      src_table     regclass,
      fk_columns    varchar,
      table_size    varchar,
      fk_constraint name,
      dst_table     regclass
    )
    as $$
    select
      -- source table having ta foreign key declaration
      tc.conrelid::regclass as src_table,
      
      -- ordered list of foreign key columns
      string_agg(ta.attname, ',' order by tx.n) as fk_columns,
      
      -- source table size
      pg_catalog.pg_size_pretty (
        pg_catalog.pg_relation_size(tc.conrelid)
      ) as table_size,
      
      -- name of the foreign key constraint
      tc.conname as fk_constraint,
      
      -- name of the target or destination table
      tc.confrelid::regclass as dst_table
      
    from pg_catalog.pg_constraint tc
    
    -- enumerated key column numbers per foreign key
    cross join lateral unnest(tc.conkey) with ordinality as tx(attnum, n)
    
    -- name for each key column
    join pg_catalog.pg_attribute ta on ta.attnum = tx.attnum and ta.attrelid = tc.conrelid
    
    where not exists (
      -- is there ta matching index for the constraint?
      select 1 from pg_catalog.pg_index i
      where 
        i.indrelid = tc.conrelid and 
        -- the first index columns must be the same as the key columns, but order doesn't matter
        (i.indkey::smallint[])[0:cardinality(tc.conkey)-1] @> tc.conkey) and 
        tc.contype = 'f'
      group by 
        tc.conrelid, 
        tc.conname, 
        tc.confrelid
      order by 
        pg_catalog.pg_relation_size(tc.conrelid) desc;
    $$ language sql;
    

    test it this way,

    select * from oftool_fkey_missing_indexes();
    

    you'll see a list like this.

    fk_columns            |table_size|fk_constraint                     |dst_table        |
    ----------------------|----------|----------------------------------|-----------------|
    id_group              |0 bytes   |fk_customer__group                |im_group         |
    id_product            |0 bytes   |fk_cart_item__product             |im_store_product |
    id_tax                |0 bytes   |fk_order_tax_resume__tax          |im_tax           |
    id_product            |0 bytes   |fk_order_item__product            |im_store_product |
    id_tax                |0 bytes   |fk_invoice_tax_resume__tax        |im_tax           |
    id_product            |0 bytes   |fk_invoice_item__product          |im_store_product |
    id_article,locale_code|0 bytes   |im_article_comment_id_article_fkey|im_article_locale|
    

    Recursively find files with a specific extension

    As an alternative to using -regex option on find, since the question is labeled , you can use the brace expansion mechanism:

    eval find . -false "-o -name Robert".{jpg,pdf}
    

    What's the point of the X-Requested-With header?

    Make sure you read SilverlightFox's answer. It highlights a more important reason.

    The reason is mostly that if you know the source of a request you may want to customize it a little bit.

    For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

    Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

    Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

    But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

    The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

    It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

    Set width to match constraints in ConstraintLayout

    in the office doc: https://developer.android.com/reference/android/support/constraint/ConstraintLayout

    When a dimension is set to MATCH_CONSTRAINT, the default behavior is to have the resulting size take all the available space.

    Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"

    Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent"

    Java, how to compare Strings with String Arrays

    Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.

    Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?

    ...or do I misunderstand your question?

    Difference between require, include, require_once and include_once?

    include() will generate a warning when it doesn't find a file, but require_once() will generate a fatal error.

    Another thing is if file is included before. Then require_once() will not include it again.

    OWIN Security - How to Implement OAuth2 Refresh Tokens

    You need to implement RefreshTokenProvider. First create class for RefreshTokenProvider ie.

    public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
    {
        public override void Create(AuthenticationTokenCreateContext context)
        {
            // Expiration time in seconds
            int expire = 5*60;
            context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
            context.SetToken(context.SerializeTicket());
        }
    
        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);
        }
    }
    

    Then add instance to OAuthOptions.

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/authenticate"),
        Provider = new ApplicationOAuthProvider(),
        AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(expire),
        RefreshTokenProvider = new ApplicationRefreshTokenProvider()
    };
    

    SQL - Select first 10 rows only?

    In MySQL:

    SELECT * FROM `table` LIMIT 0, 10
    

    Making text bold using attributed string in swift

    You can do this using simple custom method written below. You have give whole string in first parameter and text to be bold in the second parameter. Hope this will help.

    func getAttributedBoldString(str : String, boldTxt : String) -> NSMutableAttributedString {
            let attrStr = NSMutableAttributedString.init(string: str)
            let boldedRange = NSRange(str.range(of: boldTxt)!, in: str)
            attrStr.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17, weight: .bold)], range: boldedRange)
            return attrStr
        }
    

    usage: initalString = I am a Boy

    label.attributedText = getAttributedBoldString(str : initalString, boldTxt : "Boy")

    resultant string = I am a Boy

    How to read a list of files from a folder using PHP?

    There is this function scandir():

    $dir = 'dir';
    $files = scandir($dir, 0);
    for($i = 2; $i < count($files); $i++)
        print $files[$i]."<br>";
    

    More here in the php.net manual

    How to disable the back button in the browser using JavaScript

    One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

    The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

    <script>
        function preventBack() {
            window.history.forward();
        }
    
        setTimeout("preventBack()", 0);
        window.onunload = function() {
            null
        };
    </script>
    

    Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

    Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

    For more information: Reference

    How to select all checkboxes with jQuery?

     $(function() {  
    $('#select_all').click(function() {
        var checkboxes = $(this).closest('form').find(':checkbox');
        if($(this).is(':checked')) {
            checkboxes.attr('checked', 'checked');
        } else {
            checkboxes.removeAttr('checked');
        }
    });
        });
    

    How to check if a column exists in a SQL Server table?

    IF NOT EXISTS( SELECT NULL
                FROM INFORMATION_SCHEMA.COLUMNS
               WHERE table_name = 'TableName'
                 AND table_schema = 'SchemaName'
                 AND column_name = 'ColumnName')  BEGIN
    
      ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';
    
    END;
    

    Is there a typical state machine implementation pattern?

    For a simple state machine just use a switch statement and an enum type for your state. Do your transitions inside the switch statement based on your input. In a real program you would obviously change the "if(input)" to check for your transition points. Hope this helps.

    typedef enum
    {
        STATE_1 = 0,
        STATE_2,
        STATE_3
    } my_state_t;
    
    my_state_t state = STATE_1;
    
    void foo(char input)
    {
        ...
        switch(state)
        {
            case STATE_1:
                if(input)
                    state = STATE_2;
                break;
            case STATE_2:
                if(input)
                    state = STATE_3;
                else
                    state = STATE_1;
                break;
            case STATE_3:
                ...
                break;
        }
        ...
    }
    

    Is there a standard sign function (signum, sgn) in C/C++?

    int sign(float n)
    {     
      union { float f; std::uint32_t i; } u { n };
      return 1 - ((u.i >> 31) << 1);
    }
    

    This function assumes:

    • binary32 representation of floating point numbers
    • a compiler that make an exception about the strict aliasing rule when using a named union

    How do you run a Python script as a service in Windows?

    The simplest way to achieve this is to use native command sc.exe:

    sc create PythonApp binPath= "C:\Python34\Python.exe --C:\tmp\pythonscript.py"
    

    References:

    1. https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
    2. When creating a service with sc.exe how to pass in context parameters?

    Convert double to BigDecimal and set BigDecimal Precision

    The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.

    According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:

    The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

    So in your case, instead of using

    double val = 77.48;
    new BigDecimal(val);
    

    use

    BigDecimal.valueOf(val);
    

    Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of Double.toString(double).

    How to access iOS simulator camera

    It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

    How to get method parameter names?

    Update for Brian's answer:

    If a function in Python 3 has keyword-only arguments, then you need to use inspect.getfullargspec:

    def yay(a, b=10, *, c=20, d=30):
        pass
    inspect.getfullargspec(yay)
    

    yields this:

    FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})
    

    Unit Testing: DateTime.Now

    Regarding to @crabcrusherclamcollector answer there is issue when using that approach in EF queries (System.NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities). I modified implementation to that:

    public static class SystemTime
        {
            private static Func<DateTime> UtcNowFunc = () => DateTime.UtcNow;
    
            public static void SetDateTime(DateTime dateTimeNow)
            {
                UtcNowFunc = () => dateTimeNow;
            }
    
            public static void ResetDateTime()
            {
                UtcNowFunc = () => DateTime.UtcNow;
            }
    
            public static DateTime UtcNow
            {
                get
                {
                    DateTime now = UtcNowFunc.Invoke();
                    return now;
                }
            }
        }
    

    How do I negate a test with regular expressions in a bash script?

    I like to simplify the code without using conditional operators in such cases:

    TEMP=/mnt/silo/bin
    [[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP
    

    Has anyone ever got a remote JMX JConsole to work?

    You need to also make sure that your machine name resolves to the IP that JMX is binding to; NOT localhost nor 127.0.0.1. For me, it has helped to put an entry into hosts that explicitly defines this.

    Split code over multiple lines in an R script

    You are not breaking code over multiple lines, but rather a single identifier. There is a difference.

    For your issue, try

    R> setwd(paste("~/a/very/long/path/here",
                   "/and/then/some/more",
                   "/and/then/some/more",
                   "/and/then/some/more", sep=""))
    

    which also illustrates that it is perfectly fine to break code across multiple lines.

    ASP.NET DateTime Picker

    The answer to your question is that Yes there are good free/open source time picker controls that go well with ASP.NET Calendar controls.

    ASP.NET calendar controls just write an HTML table.

    If you are using HTML5 and .NET Framework 4.5, you can instead use an ASP.NET TextBox control and set the TextMode property to "Date", "Month", "Week", "Time", or "DateTimeLocal" -- or if you your browser doesn't support this, you can set this property to "DateTime". You can then read the Text property to get the date, or time, or month, or week as a string from the TextBox.

    If you are using .NET Framework 4.0 or an older version, then you can use HTML5's <input type="[month, week, etc.]">; if your browser doesn't support this, use <input type="datetime">.

    If you need the server-side code (written in either C# or Visual Basic) for the information that the user inputs in the date field, then you can try to run the element on the server by writing runat="server" inside the input tag. As with all things ASP, make sure to give this element an ID so you can access it on the server side. Now you can read the Value property to get the input date, time, month, or week as a string.

    If you cannot run this element on the server, then you will need a hidden field in addition to the <input type="[date/time/month/week/etc.]". In the submit function (written in JavaScript), set the value of the hidden field to the value of the input type="date", or "time", or "month", or "week" -- then on the server-side code, read the Value property of that hidden field as string too.

    Make sure that the hidden field element of the HTML can run on the server.

    Visual Studio 2017 errors on standard headers

    This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.

    Example:

    • EXE with C++ 17 enabled explicitly
    • Unit Test with C++ version set to "Default"

    Solution: change the Unit Test to C++17 as well.

    Screenshot

    How do I move files in node.js?

    Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:

    function copy(callback) {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);
    
        readStream.on('error', callback);
        writeStream.on('error', callback);
    
        // Do not callback() upon "close" event on the readStream
        // readStream.on('close', function () {
        // Do instead upon "close" on the writeStream
        writeStream.on('close', function () {
            callback();
        });
    
        readStream.pipe(writeStream);
    }
    

    The copy function wrapped in a Promise:

    function copy(oldPath, newPath) {
      return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(oldPath);
        const writeStream = fs.createWriteStream(newPath);
    
        readStream.on('error', err => reject(err));
        writeStream.on('error', err => reject(err));
    
        writeStream.on('close', function() {
          resolve();
        });
    
        readStream.pipe(writeStream);
      })
    

    However, keep in mind that the filesystem might crash if the target folder doesn't exist.

    How can I make a list of installed packages in a certain virtualenv?

    In my case the flask version was only visible under so I had to go to C:\Users\\AppData\Local\flask\venv\Scripts>pip freeze --local

    How to add color to Github's README.md file

    You can use the diff language tag to generate some colored text:

    ```diff
    - text in red
    + text in green
    ! text in orange
    # text in gray
    @@ text in purple (and bold)@@
    ```
    

    However, it adds it as a new line starting with either - + ! # or starts and ends with @@

    enter image description here

    This issue was raised in github markup #369, but they haven't made any change in decision since then (2014).

    Difference between volatile and synchronized in Java

    volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

        int i1;
        int geti1() {return i1;}
    
        volatile int i2;
        int geti2() {return i2;}
    
        int i3;
        synchronized int geti3() {return i3;}
    

    geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

    On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.

    There are two differences between volitile and synchronized.

    Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

    1. The thread acquires the lock on the monitor for object this .
    2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
    3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
    4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
    5. The thread releases the lock on the monitor for object this.

    So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

    http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html

    How to send and receive JSON data from a restful webservice using Jersey API

    For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

    java(Jax-rs) and Angular way

    I hope it's helpful to someone using JAVA Rest and AngularJS like me.

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, String> methodName(String data) throws Exception {
        JSONObject recoData = new JSONObject(data);
        //Do whatever with json object
    }
    

    Client side I used AngularJS

    factory.update = function () {
    data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
            data= JSON.stringify(data);//Convert object to string
            var d = $q.defer();
            $http({
                method: 'POST',
                url: 'REST/webApp/update',
                headers: {'Content-Type': 'text/plain'},
                data:data
            })
            .success(function (response) {
                d.resolve(response);
            })
            .error(function (response) {
                d.reject(response);
            });
    
            return d.promise;
        };
    

    How to initialize a static array?

    If you are creating an array then there is no difference, however, the following is neater:

    String[] suit = {
      "spades", 
      "hearts", 
      "diamonds", 
      "clubs"  
    };
    

    But, if you want to pass an array into a method you have to call it like this:

    myMethod(new String[] {"spades", "hearts"});
    
    myMethod({"spades", "hearts"}); //won't compile!
    

    Calculating how many days are between two dates in DB2?

    I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :

    SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5
    

    for more information check this site

    Showing percentages above bars on Excel column graph

    Either

    1. Use a line series to show the %
    2. Update the data labels above the bars to link back directly to other cells

    Method 2 by step

    • add data-lables
    • right-click the data lable
    • goto the edit bar and type in a refence to a cell (C4 in this example)
    • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

    enter image description here

    What are OLTP and OLAP. What is the difference between them?

    The difference is quite simple:

    OLTP (Online Transaction Processing)

    OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

    OLAP (Online Analytical Processing)

    OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

    See more details OLTP and OLAP

    Align the form to the center in Bootstrap 4

    All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

    A sample form

    enter image description here

    HTML

    <div class="container-fluid h-100 bg-light text-dark">
      <div class="row justify-content-center align-items-center">
        <h1>Form</h1>    
      </div>
      <hr/>
      <div class="row justify-content-center align-items-center h-100">
        <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
          <form action="">
            <div class="form-group">
              <select class="form-control">
                        <option>Option 1</option>
                        <option>Option 2</option>
                      </select>
            </div>
            <div class="form-group">
              <input type="text" class="form-control" />
            </div>
            <div class="form-group text-center">
              <div class="form-check-inline">
                <label class="form-check-label">
        <input type="radio" class="form-check-input" name="optradio">Option 1
      </label>
              </div>
              <div class="form-check-inline">
                <label class="form-check-label">
        <input type="radio" class="form-check-input" name="optradio">Option 2
      </label>
              </div>
              <div class="form-check-inline">
                <label class="form-check-label">
        <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
      </label>
              </div>
            </div>
            <div class="form-group">
              <div class="container">
                <div class="row">
                  <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
                  <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
                </div>
              </div>
            </div>
    
          </form>
        </div>
      </div>
    </div>
    

    Link to CodePen

    https://codepen.io/anjanasilva/pen/WgLaGZ

    I hope this helps someone. Thank you.

    What does T&& (double ampersand) mean in C++11?

    The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

    That is because it may be either r-value or l-value.

    Examples are:

    // template
    template<class T> foo(T&& t) { ... }
    
    // auto
    auto&& t = ...;
    
    // typedef
    typedef ... T;
    T&& t = ...;
    
    // decltype
    decltype(...)&& t = ...;
    

    More discussion can be found in the answer for: Syntax for universal references

    How to check the Angular version?

    run ng version

    then simply check the version of angular core package.

    @angular/cli: 1.2.6
    node: 8.11.1
    os: win32 x64
    @angular/animations: 4.3.2
    @angular/common: 4.3.2
    @angular/compiler: 4.3.2
    **@angular/core: 4.3.2**
    @angular/forms: 4.3.2
    

    org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

    I agree with the accepted answer. But for me, the issue was not that, instead I had to modify my Servlet-Class name from:-

    <servlet-class>org.glassfish.jersey.servlet.ServletContainer.class</servlet-class> 
    

    To:

    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    

    So, removing .class worked fine in my case. Hope it will help somebody!

    CSV file written with Python has blank lines between each row

    The simple answer is that csv files should always be opened in binary mode whether for input or output, as otherwise on Windows there are problems with the line ending. Specifically on output the csv module will write \r\n (the standard CSV row terminator) and then (in text mode) the runtime will replace the \n by \r\n (the Windows standard line terminator) giving a result of \r\r\n.

    Fiddling with the lineterminator is NOT the solution.

    Java string to date conversion

    Also, SimpleDateFormat is not available with some of the client-side technologies, like GWT.

    It's a good idea to go for Calendar.getInstance(), and your requirement is to compare two dates; go for long date.

    How can I copy the content of a branch to a new local branch?

    With Git 2.15 (Q4 2017), "git branch" learned "-c/-C" to create a new branch by copying an existing one.

    See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar).
    See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305).
    (Merged by Junio C Hamano -- gitster -- in commit 3b48045, 03 Oct 2017)

    branch: add a --copy (-c) option to go with --move (-m)

    Add the ability to --copy a branch and its reflog and configuration, this uses the same underlying machinery as the --move (-m) option except the reflog and configuration is copied instead of being moved.

    This is useful for e.g. copying a topic branch to a new version, e.g. work to work-2 after submitting the work topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike --move keeping the other already-submitted branch around for reference.

    Note: when copying a branch, you remain on your current branch.
    As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:

    When creating a new branch B by copying the branch A that happens to be the current branch, it also updates HEAD to point at the new branch.
    It probably was made this way because "git branch -c A B" piggybacked its implementation on "git branch -m A B",

    This does not match the usual expectation.
    If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).

    But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.

    Is there an equivalent of lsusb for OS X

    Homebrew users: you can get lsusb by installing usbutils formula from my tap:

    brew install mikhailai/misc/usbutils
    

    It installs the REAL lsusb based on Linux sources (version 007).

    Non-recursive depth first search algorithm

    An ES6 implementation based on biziclops great answer:

    _x000D_
    _x000D_
    root = {_x000D_
      text: "root",_x000D_
      children: [{_x000D_
        text: "c1",_x000D_
        children: [{_x000D_
          text: "c11"_x000D_
        }, {_x000D_
          text: "c12"_x000D_
        }]_x000D_
      }, {_x000D_
        text: "c2",_x000D_
        children: [{_x000D_
          text: "c21"_x000D_
        }, {_x000D_
          text: "c22"_x000D_
        }]_x000D_
      }, ]_x000D_
    }_x000D_
    _x000D_
    console.log("DFS:")_x000D_
    DFS(root, node => node.children, node => console.log(node.text));_x000D_
    _x000D_
    console.log("BFS:")_x000D_
    BFS(root, node => node.children, node => console.log(node.text));_x000D_
    _x000D_
    function BFS(root, getChildren, visit) {_x000D_
      let nodesToVisit = [root];_x000D_
      while (nodesToVisit.length > 0) {_x000D_
        const currentNode = nodesToVisit.shift();_x000D_
        nodesToVisit = [_x000D_
          ...nodesToVisit,_x000D_
          ...(getChildren(currentNode) || []),_x000D_
        ];_x000D_
        visit(currentNode);_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    function DFS(root, getChildren, visit) {_x000D_
      let nodesToVisit = [root];_x000D_
      while (nodesToVisit.length > 0) {_x000D_
        const currentNode = nodesToVisit.shift();_x000D_
        nodesToVisit = [_x000D_
          ...(getChildren(currentNode) || []),_x000D_
          ...nodesToVisit,_x000D_
        ];_x000D_
        visit(currentNode);_x000D_
      }_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    Twitter Bootstrap alert message close and open again

    Can this not be done simply by adding a additional "container" div and adding the removed alert div back into it each time. Seems to work for me?

    HTML

    <div id="alert_container"></div>
    

    JS

     $("#alert_container").html('<div id="alert"></div>');          
     $("#alert").addClass("alert alert-info  alert-dismissible");
     $("#alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Info!</strong>message');
    

    String method cannot be found in a main class method

    It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

    Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

    Alternatively, you can compare the names of the resorts. For example

    if (resortList[mid].getResortName().compareTo(resortName)>0)