Programs & Examples On #Vptr

Reference for C++ Virtual Pointer.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I was able to fix this issue by changing $(document).ready() to window.onLoad().

Creating a search form in PHP to search a database?

Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.

BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.

How to preserve request url with nginx proxy_pass

To perfectly forward without chopping the absoluteURI of the request and the Host in the header:

server {
    listen 35005;

    location / {
        rewrite            ^(.*)$   "://$http_host$uri$is_args$args";
        rewrite            ^(.*)$   "http$uri$is_args$args" break;
        proxy_set_header   Host     $host;

        proxy_pass         https://deploy.org.local:35005;
    }
}

Found here: https://opensysnotes.wordpress.com/2016/11/17/nginx-proxy_pass-with-absolute-url/

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How do I put a clear button inside my HTML text input box like the iPhone does?

It is so simple in HTML5

<input type="search">

This will do your job!

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

How to get last inserted id?

There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:

<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();

/*** Initialize and update Table Data Here ***/

/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();

//Update the Dataset
tblAdpt.Update(tblData);

//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;

Hope this Helps ...

Select parent element of known element in Selenium

This might be useful for someone else: Using this sample html

<div class="ParentDiv">
    <label for="label">labelName</label>
    <input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
    <label for="animal">pig</label>
    <input type="button" value="elementToSelect">
</div>

If for example, I want to select an element in the same section (e.g div) as a label, you can use this

//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect'] 

This just means, look for a label (it could anything like a, h2) called labelName. Navigate to the parent of that label (i.e. div class="ParentDiv"). Search within the descendants of that parent to find any child element with the value of elementToSelect. With this, it will not select the second elementToSelect with DontSelect div as parent.

The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need. Other Syntax like following-sibling::h2 can also be used in some cases. This means the sibling following element h2. This will work for elements at the same level, having the same parent.

Illegal access: this web application instance has been stopped already

In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.

So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.

Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).

Check if string matches pattern

  
import re

ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
  


I believe that should work for an uppercase, number pattern.

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

How to get javax.comm API?

Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.

if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

Simulate a button click in Jest

Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick() and similar events (see example below).

The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.

Here is an example of how the onClick() event may be tested in an isolated SearchForm component using Jest and react-test-renderer.

import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';

describe('SearchForm', () => {
  it('should fire onSubmit form callback', () => {
    // Mock search form parameters.
    const searchQuery = 'kittens';
    const onSubmit = jest.fn();

    // Create test component instance.
    const testComponentInstance = renderer.create((
      <SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
    )).root;

    // Try to find submit button inside the form.
    const submitButtonInstance = testComponentInstance.findByProps({
      type: 'submit',
    });
    expect(submitButtonInstance).toBeDefined();

    // Since we're not going to test the button component itself
    // we may just simulate its onClick event manually.
    const eventMock = { preventDefault: jest.fn() };
    submitButtonInstance.props.onClick(eventMock);

    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith(searchQuery);
  });
});

'dict' object has no attribute 'has_key'

The whole code in the document will be:

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}
def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

After writing it, save the document and press F 5

After that, the code you will run in the Python IDLE shell will be:

find_path(graph, 'A','D')

The answer you should receive in IDLE is

['A', 'B', 'C', 'D'] 

How do I use Wget to download all images into a single folder, from a URL?

I wrote a shellscript that solves this problem for multiple websites: https://github.com/eduardschaeli/wget-image-scraper

(Scrapes images from a list of urls with wget)

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

  1. clusterIP : IP accessible inside cluster (across nodes within d cluster).
nodeA : pod1 => clusterIP1, pod2 => clusterIP2
nodeB : pod3 => clusterIP3.

pod3 can talk to pod1 via their clusterIP network.

  1. nodeport : to make pods accessible from outside the cluster via nodeIP:nodeport, it will create/keep clusterIP above as its clusterIP network.
nodeA => nodeIPA : nodeportX
nodeB => nodeIPB : nodeportX

you might access service on pod1 either via nodeIPA:nodeportX OR nodeIPB:nodeportX. Either way will work because kube-proxy (which is installed in each node) will receive your request and distribute it [redirect it(iptables term)] across nodes using clusterIP network.

  1. Load balancer

basically just putting LB in front, so that inbound traffic is distributed to nodeIPA:nodeportX and nodeIPB:nodeportX then continue with the process flow number 2 above.

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Regex match everything after question mark?

Try this:

\?(.*)

The parentheses are a capturing group that you can use to extract the part of the string you are interested in.

If the string can contain new lines you may have to use the "dot all" modifier to allow the dot to match the new line character. Whether or not you have to do this, and how to do this, depends on the language you are using. It appears that you forgot to mention the programming language you are using in your question.

Another alternative that you can use if your language supports fixed width lookbehind assertions is:

(?<=\?).*

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

How can I use optional parameters in a T-SQL stored procedure?

Extend your WHERE condition:

WHERE
    (FirstName = ISNULL(@FirstName, FirstName)
    OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
    OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
    OR COALESCE(@Title, Title, '') = '')

i. e. combine different cases with boolean conditions.

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

how to cancel/abort ajax request in axios

There is really nice package with few examples of usage called axios-cancel. I've found it very helpful. Here is the link: https://www.npmjs.com/package/axios-cancel

Changing the size of a column referenced by a schema-bound view in SQL Server

Check the column collation. This script might change the collation to the table default. Add the current collation to the script.

How to convert an Stream into a byte[] in C#?

In .NET Framework 4 and later, the Stream class has a built-in CopyTo method that you can use.

For earlier versions of the framework, the handy helper function to have is:

public static void CopyStream(Stream input, Stream output)
{
    byte[] b = new byte[32768];
    int r;
    while ((r = input.Read(b, 0, b.Length)) > 0)
        output.Write(b, 0, r);
}

Then use one of the above methods to copy to a MemoryStream and call GetBuffer on it:

var file = new FileStream("c:\\foo.txt", FileMode.Open);

var mem = new MemoryStream();

// If using .NET 4 or later:
file.CopyTo(mem);

// Otherwise:
CopyStream(file, mem);

// getting the internal buffer (no additional copying)
byte[] buffer = mem.GetBuffer();
long length = mem.Length; // the actual length of the data 
                          // (the array may be longer)

// if you need the array to be exactly as long as the data
byte[] truncated = mem.ToArray(); // makes another copy

Edit: originally I suggested using Jason's answer for a Stream that supports the Length property. But it had a flaw because it assumed that the Stream would return all its contents in a single Read, which is not necessarily true (not for a Socket, for example.) I don't know if there is an example of a Stream implementation in the BCL that does support Length but might return the data in shorter chunks than you request, but as anyone can inherit Stream this could easily be the case.

It's probably simpler for most cases to use the above general solution, but supposing you did want to read directly into an array that is bigEnough:

byte[] b = new byte[bigEnough];
int r, offset;
while ((r = input.Read(b, offset, b.Length - offset)) > 0)
    offset += r;

That is, repeatedly call Read and move the position you will be storing the data at.

How I could add dir to $PATH in Makefile?

Path changes appear to be persistent if you set the SHELL variable in your makefile first:

SHELL := /bin/bash
PATH := bin:$(PATH)

test all:
    x

I don't know if this is desired behavior or not.

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I faced the same issue, It got fixed after keeping issuer subject value in the certificate as it is as subject of issuer certificate.

so please check "issuer subject value in the certificate(cert.pem) == subject of issuer (CA.pem)"

openssl verify -CAfile CA.pem cert.pem
cert.pem: OK

Passing headers with axios POST request

You can also use interceptors to pass the headers

It can save you a lot of code

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

How to implement endless list with RecyclerView?

I achieved an infinite scrolling type implementation using this logic in the onBindViewHolder method of my RecyclerView.Adapter class.

    if (position == mItems.size() - 1 && mCurrentPage <= mTotalPageCount) {
        if (mCurrentPage == mTotalPageCount) {
            mLoadImagesListener.noMorePages();
        } else {
            int newPage = mCurrentPage + 1;
            mLoadImagesListener.loadPage(newPage);
        }
    }

With this code when the RecyclerView gets to the last item, it increments the current page and callbacks on an interface which is responsible for loading more data from the api and adding the new results to the adapter.

I can post more complete example if this isn't clear?

Double vs. BigDecimal?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.

The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded).

If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.

I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Did you try:

<Directory /path/to/your/wp-admin>
Order allow,deny
Allow from all
</Directory>

Build a simple HTTP server in C

I suggest you take a look at tiny httpd. If you want to write it from scratch, then you'll want to thoroughly read RFC 2616. Use BSD sockets to access the network at a really low level.

Removing all script tags from html with JS Regular Expression

Here are a variety of shell scripts you can use to strip out different elements.

# doctype
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<\!DOCTYPE\s\+html[^>]*>/<\!DOCTYPE html>/gi" {} \;

# meta charset
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<meta[^>]*content=[\"'][^\"']*utf-8[\"'][^>]*>/<meta charset=\"utf-8\">/gi" {} \;

# script text/javascript
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<script[^>]*\)\(\stype=[\"']text\/javascript[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# style text/css
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<style[^>]*\)\(\stype=[\"']text\/css[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xmlns
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxmlns=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xml:lang
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxml:lang=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

HTML 5 Video "autoplay" not automatically starting in CHROME

I was just reading this article, and it says:

Important: the order of the video files is vital; Chrome currently has a bug in which it will not autoplay a .webm video if it comes after anything else.

So it looks like your problem would be solved if you put the .webm first in your list of sources. Hope that helps.

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

iPhone: How to get current milliseconds?

Try this :

NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];

NSString *newDateString = [dateFormatter stringFromDate:timestamp];
timestamp = (NSDate*)newDateString;

In this example, dateWithTimeIntervalSince1970 is used in combination of the formatter @"YYYY-MM-dd HH:mm:ss.SSS" that will return the date with year, month, day and the time with hours, minutes, seconds, and milliseconds. See the example : "2015-12-02 04:43:15.008". I used the NSString to be sure that the format will be has written before.

Convert python datetime to epoch with strftime

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

Convert string to integer type in Go?

For example,

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

func main() {
    flag.Parse()
    s := flag.Arg(0)
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println(s, i)
}

Comparing HTTP and FTP for transferring files

Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.

How to run stored procedures in Entity Framework Core?

I had a lot of trouble with the ExecuteSqlCommand and ExecuteSqlCommandAsync, IN parameters were easy, but OUT parameters were very difficult.

I had to revert to using DbCommand like so -

DbCommand cmd = _context.Database.GetDbConnection().CreateCommand();

cmd.CommandText = "dbo.sp_DoSomething";
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar) { Value = "Steve" });
cmd.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar) { Value = "Smith" });

cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt) { Direction = ParameterDirection.Output });

I wrote more about it in this post.

How do you open a file in C++?

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

VB.NET Switch Statement GoTo Case

There is no equivalent in VB.NET that I could find. For this piece of code you are probably going to want to open it in Reflector and change the output type to VB to get the exact copy of the code that you need. For instance when I put the following in to Reflector:

switch (args[0])
{
    case "UserID":
        Console.Write("UserID");
        break;
    case "PackageID":
        Console.Write("PackageID");
        break;
    case "MVRType":
        if (args[1] == "None")
            Console.Write("None");
        else
            goto default;
        break;
    default:
        Console.Write("Default");
        break;
}

it gave me the following VB.NET output.

Dim CS$4$0000 As String = args(0)
If (Not CS$4$0000 Is Nothing) Then
    If (CS$4$0000 = "UserID") Then
        Console.Write("UserID")
        Return
    End If
    If (CS$4$0000 = "PackageID") Then
        Console.Write("PackageID")
        Return
    End If
    If ((CS$4$0000 = "MVRType") AndAlso (args(1) = "None")) Then
        Console.Write("None")
        Return
    End If
End If
Console.Write("Default")

As you can see you can accomplish the same switch case statement with If statements. Usually I don't recommend this because it makes it harder to understand, but VB.NET doesn't seem to support the same functionality, and using Reflector might be the best way to get the code you need to get it working with out a lot of pain.

Update:

Just confirmed you cannot do the exact same thing in VB.NET, but it does support some other useful things. Looks like the IF statement conversion is your best bet, or maybe some refactoring. Here is the definition for Select...Case

http://msdn.microsoft.com/en-us/library/cy37t14y.aspx

oracle varchar to number

Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:

select * from exception where exception_value = to_char(105);

Is there any way to kill a Thread?

If you are explicitly calling time.sleep() as part of your thread (say polling some external service), an improvement upon Phillipe's method is to use the timeout in the event's wait() method wherever you sleep()

For example:

import threading

class KillableThread(threading.Thread):
    def __init__(self, sleep_interval=1):
        super().__init__()
        self._kill = threading.Event()
        self._interval = sleep_interval

    def run(self):
        while True:
            print("Do Something")

            # If no kill signal is set, sleep for the interval,
            # If kill signal comes in while sleeping, immediately
            #  wake up and handle
            is_killed = self._kill.wait(self._interval)
            if is_killed:
                break

        print("Killing Thread")

    def kill(self):
        self._kill.set()

Then to run it

t = KillableThread(sleep_interval=5)
t.start()
# Every 5 seconds it prints:
#: Do Something
t.kill()
#: Killing Thread

The advantage of using wait() instead of sleep()ing and regularly checking the event is that you can program in longer intervals of sleep, the thread is stopped almost immediately (when you would otherwise be sleep()ing) and in my opinion, the code for handling exit is significantly simpler.

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

How to check whether a Button is clicked by using JavaScript

All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

function functionName(){
//function defination
}



document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.

Can you have multiline HTML5 placeholder text in a <textarea>?

On most (see details below) browsers, editing the placeholder in javascript allows multiline placeholder. As it has been said, it's not compliant with the specification and you shouldn't expect it to work in the future (edit: it does work).

This example replaces all multiline textarea's placeholder.

_x000D_
_x000D_
var textAreas = document.getElementsByTagName('textarea');

Array.prototype.forEach.call(textAreas, function(elem) {
    elem.placeholder = elem.placeholder.replace(/\\n/g, '\n');
});
_x000D_
<textarea class="textAreaMultiline" 
          placeholder="Hello, \nThis is multiline example \n\nHave Fun"
          rows="5" cols="35"></textarea>
_x000D_
_x000D_
_x000D_

JsFiddle snippet.

Expected result

Expected result


Based on comments it seems some browser accepts this hack and others don't.
This is the results of tests I ran (with browsertshots and browserstack)

  • Chrome: >= 35.0.1916.69
  • Firefox: >= 35.0 (results varies on platform)
  • IE: >= 10
  • KHTML based browsers: 4.8
  • Safari: No (tested = Safari 8.0.6 Mac OS X 10.8)
  • Opera: No (tested <= 15.0.1147.72)

Fused with theses statistics, this means that it works on about 88.7% of currently (Oct 2015) used browsers.

Update: Today, it works on at least 94.4% of currently (July 2018) used browsers.

Spring Boot without the web server

In Spring boot, Spring Web dependency provides an embedded Apache Tomcat web server. If you remove spring-boot-starter-web dependency in the pom.xml then it doesn't provide an embedded web server.

remove the following dependency

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

How to access custom attributes from event object in React?

<div className='btn' onClick={(e) =>
     console.log(e.currentTarget.attributes['tag'].value)}
     tag='bold'>
    <i className='fa fa-bold' />
</div>

so e.currentTarget.attributes['tag'].value works for me

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

Overriding interface property type defined in Typescript d.ts file

For narrowing the type of the property, simple extend works perfect, as in Nitzan's answer:

interface A {
    x: string | number;
}

interface B extends A {
    x: number;
}

For widening, or generally overriding the type, you can do Zskycat's solution:

interface A {
    x: string
}

export type B = Omit<A, 'x'> & { x: number };

But, if your interface A is extending a general interface, you will lose the custom types of A's remaining properties when using Omit.

e.g.

interface A extends Record<string | number, number | string | boolean> {
    x: string;
    y: boolean;
}

export type B = Omit<A, 'x'> & { x: number };

let b: B = { x: 2, y: "hi" }; // no error on b.y! 

The reason is, Omit internally only goes over Exclude<keyof A, 'x'> keys which will be the general string | number in our case. So, B would become {x: number; } and accepts any extra property with the type of number | string | boolean.


To fix that, I came up with a different OverrideProps utility type as following:

type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };

Example:

type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };

interface A extends Record<string | number, number | string | boolean> {
    x: string;
    y: boolean;
}

export type B = OverrideProps<A, { x: number }>;

let b: B = { x: 2, y: "hi" }; // error: b.y should be boolean!

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

As of Genymotion 2.10.0 and onwards, GApps can be installed from the emulator toolbar. Please refer to answer by @MichaelStoddart.

Next follows former answer kept here for historic reason:

Genymotion doesn't provide Google Apps. To install Google Apps:

  1. Upgrade Genymotion and VirtualBox to the latest version.

  2. Download two zip files:
    - ARM Translation Installer v1.1
    - Google Apps for your Android version: 2.3.7 - 4.4.4 or 4.4 - 6.0 (with platform and variant) You can also find the GApps list in the wbroek user GitHubGist page.

  3. Open Genymotion emulator and go to home screen then drag and drop the first file Genymotion-ARM-Translation_v1.1.zip over the emulator. A dialog will appear and show as file transfer in progress, then another dialog will appear and ask that do you want to flash it on the emulator. Click OK and reboot the device by running adb reboot from your terminal or command prompt.

  4. Drag and drop the second file gapps-*-signed.zip and repeat the same steps as above. Run adb reboot again and, once rebooted, Google Apps will be in the emulator.

  5. At this point 'Google Apps Services' will crash frequently with the following message google play services has stopped working. Open Google Play. After providing your account details, open Google Play and update your installed Google Apps. This seems to make Google Play realize you have an old Google Play Services and will ask you to update (in my case, updating Google Hangouts required a new version of Google Play Services). I've also heard that simply waiting will also prompt you to update. The 'Google Play Services' app doesn't seem to appear otherwise - you can't search for it. You should then see an offer to update Google Play Services. Once the new Google Play Services is installed you will now have stable, working access to Google Play

Jquery $.ajax fails in IE on cross domain calls

Note, adding

$.support.cors = true;

was sufficient to force $.ajax calls to work on IE8

Pass a JavaScript function as parameter

I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.

function addContact(parameters, refreshCallback) {
    refreshCallback.apply(this, parameters);
}

function refreshContactList(int, int, string) {
    alert(int + int);
    console.log(string);
}

addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array

How to initialize a variable of date type in java?

To parse a Date from a String you can choose which format you would like it to have. For example:

public Date StringToDate(String s){

    Date result = null;
    try{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result  = dateFormat.parse(s);
    }

    catch(ParseException e){
        e.printStackTrace();

    }
    return result ;
}

If you would like to use this method now, you will have to use something like this

Date date = StringToDate("2015-12-06 17:03:00");

For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows().

For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach language construct does: it goes through the body of the loop for each entry in the array $row. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)).

Bootstrap Dropdown menu is not working

Maybe someone out there can benefit from this:

Summary (a.k.a. tl;dr)

Bootstrap dropdowns stopped dropping down due to upgrade from django-bootstrap3 version 6.2.2 to 11.0.0.

Background

We encountered a similar issue in a legacy django site which relies heavily on bootstrap through django-bootstrap3. The site had always worked fine, and continued to do so in production, but not on our local test system. There were no obvious related changes in the code, so a dependency issue was most likely.

Symptoms

When visiting the site on the local django test server, it looked perfectly O.K. at first glance: style/layout using bootstrap as expected, including the navbar. However, all dropdown menus failed to drop down.

No errors in the browser console. All static js and css files were loaded successfully, and functionality from other packages relying on jquery was working as expected.

Solution

It turned out that the django-bootstrap3 package in our local python environment had been upgraded to the latest version, 11.0.0, whereas the site was built using 6.2.2.

Rolling back to django-bootstrap3==6.2.2 solved the issue for us, although I have no idea what exactly caused it.

Sort ObservableCollection<string> through C#

This extension method eliminates the need to sort the entire list.

Instead, it inserts each new item in place. So the list is always remains sorted.

It turns out that this method just works when a lot of the other methods fail due to missing notifications when the collection changes. And it is rather fast.

The code below should be bulletproof; it has been extensively tested in a large-scale production environment.

To use:

// Call on dispatcher.
ObservableCollection<MyClass> collectionView = new ObservableCollection<MyClass>();
var p1 = new MyClass() { Key = "A" }
var p2 = new MyClass() { Key = "Z" }
var p3 = new MyClass() { Key = "D" }
collectionView.InsertInPlace(p1, o => o.Key);
collectionView.InsertInPlace(p2, o => o.Key);
collectionView.InsertInPlace(p3, o => o.Key);
// The list will always remain ordered on the screen, e.g. "A, D, Z" .
// Insertion speed is Log(N) as it uses a binary search.

And the extension method:

/// <summary>
/// Inserts an item into a list in the correct place, based on the provided key and key comparer. Use like OrderBy(o => o.PropertyWithKey).
/// </summary>
public static void InsertInPlace<TItem, TKey>(this ObservableCollection<TItem> collection, TItem itemToAdd, Func<TItem, TKey> keyGetter)
{
    int index = collection.ToList().BinarySearch(keyGetter(itemToAdd), Comparer<TKey>.Default, keyGetter);
    collection.Insert(index, itemToAdd);
}

And the binary search extension method:

/// <summary>
/// Binary search.
/// </summary>
/// <returns>Index of item in collection.</returns> 
/// <notes>This version tops out at approximately 25% faster than the equivalent recursive version. This 25% speedup is for list
/// lengths more of than 1000 items, with less performance advantage for smaller lists.</notes>
public static int BinarySearch<TItem, TKey>(this IList<TItem> collection, TKey keyToFind, IComparer<TKey> comparer, Func<TItem, TKey> keyGetter)
{
    if (collection == null)
    {
        throw new ArgumentNullException(nameof(collection));
    }

    int lower = 0;
    int upper = collection.Count - 1;

    while (lower <= upper)
    {
        int middle = lower + (upper - lower) / 2;
        int comparisonResult = comparer.Compare(keyToFind, keyGetter.Invoke(collection[middle]));
        if (comparisonResult == 0)
        {
            return middle;
        }
        else if (comparisonResult < 0)
        {
            upper = middle - 1;
        }
        else
        {
            lower = middle + 1;
        }
    }

    // If we cannot find the item, return the item below it, so the new item will be inserted next.
    return lower;
}

Count character occurrences in a string in C++

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

example:

string str2 = "_";
string strData = "bla_bla_blabla_bla_";

size_t pos = 0,pos2;

while ((pos = strData.find(str2, pos)) < strData.length()) 
{
    printf("\n%d", pos);
    pos += str2.length();
} 

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.

can't start MySql in Mac OS 10.6 Snow Leopard

my apple processor version10.6.3 is error and i can click system preference

Logo image and H1 heading on the same line

you can do this by using just one line code..

<h1><img src="img/logo.png" alt="logo"/>My website name</h1>

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

Remove tracking branches no longer on remote

I like using pipes because it makes the command easier to read.

This is my solution if you would like to remove all branches except master.

git branch | grep -v master | xargs -n 1 git branch -D

To delete other branches that match your criteria, modify the first and second block.

git branch --merged | grep feature_name | xargs -n 1 git branch -D

Transparent background in JPEG image

JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

Trusting all certificates with okHttp

SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.

Source: OkHttp documentation

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslContext.getSocketFactory(),
    new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    });

How do I remove all .pyc files from a project?

Django Extension

Note: This answer is very specific to Django project that have already been using Django Extension.

python manage.py clean_pyc

The implementation can be viewed in its source code.

setting min date in jquery datepicker

Try like this

<script>

  $(document).ready(function(){
          $("#order_ship_date").datepicker({
           changeMonth:true,
           changeYear:true,           
            dateFormat:"yy-mm-dd",
            minDate: +2,
        });
  }); 


</script>

html code is given below

<input id="order_ship_date"  type="text" class="input" style="width:80px;"  />

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

If using MVC 5 read this solution!

I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace SydHeller.Filters
{
    public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
            if (clientToken == null)
            {
                throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
            }

            string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
            if (serverToken == null)
            {
                throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
            }

            System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
        }

        private const string KEY_NAME = "__RequestVerificationToken";
    }
}

-- Make note of the using System.Web.Mvc and using System.Web.Mvc.Filters, not the http libraries (I think that is one of the things that changed with MVC v5. --

Then just apply the filter [ValidateJSONAntiForgeryHeader] to your action (or controller) and it should get called correctly.

In my layout page right above </body> I have @AntiForgery.GetHtml();

Finally, in my Razor page, I do the ajax call as follows:

var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
  type: "POST",
  url: serviceURL,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: requestData,
  headers: {
     "__RequestVerificationToken": formForgeryToken
  },
     success: crimeDataSuccessFunc,
     error: crimeDataErrorFunc
});

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

how to list all sub directories in a directory

Easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

Allowed memory size of 536870912 bytes exhausted in Laravel

Share the lines of code executed when you make this request. There might be an error in your code.

Also, you can change the memory limit in your php.ini file via the memory_limit setting. Try doubling your memory to 64M. If this doesn't work you can try doubling it again, but I'd bet the problem is in your code.

ini_set('memory_limit', '64M');

Set Locale programmatically

Call this method on BaseActivity -> onCreate() and BaseFragment -> OnCreateView()

Tested on API 22, 23, 24, 25, 26, 27, 28, 29...uptodate version

fun Context.updateLang() {
    val resources = resources
    val config = Configuration(resources.configuration)
    config.setLocale(PreferenceManager(this).getAppLanguage()) // language from preference
    val dm = resources.displayMetrics
    createConfigurationContext(config)
    resources.updateConfiguration(config, dm)
}

Using SQL LIKE and IN together

substr([column name],
       [desired starting position (numeric)],
       [# characters to include (numeric)]) in ([complete as usual])

Example

substr([column name],1,4) in ('M510','M615', 'M515', 'M612')

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

How to set seekbar min and max value

Copy this class and use custom Seek Bar :

public class MinMaxSeekBar extends SeekBar implements SeekBar.OnSeekBarChangeListener {
private OnMinMaxSeekBarChangeListener onMinMaxSeekBarChangeListener = null;
private int intMaxValue = 100;
private int intPrgress = 0;
private int minPrgress = 0;


public int getIntMaxValue() {
    return intMaxValue;
}

public void setIntMaxValue(int intMaxValue) {
    this.intMaxValue = intMaxValue;
    int middle = getMiddle(intMaxValue, minPrgress);
    super.setMax(middle);
}

public int getIntPrgress() {
    return intPrgress;
}

public void setIntPrgress(int intPrgress) {
    this.intPrgress = intPrgress;
}

public int getMinPrgress() {
    return minPrgress;
}

public void setMinPrgress(int minPrgress) {
    this.minPrgress = minPrgress;
    int middle = getMiddle(intMaxValue, minPrgress);
    super.setMax(middle);
}

private int getMiddle(int floatMaxValue, int minPrgress) {
    int v = floatMaxValue - minPrgress;
    return v;
}

public MinMaxSeekBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setOnSeekBarChangeListener(this);
}

public MinMaxSeekBar(Context context) {
    super(context);
    this.setOnSeekBarChangeListener(this);
}

@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
    intPrgress = minPrgress + i;
    onMinMaxSeekBarChangeListener.onMinMaxSeekProgressChanged(seekBar, intPrgress, b);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    onMinMaxSeekBarChangeListener.onStartTrackingTouch(seekBar);

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    onMinMaxSeekBarChangeListener.onStopTrackingTouch(seekBar);
}

public static interface OnMinMaxSeekBarChangeListener {
    public void onMinMaxSeekProgressChanged(SeekBar seekBar, int i, boolean b);

    public void onStartTrackingTouch(SeekBar seekBar);

    public void onStopTrackingTouch(SeekBar seekBar);
}

public void setOnIntegerSeekBarChangeListener(OnMinMaxSeekBarChangeListener floatListener) {
    this.onMinMaxSeekBarChangeListener = floatListener;
}
}

This class contin method public void setMin(int minPrgress) for setting minimum value of Seek Bar This class contin method public void setMax(int maxPrgress) for setting maximum value of Seek Bar

What is VanillaJS?

This is VanillaJS (unmodified):

// VanillaJS v1.0
// Released into the Public Domain
// Your code goes here:

As you can see, it's not really a framework or a library. It's just a running gag for framework-loving bosses or people who think you NEED to use a JS framework. It means you just use whatever your (for you own sake: non-legacy) browser gives you (using Vanilla JS when working with legacy browsers is a bad idea).

How do I get extra data from intent on Android?

If used in a FragmentActivity, try this:

The first page extends FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

In the fragment, you just need to call getActivity() first,

The second page extends Fragment:

String receive = getActivity().getIntent().getExtras().getString("name");

JUNIT testing void methods

I want to make some unit test to get maximal code coverage

Code coverage should never be the goal of writing unit tests. You should write unit tests to prove that your code is correct, or help you design it better, or help someone else understand what the code is meant to do.

but I dont see how I can test my method checkIfValidElements, it returns nothing or change nothing.

Well you should probably give a few tests, which between them check that all 7 methods are called appropriately - both with an invalid argument and with a valid argument, checking the results of ErrorFile each time.

For example, suppose someone removed the call to:

method4(arg1, arg2);

... or accidentally changed the argument order:

method4(arg2, arg1);

How would you notice those problems? Go from that, and design tests to prove it.

Convert MFC CString to integer

Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

int atoi(
   const char *str 
);
int _wtoi(
   const wchar_t *str 
);
int _atoi_l(
   const char *str,
   _locale_t locale
);
int _wtoi_l(
   const wchar_t *str,
   _locale_t locale
);

CString is wchar_t string. So, if you want convert Cstring to int, you can use:

 CString s;  
int test = _wtoi(s)

GridView sorting: SortDirection always Ascending

It's been awhile since I used a GridView, but I think you need to set the grid's SortDirection property to whatever it currently is before leaving the OnSorting method.

So....

List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection));
grdHeader.SortDirection = e.SortDirection.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
grdHeader.DataSource = items;
grdHeader.DataBind();

open resource with relative path in Java

For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :

ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());

is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.

Android: how to hide ActionBar on certain activities

First cheek MainActivity for activity tag,Like -

public class MainActivity extends AppCompatActivity

Then goto menifest xml file and write-

android:theme="@style/Theme.AppCompat.Light.NoActionBar"

in activity tag

What is the difference between up-casting and down-casting with respect to class variable

Parent: Car
Child: Figo
Car c1 = new Figo();

=====
Upcasting:-
Method: Object c1 will refer to Methods of Class (Figo - Method must be overridden) because class "Figo" is specified with "new".
Instance Variable: Object c1 will refer to instance variable of Declaration Class ("Car").

When Declaration class is parent and object is created of child then implicit casting happens which is "Upcasting".

======
Downcasting:-
Figo f1 = (Figo) c1; //
Method: Object f1 will refer to Method of Class (figo) as initial object c1 is created with class "Figo". but once down casting is done, methods which are only present in class "Figo" can also be referred by variable f1.
Instance Variable: Object f1 will not refer to instance variable of Declaration class of object c1 (declaration class for c1 is CAR) but with down casting it will refer to instance variables of class Figo.

======
Use: When Object is of Child Class and declaration class is Parent and Child class wants to access Instance variable of it's own class and not of parent class then it can be done with "Downcasting".

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

Just add a new form and add buttons and a label. Give the value to be shown and the text of the button, etc. in its constructor, and call it from anywhere you want in the project.

In project -> Add Component -> Windows Form and select a form

Add some label and buttons.

Initialize the value in constructor and call it from anywhere.

public class form1:System.Windows.Forms.Form
{
    public form1()
    {
    }

    public form1(string message,string buttonText1,string buttonText2)
    {
       lblMessage.Text = message;
       button1.Text = buttonText1;
       button2.Text = buttonText2;
    }
}

// Write code for button1 and button2 's click event in order to call 
// from any where in your current project.

// Calling

Form1 frm = new Form1("message to show", "buttontext1", "buttontext2");
frm.ShowDialog();

show distinct column values in pyspark dataframe: python

In addition to the dropDuplicates option there is the method named as we know it in pandas drop_duplicates:

drop_duplicates() is an alias for dropDuplicates().

Example

s_df = sqlContext.createDataFrame([("foo", 1),
                                   ("foo", 1),
                                   ("bar", 2),
                                   ("foo", 3)], ('k', 'v'))
s_df.show()

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|foo|  1|
|bar|  2|
|foo|  3|
+---+---+

Drop by subset

s_df.drop_duplicates(subset = ['k']).show()

+---+---+
|  k|  v|
+---+---+
|bar|  2|
|foo|  1|
+---+---+
s_df.drop_duplicates().show()


+---+---+
|  k|  v|
+---+---+
|bar|  2|
|foo|  3|
|foo|  1|
+---+---+

Java Class that implements Map and keeps insertion order?

LinkedHashMap will return the elements in the order they were inserted into the map when you iterate over the keySet(), entrySet() or values() of the map.

Map<String, String> map = new LinkedHashMap<String, String>();

map.put("id", "1");
map.put("name", "rohan");
map.put("age", "26");

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

This will print the elements in the order they were put into the map:

id = 1
name = rohan 
age = 26 

WCF timeout exception detailed investigation

You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

Thanks for the responses. I think I've solved the problem just now.

Since LD_PRELOAD is for setting some library proloaded, I check the library that ld preloads with LD_PRELOAD, one of which is "liblunar-calendar-preload.so", that is not existing in the path "/usr/lib/liblunar-calendar-preload.so", but I find a similar library "liblunar-calendar-preload-2.0.so", which is a difference version of the former one.

Then I guess maybe liblunar-calendar-preload.so was updated to a 2.0 version when the system updated, leaving LD_PRELOAD remain to be "/usr/lib/liblunar-calendar-preload.so". Thus the preload library name was not updated to the newest version.

To avoid changing environment variable, I create a symbolic link under the path "/usr/lib"

sudo ln -s liblunar-calendar-preload-2.0.so liblunar-calendar-preload.so

Then I restart bash, the error is gone.

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

How do I return a proper success/error message for JQuery .ajax() using PHP?

adding to the top answer: here is some sample code from PHP and Jquery:

$("#button").click(function () {
 $.ajax({
            type: "POST",
            url: "handler.php",
            data: dataString,

                success: function(data) {

                  if(data.status == "success"){

                 /* alert("Thank you for subscribing!");*/

                   $(".title").html("");
                    $(".message").html(data.message)
                    .hide().fadeIn(1000, function() {
                        $(".message").append("");
                        }).delay(1000).fadeOut("fast");

                 /*    setTimeout(function() {
                      window.location.href = "myhome.php";
                    }, 2500);*/


                  }
                  else if(data.status == "error"){
                      alert("Error on query!");
                  }




                    }


        });

        return false;
     }
 });

PHP - send custom message / status:

    $response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!';   /* add custom message */ 
    header('Content-type: application/json');
    echo json_encode($response_array);

Session only cookies with Javascript

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

When to use setAttribute vs .attribute= in JavaScript?

Interesting takeout from Google API script regarding this:

They do it like this:

var scriptElement = document.createElement("script");
scriptElement = setAttribute("src", "https://some.com");
scriptElement = setAttribute("nonce", "https://some.com");
scriptElement.async = "true";

Notice, how they use setAttribute for "src" and "nonce", but then .async = ... for "async" attribute.

I'm not 100% sure, but probably that's because "async" is only supported on browsers that support direct .attr = assignment. So, there's no sense trying to sestAttribute("async") because if browser doesn't understand .async=... - it will not understand "async" attribute.

Hopefully, that's a helpful insight from my ongoing "Un-minify GAPI" research project. Correct me if I'm wrong.

Switch to selected tab by name in Jquery-UI Tabs

try this: "select" / "active" tab

<article id="gtabs">
    <ul>
        <li><a href="#syscfg" id="tab-sys-cfg" class="tabtext">tab One</a></li>
        <li><a href="#ebsconf" id="tab-ebs-trans" class="tabtext">tab Two</a></li>
        <li><a href="#genconfig" id="tab-general-filter-config" class="tabtext">tab Three</a></li>
    </ul>

var index = $('#gtabs a[href="#general-filter-config"]').parent().index();

// `'select' does not support in jquery ui version 1.10.0

$('#gtabs').tabs('select', index);  

alternate solution: use "active":

$('#gtabs').tabs({ active: index });

Deserialize Java 8 LocalDateTime with JacksonMapper

UPDATE:

Change to:

@Column(name = "start_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm", iso = ISO.DATE_TIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime startDate;

JSON request:

{
 "startDate":"2019-04-02 11:45"
}

How do I capitalize first letter of first name and last name in C#?

TextInfo.ToTitleCase() capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include ToLower().

string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"

If CurrentCulture is unavailable, use:

string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());

See the MSDN Link for a detailed description.

Use of #pragma in C

#pragma startup is a directive which is used to call a function before the main function and to call another function after the main function, e.g.

#pragma startup func1
#pragma exit func2

Here, func1 runs before main and func2 runs afterwards.

NOTE: This code works only in Turbo-C compiler. To achieve this functionality in GCC, you can declare func1 and func2 like this:

void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();

resize2fs: Bad magic number in super-block while trying to open

On centos and fedora work with fsadm

fsadm resize /dev/vg_name/root

Fixing a systemd service 203/EXEC failure (no such file or directory)

I think I found the answer:

In the .service file, I needed to add /bin/bash before the path to the script.

For example, for backup.service:

ExecStart=/bin/bash /home/user/.scripts/backup.sh

As opposed to:

ExecStart=/home/user/.scripts/backup.sh

I'm not sure why. Perhaps fish. On the other hand, I have another script running for my email, and the service file seems to run fine without /bin/bash. It does use default.target instead multi-user.target, though.

Most of the tutorials I came across don't prepend /bin/bash, but I then saw this SO answer which had it, and figured it was worth a try.

The service file executes the script, and the timer is listed in systemctl --user list-timers, so hopefully this will work.

Update: I can confirm that everything is working now.

How can I get stock quotes using Google Finance API?

Here is an example that you can use. Havent got Google Finance yet, but Here is the Yahoo Example. You will need the HTMLAgilityPack , Which is awesome. Happy Symbol Hunting.

Call the procedure by using YahooStockRequest(string Symbols);

Where Symbols = a comma-delimited string of symbols, or just one symbol

public string YahooStockRequest(string Symbols,bool UseYahoo=true)
        {
            {
                string StockQuoteUrl = string.Empty;

                try
                {
                    // Use Yahoo finance service to download stock data from Yahoo
                    if (UseYahoo)
                    {
                        string YahooSymbolString = Symbols.Replace(",","+");
                        StockQuoteUrl = @"http://finance.yahoo.com/q?s=" + YahooSymbolString + "&ql=1";
                    }
                    else
                    {
                        //Going to Put Google Finance here when I Figure it out.
                    }

                    // Initialize a new WebRequest.
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(StockQuoteUrl);
                    // Get the response from the Internet resource.
                    HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    // Read the body of the response from the server.

                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    string pageSource;
                    using (StreamReader sr = new StreamReader(webresp.GetResponseStream()))
                    {
                        pageSource = sr.ReadToEnd();
                    }
                    doc.LoadHtml(pageSource.ToString());
                    if (UseYahoo)
                    {
                        string Results=string.Empty;
                        //loop through each Symbol that you provided with a "," delimiter
                        foreach (string SplitSymbol in Symbols.Split(new char[] { ',' }))
                        {
                            Results+=SplitSymbol + " : " + doc.GetElementbyId("yfs_l10_" + SplitSymbol).InnerText + Environment.NewLine;
                        }
                        return (Results);
                    }
                    else
                    {
                        return (doc.GetElementbyId("ref_14135_l").InnerText);
                    }

                }
                catch (WebException Webex)
                {
                    return("SYSTEM ERROR DOWNLOADING SYMBOL: " + Webex.ToString());

                }

            }
        }

Compression/Decompression string with C#

This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:

public static class CompressionExtensions
{
    public static async Task<IEnumerable<byte>> Zip(this object obj)
    {
        byte[] bytes = obj.Serialize();

        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
                await msi.CopyToAsync(gs);

            return mso.ToArray().AsEnumerable();
        }
    }

    public static async Task<object> Unzip(this byte[] bytes)
    {
        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(msi, CompressionMode.Decompress))
            {
                // Sync example:
                //gs.CopyTo(mso);

                // Async way (take care of using async keyword on the method definition)
                await gs.CopyToAsync(mso);
            }

            return mso.ToArray().Deserialize();
        }
    }
}

public static class SerializerExtensions
{
    public static byte[] Serialize<T>(this T objectToWrite)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);

            return stream.GetBuffer();
        }
    }

    public static async Task<T> _Deserialize<T>(this byte[] arr)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            await stream.WriteAsync(arr, 0, arr.Length);
            stream.Position = 0;

            return (T)binaryFormatter.Deserialize(stream);
        }
    }

    public static async Task<object> Deserialize(this byte[] arr)
    {
        object obj = await arr._Deserialize<object>();
        return obj;
    }
}

With this you can serialize everything BinaryFormatter supports, instead only of strings.

Edit:

In case, you need take care of Encoding, you could just use Convert.ToBase64String(byte[])...

Take a look at this answer if you need an example!

Add a auto increment primary key to existing table in oracle

You can use the Oracle Data Modeler to create auto incrementing surrogate keys.

Step 1. - Create a Relational Diagram

You can first create a Logical Diagram and Engineer to create the Relational Diagram or you can straightaway create the Relational Diagram.

Add the entity (table) that required to have auto incremented PK, select the type of the PK as Integer.

Step 2. - Edit PK Column Property

Get the properties of the PK column. You can double click the name of the column or click on the 'Properties' button.

Column Properties dialog box appears.

Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.

Step 3. - Additional Information

Additional information relating to the auto increment can be specified by selecting the 'Auto Increment' tab.

  • Start With
  • Increment By
  • Min Value
  • Max Value
  • Cycle
  • Disable Cache
  • Order
  • Sequence Name
  • Trigger Name
  • Generate Trigger

It is usually a good idea to mention the sequence name, so that it will be useful in PL/SQL.

Click OK (Apply) to the Column Properties dialog box.

Click OK (Apply) to the Table Properties dialog box.

Table appears in the Relational Diagram.

What does -1 mean in numpy reshape?

It is fairly easy to understand. The "-1" stands for "unknown dimension" which can should be infered from another dimension. In this case, if you set your matrix like this:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])

Modify your matrix like this:

b = numpy.reshape(a, -1)

It will call some deafult operations to the matrix a, which will return a 1-d numpy array/martrix.

However, I don't think it is a good idea to use code like this. Why not try:

b = a.reshape(1,-1)

It will give you the same result and it's more clear for readers to understand: Set b as another shape of a. For a, we don't how much columns it should have(set it to -1!), but we want a 1-dimension array(set the first parameter to 1!).

How to resize array in C++?

You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.

#include<algorithm> // for copy

void resize(int*& a, size_t& n)
{
   size_t new_n = 2 * n;
   int* new_a = new int[new_n];
   copy(a, a + n, new_a);
   delete[] a;
   a = new_a;
   n = new_n;
}

For 2D arrays:

#include<algorithm> // for copy

void resize(int**& a, size_t& n)
{
   size_t new_n = 2 * n, i = 0;
   int** new_a = new int* [new_n];
   for (i = 0; i != new_n; ++i)
       new_a[i] = new int[100];
   for (i = 0; i != n; ++i)
   {
       copy(a[i], a[i] + 100, new_a[i]);
       delete[] a[i];
   }
   delete[] a;
   a = new_a;
   n = new_n;
}

Invoking of 1D array:

void myfn(int*& a, size_t& n)
{
   // do smth
   resize(a, n);
}

Invoking of 2D array:

void myfn(int**& a, size_t& n)
{
   // do smth
   resize(a, n);
}
  


   

Remove duplicate values from JS array

var duplicates = function(arr){
     var sorted = arr.sort();
   var dup = [];
   for(var i=0; i<sorted.length; i++){
        var rest  = sorted.slice(i+1); //slice the rest of array
       if(rest.indexOf(sorted[i]) > -1){//do indexOf
            if(dup.indexOf(sorted[i]) == -1)    
         dup.push(sorted[i]);//store it in another arr
      }
   }
   console.log(dup);
}

duplicates(["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]);

Checkout Jenkins Pipeline Git SCM with credentials?

To explicitly checkout using a specific credentials

    stage('Checkout external proj') {
        steps {
            git branch: 'my_specific_branch',
                credentialsId: 'my_cred_id',
                url: 'ssh://[email protected]/proj/test_proj.git'

            sh "ls -lat"
        }
    }

To checkout based on the configred credentials in the current Jenkins Job

    stage('Checkout code') {
        steps {
            checkout scm
        }
    }

You can use both of the stages within a single Jenkins file.

How to use Jackson to deserialise an array of objects

From Eugene Tskhovrebov

List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))

This solution seems to be the best for me.

How to convert answer into two decimal point

Try using the Format function:

Private Sub btncalc_Click(ByVal sender As System.Object,
                          ByVal e As System.EventArgs) Handles btncalc.Click
  txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                     Val(txtF.Text) / Val(txtE.Text), "0.00")
  txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub

How to generate a simple popup using jQuery

First the CSS - tweak this however you like:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.

HTML becomes:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Codeigniter's `where` and `or_where`

You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

Xcode build failure "Undefined symbols for architecture x86_64"

This might help somebody. It took me days to finally figure it out. I am working in OBJ-C and I went to:

Project -> Build Phases -> Compile sources and added the new VC.m file I had just added.

I am working with legacy code and I am usually a swifty, new to OBJ-C so I didn't even think to import my .m files into a sources library.

EDIT:

Ran into this problem a second time and it was something else. This answer saved me after 5 hours of debugging. Tried all of the options on this thread and more. https://stackoverflow.com/a/13625967/7842175 Please give him credit if this helps you, but basically you might need to set your file to its target in file inspector.

This is your file inspector, just make sure all the targets you need are "ticked"

All in all, this is a very vague Error code that could be caused for a lot of reasons, so keep on trying different options.

tsc is not recognized as internal or external command

Me too faced the same problem. Use nodeJS command prompt instead of windows command prompt.

Step 1: Execute the npm install -g typescript

Step 2: tsc filename.ts

New file will be create same name and different extension as ".js"

Step 3: node filename.js

You can see output in screen. It works for me.

List of Timezone IDs for use with FindTimeZoneById() in C#?

DateTime dt;
TimeZoneInfo tzf;
tzf = TimeZoneInfo.FindSystemTimeZoneById("TimeZone String");
dt = TimeZoneInfo.ConvertTime(DateTime.Now, tzf);
lbltime.Text = dt.ToString();

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

how to implement Pagination in reactJs

   Sample pagination react js working code 
    import React, { Component } from 'react';
    import {
    Pagination,
    PaginationItem,
    PaginationLink
    } from "reactstrap";


    let prev  = 0;
    let next  = 0;
    let last  = 0;
    let first = 0;
    export default class SamplePagination extends Component {
       constructor() {
         super();
         this.state = {
           todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','T','v','u','w','x','y','z'],
           currentPage: 1,
           todosPerPage: 3,

         };
         this.handleClick = this.handleClick.bind(this);
         this.handleLastClick = this.handleLastClick.bind(this);
         this.handleFirstClick = this.handleFirstClick.bind(this);
       }

       handleClick(event) {
         event.preventDefault();
         this.setState({
           currentPage: Number(event.target.id)
         });
       }

       handleLastClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:last
         });
       }
       handleFirstClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:1
         });
       }
       render() {
         let { todos, currentPage, todosPerPage } = this.state;

         // Logic for displaying current todos
         let indexOfLastTodo = currentPage * todosPerPage;
         let indexOfFirstTodo = indexOfLastTodo - todosPerPage;
         let currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
          prev  = currentPage > 0 ? (currentPage -1) :0;
          last = Math.ceil(todos.length/todosPerPage);
          next  = (last === currentPage) ?currentPage: currentPage +1;

         // Logic for displaying page numbers
         let pageNumbers = [];
         for (let i = 1; i <=last; i++) {
           pageNumbers.push(i);
         }

          return (
           <div>
             <ul>
              {
                currentTodos.map((todo,index) =>{
                  return <li key={index}>{todo}</li>;
                })
              }
             </ul><ul id="page-numbers">
             <nav>
              <Pagination>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>First</PaginationLink> :
                  <PaginationLink onClick={this.handleFirstClick} id={prev} href={prev}>First</PaginationLink>
              }
              </PaginationItem>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>Prev</PaginationLink> :
                  <PaginationLink onClick={this.handleClick} id={prev} href={prev}>Prev</PaginationLink>
              }
              </PaginationItem>
                 {
                  pageNumbers.map((number,i) =>
                  <Pagination key= {i}>
                  <PaginationItem active = {pageNumbers[currentPage-1] === (number) ? true : false} >
                   <PaginationLink onClick={this.handleClick} href={number} key={number} id={number}>
                   {number}
                   </PaginationLink>
                   </PaginationItem>
                  </Pagination>
                )}

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Next</PaginationLink> :
               <PaginationLink onClick={this.handleClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Next</PaginationLink>
             }
             </PaginationItem>

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Last</PaginationLink> :
               <PaginationLink onClick={this.handleLastClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Last</PaginationLink>
             }
             </PaginationItem>
             </Pagination>
              </nav>
             </ul>
           </div>
         );
       }
     }

     ReactDOM.render(
      <SamplePagination />,
      document.getElementById('root')
    );

Why does Maven have such a bad rep?

Because unsatisfied people do complain while satisfied people don't say they are satisfied. My point is that there are far more satisfied maven users than unsatisfied but the later make more noise. This is a common pattern from real life too actually (ISP, phone carrier, transports, etc, etc).

How to find the unclosed div tag

Taking Milad's suggestion a bit further, you can break your document source down and then do another find, continuing until you find the unmatched culprit.

When you are working with many modules (using a CMS), or don't have access to the W3C tool (because you are working locally), this approach is really helpful.

Deserialize JSON with C#

A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:

http://json2csharp.com/

It will provide you with a starting point to touch up your classes for deserialization.

How to properly URL encode a string in PHP?

Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.

Use case description

Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto link that lets them do that.

PHP code

// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';

// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);

// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;

// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);

// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';

Note: the above assumes you are outputting to a text/html document. If your output media type is text/json then simply use $retval['url'] = $mailToUri; because output encoding is handled by json_encode().

Test case

  1. Run the code on a PHP test site (is there a canonical one I should mention here?)
  2. Click the link
  3. Send the email
  4. Get the email
  5. Click that link

You should see:

"args": {
  "token": "w%a&!e#\"^2(^@azW"
}, 

And of course this is the JSON representation of $token above.

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

iPhone is not available. Please reconnect the device

It is likely that your phone's iOS version is not supported by your Xcode version. You can verify this by "Adding Additional Simulators", tapping the + sign at the bottom left of that dialog, and then selecting "Download more simulator runtimes..." in the OS Version field. Compare the most recent available OS Version to your phone's iOS version (on your phone go to Settings -> General -> About).

Upgrading Xcode fixes this - so long as that doesn't cause any problems for you. If for some reason you need to stay on the same Xcode version but still need to support a newer iOS version, check this article out: https://davidlaristudios.com/2016/11/adding-device-support-to-xcode/

You can actually copy the device support out of a newer Xcode version and paste it into your Xcode version. Note that this requires that you download the new Xcode version separately - don't upgrade your current version. You can download the newer Xcode version directly from Apple.

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

Angular.js programmatically setting a form field to dirty

In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue); does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.

Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.

EDIT:

Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty() from ngModel.NgModelController.

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

Comparing two java.util.Dates to see if they are in the same day

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
                  cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);

Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".

And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).

How do I delete all messages from a single queue using the CLI?

To purge queue you can use following command (more information in API doc):

curl -i -u guest:guest -XDELETE http://localhost:15672/api/queues/vhost_name/queue_name/contents

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Stop Visual Studio from mixing line endings in files

see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017

  1. If it does not exist, add a new file called .editorconfig for your project

  2. manipulate editor config to use your preferred behaviour.

I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig

# http://editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.tmpl.html]
indent_size = 4

[*.scss]
indent_size = 2 

Angular 4 checkbox change value

Give a try on this,

Template

<input (change)="fieldsChange($event)" value="angular" type="checkbox"/>

Ts File

fieldsChange(values:any):void {
  console.log(values.currentTarget.checked);
}

ES6 modules implementation, how to load a json file

Found this thread when I couldn't load a json-file with ES6 TypeScript 2.6. I kept getting this error:

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import suburbs from 'json-loader!./suburbs.json';

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

How can I convert an image into Base64 string using JavaScript?

Try this code:

For a file upload change event, call this function:

$("#fileproof").on('change', function () {
    readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;

    if (files && files[0]) {
        var fr = new FileReader();
        fr.onload = function (e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL(files[0]);
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

Store Base64 data in hidden filed to use.

String in function parameter

function("MyString");

is similar to

char *s = "MyString";
function(s);

"MyString" is in both cases a string literal and in both cases the string is unmodifiable.

function("MyString");

passes the address of a string literal to function as an argument.

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.

get current date and time in groovy?

Date has the time as well, just add HH:mm:ss to the date format:

import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)

In case you are using JRE 8 you can use LoaclDateTime:

import java.time.*

LocalDateTime t = LocalDateTime.now();
return t as String

how to output every line in a file python

Firstly, as @l33tnerd said, f.close should be outside the for loop.

Secondly, you are only calling readline once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:

 if data.find('!masters') != -1:
     f = open('masters.txt')
     for line in f:
           print line,
           sck.send('PRIVMSG ' + chan + " " + line)
     f.close()

Finally, you were referring to the variable lines inside the loop; I assume you meant to refer to line.

Edit: Oh and you need to indent the contents of the if statement.

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

jQuery - Sticky header that shrinks when scrolling down

I took Jezzipin's answer and made it so that if you are scrolled when you refresh the page, the correct size applies. Also removed some stuff that isn't necessarily needed.

function sizer() {
    if($(document).scrollTop() > 0) {
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    } else {
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
    }
}

$(window).scroll(function(){
    sizer();
});

sizer();

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

Where is Maven Installed on Ubuntu

Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.

As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.

For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:

The Apt-get installation will install all the required files in the following folder structure

/usr/bin/mvn

/usr/share/maven2/

/etc/maven2

P.S The Maven configuration is store in /etc/maven2

Note, it's not just apt-get that will do this, it's any .deb package installer.

Laravel csrf token mismatch for ajax POST Request

I always encounter this error recently. Make sure to use a more specific selector when referring to a value. for example instead of $('#firstname') use $('form').find('#firstname');

How to create a DB for MongoDB container on start up?

If you are looking to remove usernames and passwords from your docker-compose.yml you can use Docker Secrets, here is how I have approached it.

version: '3.6'

services:
  db:
    image: mongo:3
    container_name: mycontainer
  secrets:
    - MONGO_INITDB_ROOT_USERNAME
    - MONGO_INITDB_ROOT_PASSWORD
  environment:
    - MONGO_INITDB_ROOT_USERNAME_FILE=/var/run/secrets/MONGO_INITDB_ROOT_USERNAME
    - MONGO_INITDB_ROOT_PASSWORD_FILE=/var/run/secrets/MONGO_INITDB_ROOT_PASSWORD
secrets:
  MONGO_INITDB_ROOT_USERNAME:
    file:  secrets/${NODE_ENV}_mongo_root_username.txt
  MONGO_INITDB_ROOT_PASSWORD:
    file:  secrets/${NODE_ENV}_mongo_root_password.txt

I have use the file: option for my secrets however, you can also use external: and use the secrets in a swarm.

The secrets are available to any script in the container at /var/run/secrets

The Docker documentation has this to say about storing sensitive data...

https://docs.docker.com/engine/swarm/secrets/

You can use secrets to manage any sensitive data which a container needs at runtime but you don’t want to store in the image or in source control, such as:

Usernames and passwords TLS certificates and keys SSH keys Other important data such as the name of a database or internal server Generic strings or binary content (up to 500 kb in size)

Loop through all the resources in a .resx file

Simple read loop use this code

var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}

How to open a new tab using Selenium WebDriver

Handling a browser window using Selenium WebDriver:

String winHandleBefore = driver.getWindowHandle();

for(String winHandle : driver.getWindowHandles())  // Switch to new opened window
{
    driver.switchTo().window(winHandle);
}

driver.switchTo().window(winHandleBefore);   // Move to previously opened window

What's the best CRLF (carriage return, line feed) handling strategy with Git?

These are the two options for Windows and Visual Studio users that share code with Mac or Linux users. For an extended explanation, read the gitattributes manual.

* text=auto

In your repo's .gitattributes file add:

*   text=auto

This will normalize all the files with LF line endings in the repo.

And depending on your operating system (core.eol setting), files in the working tree will be normalized to LF for Unix based systems or CRLF for Windows systems.

This is the configuration that Microsoft .NET repos use.

Example:

Hello\r\nWorld

Will be normalized in the repo always as:

Hello\nWorld

On checkout, the working tree in Windows will be converted to:

Hello\r\nWorld

On checkout, the working tree in Mac will be left as:

Hello\nWorld

Note: If your repo already contains files not normalized, git status will show these files as completely modified the next time you make any change on them, and it could be a pain for other users to merge their changes later. See refreshing a repository after changing line endings for more information.

core.autocrlf = true

If text is unspecified in the .gitattributes file, Git uses the core.autocrlf configuration variable to determine if the file should be converted.

For Windows users, git config --global core.autocrlf true is a great option because:

  • Files are normalized to LF line endings only when added to the repo. If there are files not normalized in the repo, this setting will not touch them.
  • All text files are converted to CRLF line endings in the working directory.

The problem with this approach is that:

  • If you are a Windows user with autocrlf = input, you will see a bunch of files with LF line endings. Not a hazard for the rest of the team, because your commits will still be normalized with LF line endings.
  • If you are a Windows user with core.autocrlf = false, you will see a bunch of files with LF line endings and you may introduce files with CRLF line endings into the repo.
  • Most Mac users use autocrlf = input and may get files with CRLF file endings, probably from Windows users with core.autocrlf = false.

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

Add key value pair to all objects in array

You can do this with map()

_x000D_
_x000D_
var arrOfObj = [{_x000D_
  name: 'eve'_x000D_
}, {_x000D_
  name: 'john'_x000D_
}, {_x000D_
  name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(o) {_x000D_
  o.isActive = true;_x000D_
  return o;_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

If you want to keep original array you can clone objects with Object.assign()

_x000D_
_x000D_
var arrOfObj = [{_x000D_
  name: 'eve'_x000D_
}, {_x000D_
  name: 'john'_x000D_
}, {_x000D_
  name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(el) {_x000D_
  var o = Object.assign({}, el);_x000D_
  o.isActive = true;_x000D_
  return o;_x000D_
})_x000D_
_x000D_
console.log(arrOfObj);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Java : Accessing a class within a package, which is the better way?

They're equivalent. The access is the same.

The import is just a convention to save you from having to type the fully-resolved class name each time. You can write all your Java without using import, as long as you're a fast touch typer.

But there's no difference in efficiency or class loading.

Can Flask have optional URL parameters?

Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class UserAPI(Resource):
    def show(userId, username=None):
    pass

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')

if __name__ == '__main__':
    app.run()

The add_resource method allows pass multiples URLs. Each one will be routed to your Resource.

Call a React component method from outside

You can do like

import React from 'react';

class Header extends React.Component{

    constructor(){
        super();
        window.helloComponent = this;
    }

    alertMessage(){
       console.log("Called from outside");
    }

    render(){

      return (
      <AppBar style={{background:'#000'}}>
        Hello
      </AppBar>
      )
    }
}

export default Header;

Now from outside of this component you can called like this below

window.helloComponent.alertMessage();

Run MySQLDump without Locking Tables

To dump large tables, you should combine the --single-transaction option with --quick.

http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction

Chrome hangs after certain amount of data transfered - waiting for available socket

simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...

if you use jplayer then replace preload:"metadata" to preload:"none" from jplayer JS file ...

preload:"metadata" is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

How can I Remove .DS_Store files from a Git repository?

Open terminal and type "cd < ProjectPath >"

  1. Remove existing files: find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

  2. nano .gitignore

  3. Add this .DS_Store

  4. type "ctrl + x"

  5. Type "y"

  6. Enter to save file

  7. git add .gitignore

  8. git commit -m '.DS_Store removed.'

Setting the zoom level for a MKMapView

A simple Swift implementation, if you use outlets.

@IBOutlet weak var mapView: MKMapView! {
    didSet {
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 500, 500)
        self.mapView.setRegion(viewRegion, animated: false)
    }
}

Based on @Carnal's answer.

Add params to given URL in Python

In python 2.5

import cgi
import urllib
import urlparse

def add_url_param(url, **params):
    n=3
    parts = list(urlparse.urlsplit(url))
    d = dict(cgi.parse_qsl(parts[n])) # use cgi.parse_qs for list values
    d.update(params)
    parts[n]=urllib.urlencode(d)
    return urlparse.urlunsplit(parts)

url = "http://stackoverflow.com/search?q=question"
add_url_param(url, lang='en') == "http://stackoverflow.com/search?q=question&lang=en"

Check if input value is empty and display an alert

Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

extract the date part from DateTime in C#

you can use a formatstring

DateTime time = DateTime.Now;              
String format = "MMM ddd d HH:mm yyyy";     
Console.WriteLine(time.ToString(format));

jQuery: how do I animate a div rotation?

As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.

JSFiddle demo


HTML

<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>

CSS3

img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}

.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}

jQuery

$(document).ready(function() {
    $("img").mouseenter(function() {
        $(this).addClass("rotate");
    });
    $("img").mouseleave(function() {
        $(this).removeClass("rotate");
    });
});

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Resize a picture to fit a JLabel

The best and easy way for image resize using Java Swing is:

jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));

For better display, identify the actual height & width of image and resize based on width/height percentage

The name does not exist in the namespace error in XAML

Another possible cause: A post-build event is removing the project DLL from the build folder.

To clarify: WPF designer may report "The name XXX does not exist in the namespace...", even when the name does exist in the namespace and the project builds and runs just fine if a post-build event removes the project DLL from the build folder (bin\Debug, bin\Release, etc.). I have personal experience with this in Visual Studio 2015.

How to have Android Service communicate with Activity

There are three obvious ways to communicate with services:

  1. Using Intents
  2. Using AIDL
  3. Using the service object itself (as singleton)

In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():

void onCreate(Intent i) {
  sInstance = this;
}

Make a static function MyService getInstance(), which returns the static sInstance.

Then in Activity.onCreate() you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread().

The last thing you need to do is to remove the reference to you listener object in Activity.onPause(), otherwise an instance of your activity context will leak, not good.

NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.

Filter Extensions in HTML form upload

The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.

Additionally, it appears that most browsers may not honor this attribute.

The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.

Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

Python return statement error " 'return' outside function"

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

What is the difference between & vs @ and = in angularJS

@: one-way binding

=: two-way binding

&: function binding

Javascript isnull

return (results||0) && results[1] || 0;

The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

PHP cURL not working - WAMP on Windows 7 64 bit

uncomment "curl=cainfo" in the php.ini document This helped me when installing Prestashop when all other methods still did not work.

How do I run a PowerShell script when the computer starts?

You could create a Scheduler Task that runs automatically on the start, even when the user is not logged in:

schtasks /create /tn "FileMonitor" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file C:\Doc\Files\FileMonitor.ps1"

Run this command once from a PowerShell as Admin and it will create a schedule task for you. You can list the task like this:

schtasks /Query /TN "FileMonitor" /V /FO List

or delete it

schtasks /Delete /TN "FileMonitor"

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

CSS: fixed position on x-axis but not y?

Starx's solution was extremely helpful to me. But I had some problems when I tried to implement a vertical scrolling sidebar with it. Here was my initial code, based on what Starx wrote:

function fix_vertical_scroll(id) {
    $(window).scroll(function(){
        $(id).css({
            'top': $(this).scrollTop() //Use it later
        });
    });
}

It's slightly different from Starx's solution, because I think his code is designed to allow a menu to float horizontally instead of vertically. But that's just an aside. The problem I had with the above code is that in a lot of browsers, or depending on the resource load of the computer, the menu movements would be choppy, whereas the initial css solution was nice and smooth. I attribute this to browsers being slower at firing javascript events than at implementing css.

My alternate solution to this choppiness problem is set the frame to fixed instead of absolute, then cancel out the horizontal movements using starx's method.

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

#leftframe {
 position:fixed;
 width: 200;
}   

You might say all I'm doing is trading vertical scrolling choppiness for horizontal scrolling choppiness. But the thing is, 99% of scrolling is vertical, and it's much more annoying when that is choppy than when horizontal scrolling is.

Here's my related post on this matter, if I haven't already exhausted everyone's patience: Fixing a menu in one direction in jquery

Mongoose: Find, modify, save

findOne, modify fields & save

User.findOne({username: oldUsername})
  .then(user => {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.markModified('username');
    user.markModified('password');
    user.markModified('rights');

    user.save(err => console.log(err));
});

OR findOneAndUpdate

User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }
    console.log(doc);
});

Also see updateOne

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

Git push error: "origin does not appear to be a git repository"

When you create a repository in bitbucket.org, it gives you instructions on how to set up your local directory. Chances are, you just forgot to run the code:

git remote add origin https://[email protected]/username/reponame.git

How to convert string to XML using C#

Use LoadXml Method of XmlDocument;

string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);

Get an image extension from an uploaded file in Laravel

Tested in laravel 5.5

$extension = $request->file('file')->extension();

Display Back Arrow on Toolbar

MyActivity extends AppCompatActivity {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(arrow -> onBackPressed());
    }

javascript window.location in new tab

This works for me on Chrome 53. Haven't tested anywhere else:

function navigate(href, newTab) {
   var a = document.createElement('a');
   a.href = href;
   if (newTab) {
      a.setAttribute('target', '_blank');
   }
   a.click();
}

How do I execute multiple SQL Statements in Access' Query Editor?

create a macro like this

Option Compare Database

Sub a()

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

End Sub

using extern template (C++11)

If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.

Pretty printing XML in Python

from lxml import etree
import xml.dom.minidom as mmd

xml_root = etree.parse(xml_fiel_path, etree.XMLParser())

def print_xml(xml_root):
    plain_xml = etree.tostring(xml_root).decode('utf-8')
    urgly_xml = ''.join(plain_xml .split())
    good_xml = mmd.parseString(urgly_xml)
    print(good_xml.toprettyxml(indent='    ',))

It's working well for the xml with Chinese!

Configuring Git over SSH to login once

This is about configuring ssh, not git. If you haven't already, you should use ssh-keygen (with a blank passphrase) to create a key pair. Then, you copy the public key to the remote destination with ssh-copy-id. Unless you have need of multiple keys (e.g. a more secure one with a passphrase for other purposes) or you have some really weird multiple-identity stuff going on, it's this simple:

ssh-keygen   # enter a few times to accept defaults
ssh-copy-id -i ~/.ssh/id_rsa user@host

Edit: You should really just read DigitalRoss's answer, but: if you use keys with passphrases, you'll need to use ssh-add <key-file> to add them to ssh-agent (and obviously start up an ssh-agent if your distribution doesn't already have one running for you).