Programs & Examples On #Short

A short integer is an integer number which may take less storage, while having a smaller range, than a standard integer on the same machine.

Primitive type 'short' - casting in Java

What language are you using?

Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

Java's L number (long) specification

To understand why it is necessary to distinguish between int and long literals, consider:

long l = -1 >>> 1;

versus

int a = -1;
long l = a >>> 1;

Now as you would rightly expect, both code fragments give the same value to variable l. Without being able to distinguish int and long literals, what is the interpretation of -1 >>> 1?

-1L >>> 1 // ?

or

(int)-1 >>> 1 // ?

So even if the number is in the common range, we need to specify type. If the default changed with magnitude of the literal, then there would be a weird change in the interpretations of expressions just from changing the digits.

This does not occur for byte, short and char because they are always promoted before performing arithmetic and bitwise operations. Arguably their should be integer type suffixes for use in, say, array initialisation expressions, but there isn't. float uses suffix f and double d. Other literals have unambiguous types, with there being a special type for null.

Cannot implicitly convert type 'int' to 'short'

The result of summing two Int16 variables is an Int32:

Int16 i1 = 1;
Int16 i2 = 2;
var result = i1 + i2;
Console.WriteLine(result.GetType().Name);

It outputs Int32.

Difference between an API and SDK

API is like the building blocks of some puzzling game that a child plays with to join blocks in different shapes and build something they can think of.

SDK, on the other hand, is a proper workshop where all of the development tools are available, rather than pre-shaped building blocks. In a workshop you have the actual tools and you are not limited to blocks, and can therefore make your own blocks, or can create something without any blocks to begin with.

coding without an SDK or API is like making everything from scratch without a workshop - you have to even make your own tools

Internal vs. Private Access Modifiers

internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)

private is for class scope (i.e. accessible only from code in the same class).

Saving an image in OpenCV

I know the problem! You just put a dot after "test.jpg"!

cvSaveImage("test.jpg". ,pSaveImg);

I may be wrong but I think its not good!

Create a new TextView programmatically then display it below another TextView

public View recentView;

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

        //Create a relative layout and add a button
        relativeLayout = new RelativeLayout(this);
        btn = new Button(this);
        btn.setId((int)System.currentTimeMillis());
        recentView = btn;
        btn.setText("Click me");
        relativeLayout.addView(btn);


        setContentView(relativeLayout);

        btn.setOnClickListener(new View.OnClickListener() {

            @Overr ide
            public void onClick(View view) {

                //Create a textView, set a random ID and position it below the most recently added view
                textView = new TextView(ActivityName.this);
                textView.setId((int)System.currentTimeMillis());
                layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
                textView.setText("Time: "+System.currentTimeMillis());
                relativeLayout.addView(textView, layoutParams);
                recentView = textView;
            }
        });
    }

This can be modified to display each element of a String array in different TextViews.

Responsive Bootstrap Jumbotron Background Image

I found that this worked perfectly for me:

.jumbotron {
background-image: url(/img/Jumbotron.jpg);
background-size: cover;
height: 100%;}

You can resize your screen and it will always take up 100% of the window.

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

How do I associate file types with an iPhone application?

BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.

We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.

Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):

In app did load at top, just do this...

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, 
                                                                   (CFStringRef)@"icz", 
                                                                   NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.

But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.

$ curl -D headers THEURLGOESHERE > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 27393  100 27393    0     0  24983      0  0:00:01  0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive

The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
                                                                   (CFStringRef)@"text/calendar", 
                                                                   NULL);

CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.

So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

How do I make Java register a string input with spaces?

Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.

Class Scanner

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;

System.out.println("Please input question:");
question = in.next();

// TODO do something with your input such as removing spaces...

if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
else
    System.out.println("Que?");

Chrome desktop notification example

<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

define a List like List<int,string>?

You could use an immutable struct

public struct Data
{
    public Data(int intValue, string strValue)
    {
        IntegerData = intValue;
        StringData = strValue;
    }

    public int IntegerData { get; private set; }
    public string StringData { get; private set; }
}

var list = new List<Data>();

Or a KeyValuePair<int, string>

using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));

How to add a string to a string[] array? There's no .Add function

This is how I add to a string when needed:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

Kill Attached Screen in Linux

None of the screen commands were killing or reattaching the screen for me. Any screen command would just hang. I found another approach.

Each running screen has a file associated with it in:

/var/run/screen/S-{user_name}

The files in that folder will match the names of the screens when running the screen -list. If you delete the file, it kills the associated running screen (detached or attached).

Updating a JSON object using Javascript

simply iterate over the list then check the properties of each object.

for (var i = 0; i < jsonObj.length; ++i) {
    if (jsonObj[i]['Id'] === '3') {
        jsonObj[i]['Username'] = 'Thomas';
    }
}

Windows batch files: .bat vs .cmd?

Still, on Windows 7, BAT files have also this difference : If you ever create files TEST.BAT and TEST.CMD in the same directory, and you run TEST in that directory, it'll run the BAT file.

C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

C:\Temp>echo echo bat > test.bat

C:\Temp>echo echo cmd > test.cmd

C:\Temp>test

C:\Temp>echo bat
bat

C:\Temp>

Android Text over image

You could possibly

  • make a new class inherited from the Class ImageView and
  • override the Method onDraw. Call super.onDraw() in that method first and
  • then draw some Text you want to display.

if you do it that way, you can use this as a single Layout Component which makes it easier to layout together with other components.

Converting a String array into an int Array in java

Another short way:

int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();

Put byte array to JSON and vice versa

In line with @Qwertie's suggestion, but going further on the lazy side, you could just pretend that each byte is a ISO-8859-1 character. For the uninitiated, ISO-8859-1 is a single-byte encoding that matches the first 256 code points of Unicode.

So @Ash's answer is actually redeemable with a charset:

byte[] args2 = getByteArry();
String byteStr = new String(args2, Charset.forName("ISO-8859-1"));

This encoding has the same readability as BAIS, with the advantage that it is processed faster than either BAIS or base64 as less branching is required. It might look like the JSON parser is doing a bit more, but it's fine because dealing with non-ASCII by escaping or by UTF-8 is part of a JSON parser's job anyways. It could map better to some formats like MessagePack with a profile.

Space-wise however, it is usually a loss, as nobody would be using UTF-16 for JSON. With UTF-8 each non-ASCII byte would occupy 2 bytes, while BAIS uses (2+4n + r?(r+1):0) bytes for every run of 3n+r such bytes (r is the remainder).

Move seaborn plot legend to a different position?

This is how I was able to move the legend to a particular place inside the plot and change the aspect and size of the plot:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")

figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend=False)

viol_plot.ax.legend(loc=2)
viol_plot.fig.savefig(figure_output_path)  

Legend location changed

This worked for me to change the size and aspect of the plot as well as move the legend outside the plot area.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")


figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend_out=True)

viol_plot.fig.savefig(figure_output_path)  

violin plot with changed size, aspect and legend located outside

I figured this out from mwaskom's answer here and Fernando Hernandez's answer here.

How to copy to clipboard in Vim?

for OSX, like the 10342 answers above made clear, you need to make sure that vim supports the clipboard feature, said the the one that comes pre-shipped with OSX does NOT support clipboard, and that if you run brew install vim it would work.

Except that running vi will still make you run the preshipped OSX version, not the one you installed from brew.

to get over this, I simply aliased my vim command to the brew version, not the OSX default one:

alias vim="/usr/local/Cellar/vim/8.0.1100_1/bin/vim"

and now i'm golden

Clear Cache in Android Application programmatically

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

Disable Input fields in reactive form

If to use disabled form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!

(And if you are using on submit button like [disabled]="!form.valid"it will exclude your field from validation)

enter image description here

converting a base 64 string to an image and saving it

I would suggest via Bitmap:

public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

Is there Unicode glyph Symbol to represent "Search"

Use the ? symbol (encoded as &#9906; or &#x26B2;), and rotate it to achieve the desired effect:

<div style="-webkit-transform: rotate(45deg); 
               -moz-transform: rotate(45deg); 
                 -o-transform: rotate(45deg);
                    transform: rotate(45deg);">
    &#9906;
</div>

It rotates a symbol :)

Can I embed a custom font in an iPhone application?

Yes, you can include custom fonts. Refer to the documentation on UIFont, specifically, the fontWithName:size: method.

1) Make sure you include the font in your resources folder.

2) The "name" of the font is not necessarily the filename.

3) Make sure you have the legal right to use that font. By including it in your app, you're also distributing it, and you need to have the right to do that.

cancelling a handler.postdelayed process

In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use

handler.removeCallbacksAndMessages(null);

As per documentation,

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Character reading from file in Python

But it really is "I don\u2018t like this" and not "I don't like this". The character u'\u2018' is a completely different character than "'" (and, visually, should correspond more to '`').

If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.

punctuation = {
  u'\u2018': "'",
  u'\u2019': "'",
}
for src, dest in punctuation.iteritems():
  text = text.replace(src, dest)

There are an awful lot of punctuation characters in unicode, however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

The defaultSelected attribute is not settable, it's just for informational purposes:

Quote:

The defaultSelected property returns the default value of the selected attribute.
This property returns true if an option is selected by default, otherwise it returns false.

I think you want:

$('option[value=valueToSelect]', newOption).attr('selected', 'selected');

I.e. set the selected attribute of the option you want to select.


Without trying to fix your code, here's roughly how I would do it:

function buildSelect(options, default) {
    // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
    //        default = 'value1'

    var $select = $('<select></select>');
    var $option;

    for (var val in options) {
        $option = $('<option value="' + val + '">' + options[val] + '</option>');
        if (val == default) {
            $option.attr('selected', 'selected');
        }
        $select.append($option);
    }

    return $select;
}

You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

How do I print the type or class of a variable in Swift?

Swift 3.0

let string = "Hello"
let stringArray = ["one", "two"]
let dictionary = ["key": 2]

print(type(of: string)) // "String"

// Get type name as a string
String(describing: type(of: string)) // "String"
String(describing: type(of: stringArray)) // "Array<String>"
String(describing: type(of: dictionary)) // "Dictionary<String, Int>"

// Get full type as a string
String(reflecting: type(of: string)) // "Swift.String"
String(reflecting: type(of: stringArray)) // "Swift.Array<Swift.String>"
String(reflecting: type(of: dictionary)) // "Swift.Dictionary<Swift.String, Swift.Int>"

How to add line breaks to an HTML textarea?

here is the thing i did for the same trouble i had.

when I'm passing the text to the next page in jsp, i'm reading it as a textarea instead of reading something like

so the output came as you wanted. and for other properties, you can use as below.

<textarea style="background-color: white; border: none; width:660px;font-family: Arial, Helvetica, sans-serif; font-size:1.0em; resize:none;" name="text" cols="75" rows="15" readonly="readonly" ><s:property value="%{text}"/></textarea>

How to get current date in jquery?

In JavaScript you can get the current date and time using the Date object;

var now = new Date();

This will get the local client machine time

Example for jquery LINK

If you are using jQuery DatePicker you can apply it on any textfield like this:

$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

How do I log a Python error with debug information?

You can log the stack trace without an exception.

https://docs.python.org/3/library/logging.html#logging.Logger.debug

The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.

Example:

>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.getLogger().info('This prints the stack', stack_info=True)
INFO:root:This prints the stack
Stack (most recent call last):
  File "<stdin>", line 1, in <module>
>>>

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.

Removing duplicate elements from an array in Swift

You can convert to a Set and back to an Array again quite easily:

let unique = Array(Set(originals))

This is not guaranteed to maintain the original order of the array.

Safely override C++ virtual functions

In MSVC++ you can use keyword override

class child : public parent {
public:
  virtual void handle_event(int something) <b>override</b> {
    // new exciting code
  }
};

override works both for native and CLR code in MSVC++.

How to fully delete a git repository created with init?

If you really want to remove all of the repository, leaving only the working directory then it should be as simple as this.

rm -rf .git

The usual provisos about rm -rf apply. Make sure you have an up to date backup and are absolutely sure that you're in the right place before running the command. etc., etc.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

This error is also related with a cache issue.

I had the same problem and it was solved just cleaning and building the solution again.

C++ equivalent of java's instanceof

Try using:

if(NewType* v = dynamic_cast<NewType*>(old)) {
   // old was safely casted to NewType
   v->doSomething();
}

This requires your compiler to have rtti support enabled.

EDIT: I've had some good comments on this answer!

Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

if(old->getType() == BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

How to deal with ModalDialog using selenium webdriver?

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

First, Start MongoDB:

sudo service mongod start

Then, Run:

mongo

HTML Submit-button: Different value / button-text?

If you handle "adding tag" via JScript:

<form ...>
<button onclick="...">any text you want</button>
</form>

Or above if handle via page reload

Creating Dynamic button with click event in JavaScript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");

    btn.setAttribute("style","color:red;font-size:23px");

    btn.appendChild(t);
    document.body.appendChild(btn);

    btn.setAttribute("onclick", alert("clicked"));

}
</script>

</body>
</html>

How to change progress bar's progress color in Android

For a horizontal ProgressBar, you can use a ColorFilter, too, like this:

progressBar.getProgressDrawable().setColorFilter(
    Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);

Red ProgressBar using color filter

Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:

Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);

If progressBar is indeterminate then use getIndeterminateDrawable() instead of getProgressDrawable().

Since Lollipop (API 21) you can set a progress tint:

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

Red ProgressBar using progress tint

Redirecting to authentication dialog - "An error occurred. Please try again later"

I had this exact problem on a Page Tab app and for the life of me couldn't work out what the problem was. It worked on my test page but as soon as I made it live it wouldn't work. I found in the end that I fixed the problem by putting the actual URL to the Page Tab (i.e. http://www.facebook.com/<"page_name">/app_<"app_id">) into "Site URL" under "Website". This doesn't make any sense. But it worked :-)

How to import a SQL Server .bak file into MySQL?

MySql have an application to import db from microsoft sql. Steps:

  1. Open MySql Workbench
  2. Click on "Database Migration" (if it do not appear you have to install it from MySql update)
  3. Follow the Migration Task List using the simple Wizard.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

@Html.Partial and @Html.RenderPartial are used when your Partial view model is correspondence of parent model, we don't need to create any action method to call this.

@Html.Action and @Html.RenderAction are used when your partial view model are independent from parent model, basically it is used when you want to display any widget type content on page. You must create an action method which returns a partial view result while calling the method from view.

Run an exe from C# code

Example:

System.Diagnostics.Process.Start("mspaint.exe");

Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Depending on what you actually want to achieve, you should take a look at Android Handlers:

http://developer.android.com/reference/android/os/Handler.html

If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).

Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

Insert if not exists Oracle

INSERT INTO schema.myFoo ( primary_key        , value1          , value2         )
                         SELECT 'bar1' AS primary_key ,'baz1' AS value1 ,'bat1' AS value2 FROM DUAL WHERE (SELECT 1 AS value FROM schema.myFoo WHERE LOWER(primary_key) ='bar1' AND ROWNUM=1) is null;

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

Call asynchronous method in constructor?

Don't ever call .Wait() or .Result as this is going to lock your app. Don't spin up a new Task either, just call the ContinueWith

public class myClass
{
  public myClass
  {
    GetMessageAsync.ContinueWith(GetResultAsync);
  }

  async Task<string> GetMessageAsync()
  {
    return await Service.GetMessageFromAPI(); 
  }
private async Task GetResultAsync(Task<string> resultTask)
{
    if (resultTask.IsFaulted)
{
      Log(resultTask.Exception); 
}
eles
{
 //do what ever you need from the result
}
}
}

https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern

How can I change cols of textarea in twitter-bootstrap?

UPDATE: As of Bootstrap 3.0, the input-* classes described below for setting the width of input elements were removed. Instead use the col-* classes to set the width of input elements. Examples are provided in the documentation.


In Bootstrap 2.3, you'd use the input classes for setting the width.

<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?

Do a find for "Control sizing" for examples in the documentation.

But for height I think you'd still use the rows attribute.

How to create a responsive image that also scales up in Bootstrap 3

Sure things!

.img-responsive is the right way to make images responsive with bootstrap 3 You can add some height rule for the picture you want to make responsive, because with responsibility, width changes along the height, fix it and there you are.

How to run multiple SQL commands in a single SQL connection?

Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection

public static class SQLTest
    {
        public static void NpgsqlCommand()
        {
            using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
            {
                NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
                NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
                command1.Connection.Open();
                command1.ExecuteNonQuery();
                command2.ExecuteNonQuery();
                command2.Connection.Close();
            }
        }
    }

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'number') {
   //whatever
}

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

The type of an array is still object. Here you really need the instanceof operator.

Update:

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".

See Java GC FAQ, question 22 for more information.

Note that there are some known bugs with UseParNewGC

Retrieving Data from SQL Using pyodbc

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=db-server;'
                  'Database=db;'
                  'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
    print(r)

Storing WPF Image Resources

The following worked and the images to be set is resources in properties:

    var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
                                      IntPtr.Zero,
                                      Int32Rect.Empty,
                                      BitmapSizeOptions.FromEmptyOptions());
    MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;

Understanding "VOLUME" instruction in DockerFile

I don't consider the use of VOLUME good in any case, except if you are creating an image for yourself and no one else is going to use it.

I was impacted negatively due to VOLUME exposed in base images that I extended and only came up to know about the problem after the image was already running, like wordpress that declares the /var/www/html folder as a VOLUME, and this meant that any files added or changed during the build stage aren't considered, and live changes persist, even if you don't know. There is an ugly workaround to define web directory in another place, but this is just a bad solution to a much simpler one: just remove the VOLUME directive.

You can achieve the intent of volume easily using the -v option, this not only make it clear what will be the volumes of the container (without having to take a look at the Dockerfile and parent Dockerfiles), but this also gives the consumer the option to use the volume or not.

It's also bad to use VOLUMES due to the following reasons, as said by this answer:

However, the VOLUME instruction does come at a cost.

  • Users might not be aware of the unnamed volumes being created, and continuing to take up storage space on their Docker host after containers are removed.
  • There is no way to remove a volume declared in a Dockerfile. Downstream images cannot add data to paths where volumes exist.

The latter issue results in problems like these.

Having the option to undeclare a volume would help, but only if you know the volumes defined in the dockerfile that generated the image (and the parent dockerfiles!). Furthermore, a VOLUME could be added in newer versions of a Dockerfile and break things unexpectedly for the consumers of the image.

Another good explanation (about the oracle image having VOLUME, which was removed): https://github.com/oracle/docker-images/issues/640#issuecomment-412647328

More cases in which VOLUME broke stuff for people:

A pull request to add options to reset properties the parent image (including VOLUME), was closed and is being discussed here (and you can see several cases of people affected adversely due to volumes defined in dockerfiles), which has a comment with a good explanation against VOLUME:

Using VOLUME in the Dockerfile is worthless. If a user needs persistence, they will be sure to provide a volume mapping when running the specified container. It was very hard to track down that my issue of not being able to set a directory's ownership (/var/lib/influxdb) was due to the VOLUME declaration in InfluxDB's Dockerfile. Without an UNVOLUME type of option, or getting rid of it altogether, I am unable to change anything related to the specified folder. This is less than ideal, especially when you are security-aware and desire to specify a certain UID the image should be ran as, in order to avoid a random user, with more permissions than necessary, running software on your host.

The only good thing I can see about VOLUME is about documentation, and I would consider it good if it only did that (without any side effects).

TL;DR

I consider that the best use of VOLUME is to be deprecated.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

In my case:-

  • What went wrong: Execution failed for task ':app:multiDexListDebug'.

Answer:-

I just deleted the react-native-firebase folder which will be inside the node_modules folder, that's it then I could run the app successfully.

And one more thing don't forget to remove react-native-firebase but not @react-native-firebase in package.json file. So that next time when you run npm I or yarn. This won't get installed in your app.

This package was causing the issue.

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

What is the Auto-Alignment Shortcut Key in Eclipse?

auto-alignment shortcut key Ctrl+Shift+F

to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions

How to convert Blob to File in JavaScript

I have used FileSaver.js to save the blob as file.

This is the repo : https://github.com/eligrey/FileSaver.js/

Usage:

import { saveAs } from 'file-saver';

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

saveAs("https://httpbin.org/image", "image.jpg");

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

How do I get into a non-password protected Java keystore or change the password?

which means that cacerts keystore isn't password protected

That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

In order to verify its integrity, you must provide your keystore password.

Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

MAMP mysql server won't start. No mysql processes are running

This is what worked for me (Windows 10) :

  1. Click on Start Servers in MAMP
  2. Manually click on mysql.exe in MAMP installation folder (C:\MAMP\bin\mysql\bin\mysql.exe)

Tip : You can pin mysql.exe to Start Menu so you don't always have to search for this folder

How to link html pages in same or different folders?

If you'd like to link to the root directory you can use

/, or /index.html

If you'd like to link to a file in the same directory, simply put the file name

<a href="/employees.html">Employees Click Here</a>

To move back a folder, you can use

../

To link to the index page in the employees directory from the root directory, you'd do this

<a href="../employees/index.html">Employees Directory Index Page</a>

Best way to store a key=>value array in JavaScript?

In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?

Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

Simple Array eg.

$(document).ready(function(){

    var countries = ['Canada','Us','France','Italy'];
    console.log('I am from '+countries[0]);
    $.each(countries, function(key, value) {
        console.log(key, value);
    });

});

Output -

0 "Canada"

1 "Us"

2 "France"

3 "Italy"

We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.

Simple Object (json)

$(document).ready(function(){

    var person = {
        name: "James",
        occupation: "programmer",
        height: {
            feet: 6,
            inches: 1
        },
    }

    console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);

    $.each(person, function(key, value) {
        console.log(key, value);
    });

});

Output -

My name is James and I am a 6 ft 1 programmer

name James

occupation programmer

height Object {feet: 6, inches: 1}

In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.

Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -

JSON array (array of objects) -

$(document).ready(function(){

    var people = [
        {
            name: "James",
            occupation: "programmer",
            height: {
                feet: 6,
                inches: 1
            }
        }, {
            name: "Peter",
            occupation: "designer",
            height: {
                feet: 4,
                inches: 10
            }
        }, {
            name: "Joshua",
            occupation: "CEO",
            height: {
                feet: 5,
                inches: 11
            }
        }
    ];

    console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");

    $.each(people, function(key, person) {
        console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
    });

});

Output -

My name is Joshua and I am a 5 ft 11 CEO

My name is James and I am a 6 ft 1 programmer

My name is Peter and I am a 4 ft 10 designer

My name is Joshua and I am a 5 ft 11 CEO

Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.

'\r': command not found - .bashrc / .bash_profile

If you are using a recent Cygwin (e.g. 1.7), you can also start both your .bashrc and .bash_profile with the following line, on the first non commented line:

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
(set -o igncr) 2>/dev/null && set -o igncr; # this comment is needed

This will force bash to ignore carriage return (\r) characters used in Windows line separators.

See http://cygwin.com/ml/cygwin-announce/2010-08/msg00015.html.

How can I alter a primary key constraint using SQL syntax?

you can rename constraint objects using sp_rename (as described in this answer)

for example:

EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint'

How to trim a string to N chars in Javascript?

I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

How to align two elements on the same line without changing HTML

Change your css as below

#element1 {float:left;margin-right:10px;} 
#element2 {float:left;} 

Here is the JSFiddle http://jsfiddle.net/a4aME/

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;

Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

TextBox1.CssClass = "highlight";

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

How to get cookie expiration date / creation date from javascript?

you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

Circular gradient in android

I always find images helpful when learning a new concept, so this is a supplemental answer.

enter image description here

The %p means a percentage of the parent, that is, a percentage of the narrowest dimension of whatever view we set our drawable on. The images above were generated by changing the gradientRadius in this code

my_gradient_drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="10%p"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

Which can be set on a view's background attribute like this

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

Center

You can change the center of the radius with

android:centerX="0.2"
android:centerY="0.7"

where the decimals are fractions of the width and height for x and y respectively.

enter image description here

Documentation

Here are some notes from the documentation explaining things a little more.

android:gradientRadius

Radius of the gradient, used only with radial gradient. May be an explicit dimension or a fractional value relative to the shape's minimum dimension.

May be a floating point value, such as "1.2".

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.

Clear terminal in Python

For Windows, on the interpreter command line only (not the GUI)! Simply type: (Remember to use proper indentation with python):

import os
def clear():
    os.system('cls')

Every time you type clear() on the shell (command line), it will clear the screen on your shell. If you exit the shell, then you must redo the above to do it again as you open a new Python (command line) shell.

Note: Does not matter what version of Python you are using, explicitly (2.5, 2.7, 3.3 & 3.4).

Is Constructor Overriding Possible?

What you describe isn't overriding. If you don't specify a default constructor, the compiler will create a default constructor. If it's a subclass, it will call the default parent constructor(super()), it will also initialize all instance variables to a default value determined by the type's default value(0 for numeric types, false for booleans, or null for objects).

Overriding happens when a subclass has the same name, number/type of parameters, and the same return type as an instance method of the superclass. In this case, the subclass will override the superclass's method. Information on overriding here.

What is the difference between Python and IPython?

ipython is an interactive shell built with python.

From the project website:

IPython provides a rich toolkit to help you make the most out of using Python, with:

  • Powerful Python shells (terminal and Qt-based).
  • A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media.
  • Support for interactive data visualization and use of GUI toolkits.
  • Flexible, embeddable interpreters to load into your own projects.
  • Easy to use, high performance tools for parallel computing.

Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features.

I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

This could be because of proxy or firewall. If it's proxy, then you need to specify proxy setting at entry point of your code or project.

import os #for proxy

proxy = 'http://10.XX.XX.XX:8X8X' #your own proxy 'http://<user>:<pass>@<proxy>:<port>'

os.environ['http_proxy'] = proxy 
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy
#rest of code .....

converting multiple columns from character to numeric format in r

If you're already using the tidyverse, there are a few solution depending on the exact situation.

Basic if you know it's all numbers and doesn't have NAs

library(dplyr)

# solution
dataset %>% mutate_if(is.character,as.numeric)

Test cases

df <- data.frame(
  x1 = c('1','2','3'),
  x2 = c('4','5','6'),
  x3 = c('1','a','x'), # vector with alpha characters
  x4 = c('1',NA,'6'), # numeric and NA
  x5 = c('1',NA,'x'), # alpha and NA
  stringsAsFactors = F)

# display starting structure
df %>% str()

Convert all character vectors to numeric (could fail if not numeric)

df %>%
  select(-x3) %>% # this removes the alpha column if all your character columns need converted to numeric
  mutate_if(is.character,as.numeric) %>%
  str()

Check if each column can be converted. This can be an anonymous function. It returns FALSE if there is a non-numeric or non-NA character somewhere. It also checks if it's a character vector to ignore factors. na.omit removes original NAs before creating "bad" NAs.

is_all_numeric <- function(x) {
  !any(is.na(suppressWarnings(as.numeric(na.omit(x))))) & is.character(x)
}
df %>% 
  mutate_if(is_all_numeric,as.numeric) %>%
  str()

If you want to convert specific named columns, then mutate_at is better.

df %>% mutate_at('x1', as.numeric) %>% str()

scp (secure copy) to ec2 instance without password

scp -i ~/.ssh/key.pem ec2-user@ip:/home/ec2-user/file-to-copy.txt .

The file name shouldnt be between the pem file and the ec2-user string - that doesnt work. This also allows you to reserve the name of the copied file.

Can't find android device using "adb devices" command

If using adb devices on Mac OS X no device is displayed and, of course, you have enabled the USB debugging on your device (see http://developer.android.com/tools/device.html), then try with:

$ android update adb
adb has been updated. You must restart adb with the following commands
    adb kill-server
    adb start-server

Then:

$ adb kill-server
$ adb start-server
* daemon not running. starting it now on port ... *
* daemon started successfully *

And finally:

$ adb devices
List of devices attached 
......  device

Your device should be now in the list.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

How do I run two commands in one line in Windows CMD?

A number of processing symbols can be used when running several commands on the same line, and may lead to processing redirection in some cases, altering output in other case, or just fail. One important case is placing on the same line commands that manipulate variables.

@echo off
setlocal enabledelayedexpansion
set count=0
set "count=1" & echo %count% !count!

0 1

As you see in the above example, when commands using variables are placed on the same line, you must use delayed expansion to update your variable values. If your variable is indexed, use CALL command with %% modifiers to update its value on the same line:

set "i=5" & set "arg!i!=MyFile!i!" & call echo path!i!=%temp%\%%arg!i!%%

path5=C:\Users\UserName\AppData\Local\Temp\MyFile5

Get list of passed arguments in Windows batch script (.bat)

@echo off
:start

:: Insert your code here
echo.%%1 is now:%~1
:: End insert your code here

if "%~2" NEQ "" (
    shift
    goto :start
)

Django datetime issues (default=datetime.now())

The answer to this one is actually wrong.

Auto filling in the value (auto_now/auto_now_add isn't the same as default). The default value will actually be what the user sees if its a brand new object. What I typically do is:

date = models.DateTimeField(default=datetime.now, editable=False,)

Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field name

read_only = 'date'

Again, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise. There is certainly a difference however between setting a default value and implementing the auto_add which is key here. Test it out!

How to retrieve the current version of a MySQL database management system (DBMS)?

Try this function -

SELECT VERSION();
-> '5.7.22-standard'

VERSION()

Or for more details use :

SHOW VARIABLES LIKE "%version%";
+-------------------------+------------------------------------------+
| Variable_name           | Value                                    |
+-------------------------+------------------------------------------+
| protocol_version        | 10                                       |
| version                 | 5.0.27-standard                          |
| version_comment         | MySQL Community Edition - Standard (GPL) |
| version_compile_machine | i686                                     |
| version_compile_os      | pc-linux-gnu                             |
+-------------------------+------------------------------------------+
5 rows in set (0.04 sec)

MySQL 5.0 Reference Manual (pdf) - Determining Your Current MySQL Version - page 42

How do you load custom UITableViewCells from Xib files?

The correct way to do it is to create a UITableViewCell subclass implementation, header, and XIB. In the XIB remove any views and just add a table cell. Set the class as the name of the UITableViewCell subclass. For file owner, make it the UITableViewController subclass class name. Connect the file owner to the cell using the tableViewCell outlet.

In the header file:

UITableViewCell *_tableViewCell;
@property (assign) IBOutlet UITableViewCell *tableViewCell;

In the implementation file:

@synthesize tableViewCell = _tableViewCell;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellIdentifier = @"reusableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:kCellIdentifier owner:self options:nil];
        cell = _tableViewCell;
        self.tableViewCell = nil;
    }

    return cell;
}

HTTP POST with URL query parameters -- good idea or not?

You want reasons? Here's one:

A web form can't be used to send a request to a page that uses a mix of GET and POST. If you set the form's method to GET, all the parameters are in the query string. If you set the form's method to POST, all the parameters are in the request body.

Source: HTML 4.01 standard, section 17.13 Form Submission

What's the difference between git reset --mixed, --soft, and --hard?

In these cases I like a visual that can hopefully explain this:

git reset --[hard/mixed/soft] :

enter image description here

So each effect different scopes

  1. Hard => WorkingDir + Index + HEAD
  2. Mixed => Index + HEAD
  3. Soft => HEAD only (index and working dir unchanged).

How to use a client certificate to authenticate and authorize in a Web API

Make sure HttpClient has access to the full client certificate (including the private key).

You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.

Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).

Best XML Parser for PHP

It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.

If you are looking to manipulate the XML files you're probably best off using DOM XML

How to remove carriage return and newline from a variable in shell script

yet another solution uses tr:

echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'

the option -d stands for delete.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

This is all that is needed:

<!doctype html>
<script src="/path.js"></script>

JQuery - how to select dropdown item based on value

You can select dropdown option value by name

// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }

});

How do I position a div relative to the mouse pointer using jQuery?

There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.

The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.

body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.

Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.

But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.

The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:

// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
}) 

Phew. That took me a while to fix ! I hope this is useful to other developers !

How can I check if char* variable points to empty string?

Check if the first character is '\0'. You should also probably check if your pointer is NULL.

char *c = "";
if ((c != NULL) && (c[0] == '\0')) {
   printf("c is empty\n");
}

You could put both of those checks in a function to make it convenient and easy to reuse.

Edit: In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".

The && simply combines the two conditions. It is basically like saying this:

if (c != NULL) { /* AND (or &&) */
    if (c[0] == '\0') {
        printf("c is empty\n");
    }
}

You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".

The shortest version equivalent to the above would be:

if (c && !c[0]) {
  printf("c is empty\n");
}

Inserting multiple rows in a single SQL query?

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

How can I check for IsPostBack in JavaScript?

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

<html>

<?php
if ($_POST['myVar']) {
    //postback
    echo '<script>var postingBack = true;</script>';
    //Do other processing
} else {
    echo '<script>var postingBack = false;</script>'
 } ?>
<script>
function myLoader() {
     if (postingBack == false) {
          //Do stuff
     }
 }

<body onLoad="myLoader():"> ...

How to run a program in Atom Editor?

I find the Script package useful for this. You can download it here.

Once installed you can run scripts in many languages directly from Atom using cmd-i on Mac or shift-ctrl-b on Windows or Linux.

link_to image tag. how to add class to a tag

<%= link_to root_path do %><%= image_tag("Search.png",:alt=>'Vivek',:title=>'Vivek',:class=>'dock-item')%><%= content_tag(:span, "Search").html_safe%><% end %>

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

Delete all nodes and relationships in neo4j 1.8

if the name of node is for example : abcd then below query will work :

MATCH (n:abcd)
DETACH DELETE n

This will only delete the node with label "abcd" and all its relation-ships.

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php

select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
  from ...

or

select to_char(date_field,'mon dd, yyyy')
  from ...  

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

Django -- Template tag in {% if %} block

You shouldn't use the double-bracket {{ }} syntax within if or ifequal statements, you can simply access the variable there like you would in normal python:

{% if title == source %}
   ...
{% endif %}

Can one do a for each loop in java in reverse order?

The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:

for (int i = stack.size() - 1; i >= 0; i--) {
    System.out.println(stack.get(i));
}

I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.

Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.

Razor View Without Layout

@{ viewbag.title="index" Layout = null; }

Negative matching using grep (match lines that do not contain foo)

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Find all matches in workbook using Excel VBA

Below code avoids creating infinite loop. Assume XYZ is the string which we are looking for in the workbook.

   Private Sub CommandButton1_Click()
   Dim Sh As Worksheet, myCounter
   Dim Loc As Range

   For Each Sh In ThisWorkbook.Worksheets
   With Sh.UsedRange
   Set Loc = .Cells.Find(What:="XYZ")

    If Not Loc Is Nothing Then

           MsgBox ("Value is found  in " & Sh.Name)
           myCounter = 1
            Set Loc = .FindNext(Loc)

    End If
End With
Next
If myCounter = 0 Then
MsgBox ("Value not present in this worrkbook")
End If

End Sub

Revert to a commit by a SHA hash in Git?

Updated:

This answer is simpler than my answer: https://stackoverflow.com/a/21718540/541862

Original answer:

# Create a backup of master branch
git branch backup_master

# Point master to '56e05fce' and
# make working directory the same with '56e05fce'
git reset --hard 56e05fce

# Point master back to 'backup_master' and
# leave working directory the same with '56e05fce'.
git reset --soft backup_master

# Now working directory is the same '56e05fce' and
# master points to the original revision. Then we create a commit.
git commit -a -m "Revert to 56e05fce"

# Delete unused branch
git branch -d backup_master

The two commands git reset --hard and git reset --soft are magic here. The first one changes the working directory, but it also changes head (the current branch) too. We fix the head by the second one.

Convert an image (selected by path) to base64 string

You can convert it like this

  string test = @"C:/image/1.gif";
  byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(test);
  string base64String = System.Convert.ToBase64String(bytes);
  Console.WriteLine("Base 64 string: " + base64String);

Output

  QzovaW1hZ2UvMS5naWY=

Creating a selector from a method name with parameters

Beyond what's been said already about selectors, you may want to look at the NSInvocation class.

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.

An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.

Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.

How to detect scroll position of page using jQuery

GET Scroll Position:

var scrolled_val = window.scrollY;

DETECT Scroll Position:

$(window).scroll
(
     function (event) 
     {
          var scrolled_val = window.scrollY;
          alert(scrolled_val);
     }
 );

Android ViewPager with bottom dots

If anyone wants to build a viewPager with thumbnails as indicators, using this library could be an option: ThumbIndicator for viewPager that works also with image links as resources.

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

The $(document).ready mechanism is meant to fire after the DOM has been loaded successfully but makes no guarantees as to the state of the images referenced by the page.

When in doubt, fall back on the good ol' window.onload event:

window.onload = function()
{
  //your code here
};

Now, this is obviously slower than the jQuery approach. However, you can compromise somewhere in between:

$(document).ready
(
  function()
  {
    var img = document.getElementById("myImage");

    var intervalId = setInterval(
                        function()
                        {
                          if(img.complete)
                          {
                            clearInterval(intervalId);
                            //now we can start rotating the header
                          }
                        },
                        50);
  }
);

To explain a bit:

  1. we grab the DOM element of the image whose image we want completely loaded

  2. we then set an interval to fire every 50 milliseconds.

  3. if, during one of these intervals, the complete attribute of this image is set to true, the interval is cleared and the rotate operation is safe to start.

starting file download with JavaScript

To get around the security flaw in the top-voted answer, you can set the iframe src directly to the file you want (instead of an intermediate php file) and set the header information in an .htaccess file:

<Files *.apk>
     ForceType application/force-download
     Header set Content-Disposition attachment
     Header set Content-Type application/vnd.android.package-archive
     Header set Content-Transfer-Encoding binary
</Files>

Java Error: illegal start of expression

Declare

public static int[] locations={1,2,3};

outside of the main method.

If WorkSheet("wsName") Exists

There's no built-in function for this.

Function SheetExists(SheetName As String, Optional wb As Excel.Workbook)
   Dim s As Excel.Worksheet
   If wb Is Nothing Then Set wb = ThisWorkbook
   On Error Resume Next
   Set s = wb.Sheets(SheetName)
   On Error GoTo 0
   SheetExists = Not s Is Nothing
End Function

What's the difference between "super()" and "super(props)" in React when using es6 classes?

As per source code

function ReactComponent(props, context) {
  this.props = props;
  this.context = context;
}

you must pass props every time you have props and you don't put them into this.props manually.

A valid provisioning profile for this executable was not found... (again)

In my case it was just after a new Program Licence Agreement was released so we had to accept them and it was fine.

The difference between "require(x)" and "import x"

I will make it simple,

  • Import and Export are ES6 features(Next gen JS).
  • Require is old school method of importing code from other files

Major difference is in require, entire JS file is called or imported. Even if you don't need some part of it.

var myObject = require('./otherFile.js'); //This JS file will be imported fully.

Whereas in import you can extract only objects/functions/variables which are required.

import { getDate }from './utils.js'; 
//Here I am only pulling getDate method from the file instead of importing full file

Another major difference is you can use require anywhere in the program where as import should always be at the top of file

How to append a newline to StringBuilder

I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Usage:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Console:

aaaaa
bbbbb

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

How do you merge two Git repositories?

If you want to put the files from a branch in repo B in a subtree of repo A and also preserve the history, keep reading. (In the example below, I am assuming that we want repo B's master branch merged into repo A's master branch.)

In repo A, first do the following to make repo B available:

git remote add B ../B # Add repo B as a new remote.
git fetch B

Now we create a brand new branch (with only one commit) in repo A that we call new_b_root. The resulting commit will have the files that were committed in the first commit of repo B's master branch but put in a subdirectory called path/to/b-files/.

git checkout --orphan new_b_root master
git rm -rf . # Remove all files.
git cherry-pick -n `git rev-list --max-parents=0 B/master`
mkdir -p path/to/b-files
git mv README path/to/b-files/
git commit --date="$(git log --format='%ai' $(git rev-list --max-parents=0 B/master))"

Explanation: The --orphan option to the checkout command checks out the files from A's master branch but doesn't create any commit. We could have selected any commit because next we clear out all the files anyway. Then, without committing yet (-n), we cherry-pick the first commit from B's master branch. (The cherry-pick preserves the original commit message which a straight checkout doesn't seem to do.) Then we create the subtree where we want to put all files from repo B. We then have to move all files that were introduced in the cherry-pick to the subtree. In the example above, there's only a README file to move. Then we commit our B-repo root commit, and, at the same time, we also preserve the timestamp of the original commit.

Now, we'll create a new B/master branch on top of the newly created new_b_root. We call the new branch b:

git checkout -b b B/master
git rebase -s recursive -Xsubtree=path/to/b-files/ new_b_root

Now, we merge our b branch into A/master:

git checkout master
git merge --allow-unrelated-histories --no-commit b
git commit -m 'Merge repo B into repo A.'

Finally, you can remove the B remote and temporary branches:

git remote remove B
git branch -D new_b_root b

The final graph will have a structure like this:

enter image description here

Insert HTML with React Variable Statements (JSX)

dangerouslySetInnerHTML has many disadvantage because it set inside the tag.

I suggest you to use some react wrapper like i found one here on npm for this purpose. html-react-parser does the same job.

import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content">{Parser(thisIsMyCopy)}</div>
    );
}

Very Simple :)

Is there any kind of hash code function in JavaScript?

Based on the title, we can generate strong SHA hashes, in a browser context, it can be used to generate a unique hash from an object, an array of params, a string, or whatever.

_x000D_
_x000D_
async function H(m) {
  const msgUint8 = new TextEncoder().encode(m)                       
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8)          
  const hashArray = Array.from(new Uint8Array(hashBuffer))                    
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  console.log(hashHex)
}

/* Examples ----------------------- */
H("An obscure ....")
H(JSON.stringify( {"hello" : "world"} ))
H(JSON.stringify( [54,51,54,47] ))
_x000D_
_x000D_
_x000D_

The above output in my browser, it should be equal for you too:

bf1cf3fe6975fe382ab392ec1dd42009380614be03d489f23601c11413cfca2b
93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588
d2f209e194045604a3b15bdfd7502898a0e848e4603c5a818bd01da69c00ad19

Supported algos:

SHA-1 (but don't use this in cryptographic applications)
SHA-256
SHA-384
SHA-512

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

phpMyAdmin - The MySQL Extension is Missing

At first make sure you have mysql installed properly. You can ensure it just by checking that whether you can access mysql using mysql command promp. So if you mysql is working then probably it is not loading. For that follow the steps given below

First of all, you must find your php.ini. It could be anywhere but if you create a small php file with the

<?php phpinfo(); ?>

script it will tell you where it is. Just look at the path of loaded configuration file. Common places include /etc/apache/, /etc/php4/apache2/php.ini, /etc/php5/apache2/php.ini or even /usr/local/lib/php.ini for Windows it may be C:\Users\username\PHP\php.ini

Edit your server’s php.ini and look for the following line. Remove the ‘;’ from the start of the line and restart Apache. Things should work fine now!

;extension=mysql.so

should become

extension=mysql.so

For windows it will be

;extension=mysql.dll

should become

extension=mysql.dll

Controlling execution order of unit tests in Visual Studio

I see that this topic is almost 6 years old, and we now have new version of Visual studio but I will reply anyway. I had that order problem in Visual Studio 19 and I figured it out by adding capital letter (you can also add small letter) in front of your method name and in alphabetical order like this:

[TestMethod]
        public void AName1()
        {}
[TestMethod]
        public void BName2()
        {}

And so on. I know that this doesn't look appealing, but it looks like Visual is sorting your tests in test explorer in alphabetical order, doesn't matter how you write it in your code. Playlist didn't work for me in this case.

Hope that this will help.

Printing Mongo query output to a file while in the mongo shell

We can do it this way -

mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.json

The shellBatchSize argument is used to determine how many rows is the mongo client allowed to print. Its default value is 20.

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Python: How to pip install opencv2 with specific version 2.4.9?

If you are using windows os, you can download your desired opencv unofficial windows binary from here, and type something like pip install opencv_python-2.4.13.2-cp27-cp27m-win_amd64.whl in the directory of binary file.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

You could use both LTRIM and RTRIM.

select rtrim(ltrim('abcdab','ab'),'ab') from dual;

If you want to trim CHR(13) only when it comes with a CHR(10) it gets more complicated. Firstly, translated the combined string to a single character. Then LTRIM/RTRIM that character, then replace the single character back to the combined string.

select replace(rtrim(ltrim(replace('abccccabcccaab','ab','#'),'#'),'#'),'#','ab') from dual;

npm not working - "read ECONNRESET"

This can be caused by installing anything with npm using sudo -- this causes the files in the cache to be owned by root, resulting in this problem. You can fix it by running:

sudo rm -rf ~/.npm

to remove the cache. Then try whatever you were doing again, making sure you never use sudo along with npm (or the problem may come back).

Lots more information: npm throws error without sudo

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

JQuery ajax call default timeout value

There doesn't seem to be a standardized default value. I have the feeling the default is 0, and the timeout event left totally dependent on browser and network settings.

For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

sudo apt-get install putty

This will automatically install the puttygen tool.

Now to convert the PPK file to be used with SSH command execute the following in terminal

puttygen mykey.ppk -O private-openssh -o my-openssh-key

Then, you can connect via SSH with:

ssh -v [email protected] -i my-openssh-key

http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603

Perform Segue programmatically and pass parameters to the destination view

In case if you use new swift version.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}

Div side by side without float

The usual method when not using floats is to use display: inline-block: http://www.jsfiddle.net/zygnz/1/

.container div {
  display: inline-block;
}

Do note its limitations though: There is a additional space after the first bloc - this is because the two blocks are now essentially inline elements, like a and em, so whitespace between the two counts. This could break your layout and/or not look nice, and I'd prefer not to strip out all whitespaces between characters for the sake of this working.

Floats are also more flexible, in most cases.

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this:

UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
   Test1.dbo.Employee.EmployeeID = emp2.EmployeeID

From your post, I'm not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that's what my query does), or the other way around (since you mention the db on Test1 was the new table......)

"Insufficient Storage Available" even there is lot of free space in device memory

I also had this issue while installating an app after I had uninstalled that. I resolved downloading Lucky Patcher and then click on menu - troubleshooting - remove fixes and backups (insufficient storage available). Please notice you need your device to be rooted.

Android studio logcat nothing to show

Step 1: Connect Your Phone with Android Developer option On and USB Debug On.

Step 2: Go TO View > Tools Window > Logcat

Step 3: Before Run Project Make Sure Your Phone Connect Android Studio. Then run application

Note: If You Can not Show Logcat Just Restart Android Studio : File > Invalid Caches/ restart

Taking multiple inputs from user in python

In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.

items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]

print items

How can I compile LaTeX in UTF8?

I have success with using the Chrome addon "Sharelatex". This online editor has great compability with most latex files, but it somewhat lacks configuration possibilities. www.sharelatex.com

How can I clear the content of a file?

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

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

Rails: How can I set default values in ActiveRecord?

Similar questions, but all have slightly different context: - How do I create a default value for attributes in Rails activerecord's model?

Best Answer: Depends on What You Want!

If you want every object to start with a value: use after_initialize :init

You want the new.html form to have a default value upon opening the page? use https://stackoverflow.com/a/5127684/1536309

class Person < ActiveRecord::Base
  has_one :address
  after_initialize :init

  def init
    self.number  ||= 0.0           #will set the default value only if it's nil
    self.address ||= build_address #let's you set a default association
  end
  ...
end 

If you want every object to have a value calculated from user input: use before_save :default_values You want user to enter X and then Y = X+'foo'? use:

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status ||= 'P'
  end
end

Parsing JSON in Java without knowing JSON format

If a different library is fine for you, you could try org.json:

JSONObject object = new JSONObject(myJSONString);
String[] keys = JSONObject.getNames(object);

for (String key : keys)
{
    Object value = object.get(key);
    // Determine type of value and do something with it...
}

How can I make all images of different height and width the same via CSS?

Simplest way - This will keep the image size as it is and fill the other area with space, this way all the images will take same specified space regardless of the image size without stretching

.img{
   width:100px;
   height:100px;

/*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/
    object-fit:scale-down;

}

Create a date from day month and year with T-SQL

Try this:

Declare @DayOfMonth TinyInt Set @DayOfMonth = 13
Declare @Month TinyInt Set @Month = 6
Declare @Year Integer Set @Year = 2006
-- ------------------------------------
Select DateAdd(day, @DayOfMonth - 1, 
          DateAdd(month, @Month - 1, 
              DateAdd(Year, @Year-1900, 0)))

It works as well, has added benefit of not doing any string conversions, so it's pure arithmetic processing (very fast) and it's not dependent on any date format This capitalizes on the fact that SQL Server's internal representation for datetime and smalldatetime values is a two part value the first part of which is an integer representing the number of days since 1 Jan 1900, and the second part is a decimal fraction representing the fractional portion of one day (for the time) --- So the integer value 0 (zero) always translates directly into Midnight morning of 1 Jan 1900...

or, thanks to suggestion from @brinary,

Select DateAdd(yy, @Year-1900,  
       DateAdd(m,  @Month - 1, @DayOfMonth - 1)) 

Edited October 2014. As Noted by @cade Roux, SQL 2012 now has a built-in function:
DATEFROMPARTS(year, month, day)
that does the same thing.

Edited 3 Oct 2016, (Thanks to @bambams for noticing this, and @brinary for fixing it), The last solution, proposed by @brinary. does not appear to work for leap years unless years addition is performed first

select dateadd(month, @Month - 1, 
     dateadd(year, @Year-1900, @DayOfMonth - 1)); 

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs.110).aspx

Creating new database from a backup of another Database on the same server?

I think that is easier than this.

  • First, create a blank target database.
  • Then, in "SQL Server Management Studio" restore wizard, look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
  • Remember to select target files in 'Files' page.

You can change 'tabs' at left side of the wizard (General, Files, Options)

Does C# support multiple inheritance?

C# 3.5 or below does not support the multiple inheritance, but C# 4.0 could do this by using, as I remembered, Dynamics.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

How to add (vertical) divider to a horizontal LinearLayout?

Update: pre-Honeycomb using AppCompat

If you are using the AppCompat library v7 you may want to use the LinearLayoutCompat view. Using this approach you can use drawable dividers on Android 2.1, 2.2 and 2.3.

Example code:

<android.support.v7.widget.LinearLayoutCompat
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:showDividers="middle"
        app:divider="@drawable/divider">

drawable/divider.xml: (divider with some padding on the top and bottom)

<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
        android:insetBottom="2dp"
        android:insetTop="2dp">
    <shape>
        <size android:width="1dp" />
        <solid android:color="#FFCCCCCC" />
    </shape>
</inset>

Very important note: The LinearLayoutCompat view does not extend LinearLayout and therefor you should not use the android:showDividers or android:divider properties but the custom ones: app:showDividers and app:divider. In code you should also use the LinearLayoutCompat.LayoutParams not the LinearLayout.LayoutParams!

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The Reason

You are not opening the page through a server, like Apache, so when the browser tries to obtain the resource it thinks it is from a separate domain, which is not allowed. Though some browsers do allow it.

The Solution

Run inetmgr and host your page locally and browse as http://localhost:portnumber/PageName.html or through a web server like Apache, nginx, node etc.

Alternatively use a different browser No error was shown when directly opening the page using Firefox and Safari. It comes only for Chrome and IE(xx).

If you are using code editors like Brackets, Sublime or Notepad++, those apps handle this error automatically.

Positive Number to Negative Number in JavaScript?

It will convert negative array to positive or vice versa

function negateOrPositive(arr) {
    arr.map(res => -res)
};

Whether a variable is undefined

function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

Check if a variable is null in plsql

Another way:

var := coalesce (var, 5);

COALESCE is the ANSI equivalent (more or less) of Oracle's NVL function.

React.js: Identifying different inputs with one onChange handler

You can track the value of each child input by creating a separate InputField component that manages the value of a single input. For example the InputField could be:

var InputField = React.createClass({
  getInitialState: function () {
    return({text: this.props.text})
  },
  onChangeHandler: function (event) {
     this.setState({text: event.target.value})
  }, 
  render: function () {
    return (<input onChange={this.onChangeHandler} value={this.state.text} />)
  }
})

Now the value of each input can be tracked within a separate instance of this InputField component without creating separate values in the parent's state to monitor each child component.

Converting int to string in C

void itos(int value, char* str, size_t size) {
    snprintf(str, size, "%d", value);
}

..works with call by reference. Use it like this e.g.:

int someIntToParse;
char resultingString[length(someIntToParse)];

itos(someIntToParse, resultingString, length(someIntToParse));

now resultingString will hold your C-'string'.

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

enter image description heregoto Android->sdk->build-tools directory make sure you have all the versions required . if not , download them . after that goto File-->Settigs-->Build,Execution,Depoyment-->Gradle

choose use default gradle wapper (recommended)

and untick Offline work

gradle build finishes successfully for once you can change the settings

If it dosent simply solve the problem

check this link to find an appropriate support library revision

https://developer.android.com/topic/libraries/support-library/revisions

Make sure that the compile sdk and target version same as the support library version. It is recommended maintain network connection atleast for the first time build (Remember to rebuild your project after doing this)

What is the C++ function to raise a number to a power?

I don't have enough reputation to comment, but if you like working with QT, they have their own version.

    #include <QtCore/qmath.h>
    qPow(x, y); // returns x raised to the y power.

Or if you aren't using QT, cmath has basically the same thing.

    #include <cmath>
    double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
    pow(x, y); //Should return this: 78125

super() in Java

As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

Here is an example of this:

class A {
    A() {
    System.out.println("Constructor A");
    }
}

class B extends A{

    public B() {
    System.out.println("Constructor B");
    }
}

class C extends B{ 

    public C() {
    System.out.println("Constructor C");
    }

    public static void main(String[] args) {
    C c1 = new C();
    }
} 

The above would output:

Constructor A
Constructor B
Constructor C

Execute a shell function with timeout

function foo(){
    for i in {1..100};
    do 
        echo $i;  
        sleep 1;
    done;
}

cat <( foo ) # Will work 
timeout 3 cat <( foo ) # Will Work 
timeout 3 cat <( foo ) | sort # Wont work, As sort will fail 
cat <( timeout 3 cat <( foo ) ) | sort -r # Will Work 

Using Spring RestTemplate in generic method with generic parameter

My own implementation of generic restTemplate call:

private <REQ, RES> RES queryRemoteService(String url, HttpMethod method, REQ req, Class reqClass) {
    RES result = null;
    try {
        long startMillis = System.currentTimeMillis();

        // Set the Content-Type header
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(new MediaType("application","json"));            

        // Set the request entity
        HttpEntity<REQ> requestEntity = new HttpEntity<>(req, requestHeaders);

        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Add the Jackson and String message converters
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

        // Make the HTTP POST request, marshaling the request to JSON, and the response to a String
        ResponseEntity<RES> responseEntity = restTemplate.exchange(url, method, requestEntity, reqClass);
        result = responseEntity.getBody();
        long stopMillis = System.currentTimeMillis() - startMillis;

        Log.d(TAG, method + ":" + url + " took " + stopMillis + " ms");
    } catch (Exception e) {
         Log.e(TAG, e.getMessage());
    }
    return result;
}

To add some context, I'm consuming RESTful service with this, hence all requests and responses are wrapped into small POJO like this:

public class ValidateRequest {
  User user;
  User checkedUser;
  Vehicle vehicle;
}

and

public class UserResponse {
  User user;
  RequestResult requestResult;
}

Method which calls this is the following:

public User checkUser(User user, String checkedUserName) {
    String url = urlBuilder()
            .add(USER)
            .add(USER_CHECK)
            .build();

    ValidateRequest request = new ValidateRequest();
    request.setUser(user);
    request.setCheckedUser(new User(checkedUserName));

    UserResponse response = queryRemoteService(url, HttpMethod.POST, request, UserResponse.class);
    return response.getUser();
}

And yes, there's a List dto-s as well.

_tkinter.TclError: no display name and no $DISPLAY environment variable

Another solution is to install Xvfb, and export your display to it. ie:

disp=:8
screen=0
geom=640x480x24
exec Xvfb $disp -screen $screen $geom 2>/tmp/Xvfb.log &

Then

$ export DISPLAY=:8

$ ./example.py

Getting the name of the currently executing method

Util.java:

public static String getCurrentClassAndMethodNames() {
    final StackTraceElement e = Thread.currentThread().getStackTrace()[2];
    final String s = e.getClassName();
    return s.substring(s.lastIndexOf('.') + 1, s.length()) + "." + e.getMethodName();
}

SomeClass.java:

public class SomeClass {
    public static void main(String[] args) {
        System.out.println(Util.getCurrentClassAndMethodNames()); // output: SomeClass.main
    }
}

Cannot lower case button text in android studio

This is fixable in the application code by setting the button's TransformationMethod null, e.g.

mButton.setTransformationMethod(null);

C# Macro definitions in Preprocessor

Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.

javascript multiple OR conditions in IF statement

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

Parse DateTime string in JavaScript

Use Date object:

var time = Date.parse('02.02.1999');
document.writeln(time);

Give: 917902800000

Laravel migration: unique key is too long, even if specified

I had a problem, change the configuration of the 'config / database'

file 'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',

keeping the same pattern in the database.

I then gave the command

php artisan migrate

htaccess remove index.php from url

This will work, use the following code in .htaccess file RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

How to use external ".js" files

Code like this

 <html>
    <head>
          <script type="text/javascript" src="path/to/script.js"></script>
          <!--other script and also external css included over here-->
    </head>
    <body>
        <form>
            <select name="users" onChange="showUser(this.value)">
               <option value="1">Tom</option>
               <option value="2">Bob</option>
               <option value="3">Joe</option>
            </select>
        </form>
    </body>
    </html>

I hope it will help you.... thanks

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

In VB:

from m in MyTable
take 10
select m.Foo

This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.

It also assumes that Foo is a column in MyTable that gets mapped to a property name.

See http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx for more detail.

MySQL user DB does not have password columns - Installing MySQL on OSX

Thank you for your help. Just in case if people are still having problems, try this.

For MySQL version 5.6 and under

Have you forgotten your Mac OS X 'ROOT' password  and need to reset it?  Follow these 4 simple steps:

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:      sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q
  4.  Stop the mysqld server again and restart it in normal mode.

For MySQL version 5.7 and up

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:            sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q      
  4.  Stop the mysqld server again and restart it in normal mode.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

To use the strict ISO8601, you can use the s (Sortable) format string:

 myDate.ToString("s"); // example 2009-06-15T13:45:30

It's a short-hand to this custom format string:

myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");

And of course, you can build your own custom format strings.

More info:

How to get a matplotlib Axes instance to plot to?

You can either

fig, ax = plt.subplots()  #create figure and axes
candlestick(ax, quotes, ...)

or

candlestick(plt.gca(), quotes) #get the axis when calling the function

The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot

SQL Server Group by Count of DateTime Per Hour?

I found this somewhere else. I like this answer!

SELECT [Hourly], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
    FROM table) idat
 GROUP BY [Hourly]

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I've been strugglin with this problem for hours till found this post. Just like @ligi said, some people have two SDK folders (Android Studio, which is bundled and Eclipse). The problem is that it doesn't matter if you downloaded the Google Play Services library on both SDK folders, your ANDROID_HOME enviroment variable must be pointing to the SDK folder used by the Android Studio.

SDK Folder A  (Used on Eclipse)
SDK Folder B  (Used on AS)

ANDROID_HOME=<path to SDK Folder B>

After change the path of this variable the error was gone.