Programs & Examples On #Inline

An inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. (However, compilers are not obligated to respect this request.)

How to write inline if statement for print?

You can use:

print (1==2 and "only if condition true" or "in case condition is false")

Just as well you can keep going like:

print 1==2 and "aa" or ((2==3) and "bb" or "cc")

Real world example:

>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
1 item found.
>>> count = 2
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
2 items found.

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

Why are C++ inline functions in the header?

I know this is an old thread but thought I should mention that the extern keyword. I've recently ran into this issue and solved as follows

Helper.h

namespace DX
{
    extern inline void ThrowIfFailed(HRESULT hr);
}

Helper.cpp

namespace DX
{
    inline void ThrowIfFailed(HRESULT hr)
    {
        if (FAILED(hr))
        {
            std::stringstream ss;
            ss << "#" << hr;
            throw std::exception(ss.str().c_str());
        }
    }
}

Java - Check Not Null/Empty else assign default value

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
    return value == null ? defaultValue : value;
}

inline if statement java, why is not working

(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:

int y = (c == 19) ? 7 : 11 ; 

or

String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);

as You can see the type of the variable Y is the same as the return value ...

in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");

Send inline image in email

You need to add the LinkedResource into an AlternateView

AlternateView alternateView = AlternateView.CreateAlternateViewFromString("<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
                @"<img src=""cid:{0}"" />", null, "text/html");
alternateView.LinkedResources.Add(inline);
mail.AlternateViews.Add(alternateView);

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

How to pass event as argument to an inline event handler in JavaScript?

You don't need to pass this, there already is the event object passed by default automatically, which contains event.target which has the object it's coming from. You can lighten your syntax:

This:

<p onclick="doSomething()">

Will work with this:

function doSomething(){
  console.log(event);
  console.log(event.target);
}

You don't need to instantiate the event object, it's already there. Try it out. And event.target will contain the entire object calling it, which you were referencing as "this" before.

Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:

document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));

Then doSomething() will see event and event.target as per usual!

No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.

CSS two div width 50% in one line with line break in file

How can i do something like that but without using absolute position and float?

Apart from using the inline-block approach (as mentioned in other answers) here are some other approaches:

1) CSS tables (FIDDLE)

_x000D_
_x000D_
.container {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
}_x000D_
.container div {_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>A</div>_x000D_
  <div>B</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2) Flexbox (FIDDLE)

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.container div {_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>A</div>_x000D_
  <div>B</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

For a reference, this CSS-tricks post seems to sum up the various approaches to acheive this.

How can I tell gcc not to inline a function?

GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

Inline functions in C#?

I know this question is about C#. However, you can write inline functions in .NET with F#. see: Use of `inline` in F#

When should I write the keyword 'inline' for a function/method?

Inline keyword requests the compiler to replace the function call with the body of the function ,it first evaluates the expression and then passed.It reduces the function call overhead as there is no need to store the return address and stack memory is not required for function arguments.

When to use:

  • To Improve performance
  • To reduce call overhead .
  • As it's just a request to the compiler, certain functions won't be inlined *large functions
    • functions having too many conditional arguments
    • recursive code and code with loops etc.

How to check for null in a single statement in scala?

If it instead returned Option[QueueObject] you could use a construct like getObject.foreach { QueueManager.add }. You can wrap it right inline with Option(getObject).foreach ... because Option[QueueObject](null) is None.

JavaScript: IIF like statement

'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';

how to create inline style with :before and :after

You can't. With inline styles you are targeting the element directly. You can't use other selectors there.

What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

$('div').attr('style', '');

or

$('div').removeAttr('style'); (From Andres's Answer)

To make this a little smaller, try this:

$('div[style]').removeAttr('style');

This should speed it up a little because it checks that the divs have the style attribute.

Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.

Logo image and H1 heading on the same line

You can do it as Billy Moat told you, wrap your <img> and <h1> in a <div> and use float: left; to float your image to the left, set the <div> width and than set a line-height for your h1 and use <div style="clear: float;"></div> to clear your floating elements.

Fiddle

What's the difference between "static" and "static inline" function?

inline instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.

For small functions that are called frequently that can make a big performance difference.

However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.

for example:

static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};

This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline will essentially instruct the compiler to convert the code above into an equivalent of:

 int i;
 ....
 for (i=0; i<999999; i = i+1) { /* do something here */};

Skipping the actual function call and return

Obviously this is an example to show the point, not a real piece of code.

static refers to the scope. In C it means that the function/variable can only be used within the same translation unit.

How to display Base64 images in HTML?

Try this one too:

let base64="iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let buffer=Uint8Array.from(atob(base64), c => c.charCodeAt(0));
let blob=new Blob([buffer], { type: "image/gif" });
let url=URL.createObjectURL(blob);
let img=document.createElement("img");
img.src=url;
document.body.appendChild(img);

Not recommended for production as it is only compatible with modern browsers.

How to select first and last TD in a row?

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

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

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

How to permanently export a variable in Linux?

add the line to your .bashrc or .profile. The variables set in $HOME/.profile are active for the current user, the ones in /etc/profile are global. The .bashrc is pulled on each bash session start.

Python, compute list difference

most simple way,

use set().difference(set())

list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))

answer is set([1])

How to make a back-to-top button using CSS and HTML only?

This is the HTML only way:

<body>
<a name="top"></a>
foo content
foo bottom of page
<a href="#top">Back to Top</a>
</body>

There are quite a few other alternatives using jquery and jscript though which offer additional effects. It really just depends on what you are looking for.

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

Wait until all promises complete even if some rejected

Benjamin's answer offers a great abstraction for solving this issue, but I was hoping for a less abstracted solution. The explicit way to to resolve this issue is to simply call .catch on the internal promises, and return the error from their callback.

let a = new Promise((res, rej) => res('Resolved!')),
    b = new Promise((res, rej) => rej('Rejected!')),
    c = a.catch(e => { console.log('"a" failed.'); return e; }),
    d = b.catch(e => { console.log('"b" failed.'); return e; });

Promise.all([c, d])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Promise.all([a.catch(e => e), b.catch(e => e)])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Taking this one step further, you could write a generic catch handler that looks like this:

const catchHandler = error => ({ payload: error, resolved: false });

then you can do

> Promise.all([a, b].map(promise => promise.catch(catchHandler))
    .then(results => console.log(results))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!',  { payload: Promise, resolved: false } ]

The problem with this is that the caught values will have a different interface than the non-caught values, so to clean this up you might do something like:

const successHandler = result => ({ payload: result, resolved: true });

So now you can do this:

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

Then to keep it DRY, you get to Benjamin's answer:

const reflect = promise => promise
  .then(successHandler)
  .catch(catchHander)

where it now looks like

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

The benefits of the second solution are that its abstracted and DRY. The downside is you have more code, and you have to remember to reflect all your promises to make things consistent.

I would characterize my solution as explicit and KISS, but indeed less robust. The interface doesn't guarantee that you know exactly whether the promise succeeded or failed.

For example you might have this:

const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));

This won't get caught by a.catch, so

> Promise.all([a, b].map(promise => promise.catch(e => e))
    .then(results => console.log(results))
< [ Error, Error ]

There's no way to tell which one was fatal and which was wasn't. If that's important then you're going to want to enforce and interface that tracks whether it was successful or not (which reflect does).

If you just want to handle errors gracefully, then you can just treat errors as undefined values:

> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
    .then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]

In my case, I don't need to know the error or how it failed--I just care whether I have the value or not. I'll let the function that generates the promise worry about logging the specific error.

const apiMethod = () => fetch()
  .catch(error => {
    console.log(error.message);
    throw error;
  });

That way, the rest of the application can ignore its error if it wants, and treat it as an undefined value if it wants.

I want my high level functions to fail safely and not worry about the details on why its dependencies failed, and I also prefer KISS to DRY when I have to make that tradeoff--which is ultimately why I opted to not use reflect.

Get day of week using NSDate

The simple answer (swift 3):

Calendar.current.component(.weekday, from: Date())

How to put/get multiple JSONObjects to JSONArray?

I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object

Here's code to add multiple JSONObjects to JSONArray.

JSONArray Obj = new JSONArray();
try {
    for(int i = 0; i < 3; i++) {
        // 1st object
        JSONObject list1 = new JSONObject();
        list1.put("val1",i+1);
        list1.put("val2",i+2);
        list1.put("val3",i+3);
        obj.put(list1);
    }

} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}             
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();

store and retrieve a class object in shared preference

Yes we can do this using Gson

Download Working code from GitHub

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For save

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

For get

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Update1

The latest version of GSON can be downloaded from github.com/google/gson.

Update2

If you are using Gradle/Android Studio just put following in build.gradle dependencies section -

implementation 'com.google.code.gson:gson:2.6.2'

android.widget.Switch - on/off event listener?

You can use DataBinding and ViewModel for Switch Checked Change event

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
                name="viewModel"
                type="com.example.ui.ViewModel" />
    </data>
    <Switch
            android:id="@+id/on_off_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onCheckedChanged="@{(button, on) -> viewModel.onCheckedChange(on)}"
     />

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

Where are shared preferences stored?

Use http://facebook.github.io/stetho/ library to access your app's local storage with chrome inspect tools. You can find sharedPreference file under Local storage -> < your app's package name >

enter image description here

Retrieving Dictionary Value Best Practices

Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

Edit:

Ok, I understand your confusion so let me elaborate:

Case 1:

if (myDict.Contains(someKey))
     someVal = myDict[someKey];

In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it

Case 2:

myDict.TryGetValue(somekey, out someVal)

In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

Why does ++[[]][+[]]+[+[]] return the string "10"?

If we split it up, the mess is equal to:

++[[]][+[]]
+
[+[]]

In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).

Therefore, we can simplify it (++ has precendence over +):

++[[]][0]
+
[0]

Because [[]][0] means: get the first element from [[]], it is true that:

[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.

++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).

Again, we can simplify the mess into something more legible. Let's substitute [] back for A:

(+[] + 1)
+
[0]

Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.

  • (+[] + 1) === (+"" + 1)
  • (+"" + 1) === (0 + 1)
  • (0 + 1) === 1

Let's simplify it even more:

1
+
[0]

Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.

In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.

"1" + "0" === "10" // Yay!

Specification details for +[]:

This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber() says:

Object

Apply the following steps:

  1. Let primValue be ToPrimitive(input argument, hint String).

  2. Return ToString(primValue).

ToPrimitive() says:

Object

Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

[[DefaultValue]] says:

8.12.8 [[DefaultValue]] (hint)

When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:

  1. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".

  2. If IsCallable(toString) is true then,

a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.

b. If str is a primitive value, return str.

The .toString of an array says:

15.4.4.2 Array.prototype.toString ( )

When the toString method is called, the following steps are taken:

  1. Let array be the result of calling ToObject on the this value.

  2. Let func be the result of calling the [[Get]] internal method of array with argument "join".

  3. If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).

  4. Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.

So +[] comes down to +"", because [].join() === "".

Again, the + is defined as:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber is defined for "" as:

The MV of StringNumericLiteral ::: [empty] is 0.

So +"" === 0, and thus +[] === 0.

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

How do I append one string to another in Python?

Python 3.6 gives us f-strings, which are a delight:

var1 = "foo"
var2 = "bar"
var3 = f"{var1}{var2}"
print(var3)                       # prints foobar

You can do most anything inside the curly braces

print(f"1 + 1 == {1 + 1}")        # prints 1 + 1 == 2

How can I get the height and width of an uiimage?

UIImageView *imageView = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MyImage.png"]]autorelease];

NSLog(@"Size of my Image => %f, %f ", [[imageView image] size].width, [[imageView image] size].height) ;

Relative instead of Absolute paths in Excel VBA

It maybe is not the best way to do it. But the only I found to get the Absolute path is to calculate how many times the syntax .. was in the string and then use the function gotoparent as many times that syntax comes in the hyperlink adress. (in my case, my field is a hyperlink address. Ps: This code requires the reference to microsoft scripting runtime

Function AbsolutePath(strRelativePath As String, strCurrentFileName As String) As String
Dim fso As Object
Dim strCurrentProjectpath As String
Dim strGoToParentFolder As String
Dim strOrigineFolder As String
Dim strPath As String
Dim lngParentFolder As Long


''Pour retrouver le répertoire parent
Set fso = CreateObject("Scripting.FileSystemObject")

'' détermine le répertire du projet actif
strCurrentProjectpath = CurrentProject.Path

'' détermine le nom du répertoire dans lequel le fichier d'origine se trouve
strOrigineFolder = Replace(Replace(Replace(strRelativePath, strCurrentFileName, ""), "..", ""), "\", "")

''Extraction du chemin relatif (ex. ..\..\..)
strGoToParentFolder = Replace(Replace(strRelativePath, strOrigineFolder, ""), strCurrentFileName, "")

''retourne le nombre de fois qu'il faut remonter au répertoire parent
lngParentsFolder = Len(Replace(strGoToParentFolder, "\", "")) / 2

''détermine la valeur d'origine du répertoire du début
strPath = strCurrentProjectpath

Vérifie s 'il faut aller au répertoire parent
If lngParentsFolder < 1 Then
    'si non, alors répertoire parent et répertoire d'origine du fichier
    strPath = strCurrentProjectpath & "\" & strOrigineFolder
Else
    ''si oui, nous faisons la boucle pour retourner au répertoire d'origine
    For i = 1 To lngParentsFolder
        strPath = fso.GetParentFolderName(strPath)
    Next i
End If

''retournons le répertoire parent du fichier et son répertoire d'origine [le OUTPUT]
AbsolutePath = strPath & strOrigineFolder & "\"

End Function

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Javascript, Change google map marker color

I really liked the answer given by Bahadir Yagan except I didn't like depending on a limited set of icons given by Google or an external API to generate my marker icons. Here is the initial solution:

var marker = new google.maps.Marker({
    id: "some-id",
    icon: {
        path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        strokeColor: "red",
        scale: 3
    },
    map: map,
    title: "some-title",
    position: myLatlng
});

And here is my improved solution:

var marker = new google.maps.Marker({
            position: myLatlng,
            icon:{
                path: 'm 12,2.4000002 c -2.7802903,0 -5.9650002,1.5099999 -5.9650002,5.8299998 0,1.74375 1.1549213,3.264465 2.3551945,4.025812 1.2002732,0.761348 2.4458987,0.763328 2.6273057,2.474813 L 12,24 12.9825,14.68 c 0.179732,-1.704939 1.425357,-1.665423 2.626049,-2.424188 C 16.809241,11.497047 17.965,9.94 17.965,8.23 17.965,3.9100001 14.78029,2.4000002 12,2.4000002 Z',
                fillColor: '#00FF00',
                fillOpacity: 1.0,
                strokeColor: '#000000',
                strokeWeight: 1,
                scale: 2,
                anchor: new google.maps.Point(12, 24),
            },
        });

I wanted a specific pin icon so I went and made one with inkscape, then opened the SVG file and copied the svg path into the path into the code, but this works with any SVG path that you put in the "path" attribute of the icon object.

Here is the result:

enter image description here

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Get last 30 day records from today date in SQL Server

I dont know why all these complicated answers are on here but this is what I would do

where pdate >= CURRENT_TIMESTAMP -30

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

Change One Cell's Data in mysql

Try the following:

UPDATE TableName SET ValueName=@parameterName WHERE
IdName=@ParameterIdName

Resize UIImage and change the size of UIImageView

Use the category below and then apply border from Quartz into your image:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];

The category: UIImage+AutoScaleResize.h

#import <Foundation/Foundation.h>

@interface UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

UIImage+AutoScaleResize.m

#import "UIImage+AutoScaleResize.h"

@implementation UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

@end

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Lightweight workflow engine for Java

I would like to add my comments. When you choose a ready engine, such as jBPM, Activity and others (there are plenty of them), then you have to spend some time learning the system itself, this may not be an easy task. Especially, when you need only to automate small piece of code.

Then, when an issue occurs you have to deal with the vendor's support, which is not as speedy as you would imagine. Even pay for some consultancy.

And, last, a most important reason, you have to develop in the ecosystem of the engine. Although, the vendors tend to say that their system are flexible to be incorporated into any systems, this may not be case. Eventually you end up re-writing your application to match with the BPM ecosystem.

SVN - Checksum mismatch while updating

I found an easier way to fix this issue. You cannot do this directly from eclipse. Steps:

  1. Navigate to the workspace folder structure in windows
  2. rename the folder
  3. refresh in eclipse
  4. Now the folder and files will be removed from project in eclipse and will appear under new renamed folder
  5. Now try "Synchronise with Respository" option.

This will restore text base folder in .svnfolder . Checksum mismatch while updating error will not appear further.

Cannot set property 'innerHTML' of null

You have to place the hello div before the script, so that it exists when the script is loaded.

How do I export (and then import) a Subversion repository?

I found an article about how to move svn repositories from a hosting service to another, and how to do local backups:

  1. Define where you will store your repositories:

    mkdir ~/repo
    MYREPO=/home/me/someplace ## you should use full path here
    
  2. Now create a empty svn repository with svnadmin create $MYREPO
  3. Create a hook file and make it executable:

    echo '#!/bin/sh' > $MYREPO/hooks/pre-revprop-change
    chmod +x $MYREPO/hooks/pre-revprop-change
    
  4. Now we can start importing the repository with svnsync, that will initialize a destination repository for synchronization from another repository:

    svnsync init file://$MYREPO http://your.svn.repo.here/
    
  5. And the finishing touch to transfer all pending revisions to the destination from the source with which it was initialized:

    svnsync sync file://$MYREPO
    

There now you have a local svn repository in the ~/repo directory.

Source:

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

Class has been compiled by a more recent version of the Java Environment

53 stands for java-9, so it means that whatever class you have has been compiled with javac-9 and you try to run it with jre-8. Either re-compile that class with javac-8 or use the jre-9

How to set only time part of a DateTime variable in C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by using

DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");

OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:

DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

Argument Exception "Item with Same Key has already been added"

As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):

// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];

Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string> for each string key.

For example:

var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();

foreach (string line in rct3Lines)
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        // No items for this key have been added, so create a new list
        // for the value with item[1] as the only item in the list
        rct3Features.Add(items[0], new List<string> { items[1] });
    }
    else
    {
        // This key already exists, so add item[1] to the existing list value
        rct3Features[items[0]].Add(items[1]);
    }
}

// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
    Console.WriteLine("The Key: {0} has values:", item.Key);
    foreach (string value in item.Value)
    {
        Console.WriteLine(" - {0}", value);
    }
}

jQuery event to trigger action when a div is made visible

One way to do this.
Works only on visibility changes that are made by css class change, but can be extended to watch for attribute changes too.

var observer = new MutationObserver(function(mutations) {
        var clone = $(mutations[0].target).clone();
        clone.removeClass();
                for(var i = 0; i < mutations.length; i++){
                    clone.addClass(mutations[i].oldValue);
        }
        $(document.body).append(clone);
        var cloneVisibility = $(clone).is(":visible");
        $(clone).remove();
        if (cloneVisibility != $(mutations[0].target).is(":visible")){
            var visibilityChangedEvent = document.createEvent('Event');
            visibilityChangedEvent.initEvent('visibilityChanged', true, true);
            mutations[0].target.dispatchEvent(visibilityChangedEvent);
        }
});

var targets = $('.ui-collapsible-content');
$.each(targets, function(i,target){
        target.addEventListener('visibilityChanged',VisbilityChanedEventHandler});
        target.addEventListener('DOMNodeRemovedFromDocument',VisbilityChanedEventHandler });
        observer.observe(target, { attributes: true, attributeFilter : ['class'], childList: false, attributeOldValue: true });
    });

function VisbilityChanedEventHandler(e){console.log('Kaboom babe'); console.log(e.target); }

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

Any easy way to use icons from resources?

choosing that file, will embed the icon in the executable.

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

How to test if a file is a directory in a batch script?

This works:

if exist %1\* echo Directory

Works with directory names that contains spaces:

C:\>if exist "c:\Program Files\*" echo Directory
Directory

Note that the quotes are necessary if the directory contains spaces:

C:\>if exist c:\Program Files\* echo Directory

Can also be expressed as:

C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory

This is safe to try at home, kids!

Print the stack trace of an exception

See javadoc

out = some stream ...
try
{
}
catch ( Exception cause )
{
      cause . printStrackTrace ( new PrintStream ( out ) ) ;
}

Good Patterns For VBA Error Handling

Here's my standard implementation. I like the labels to be self-descriptive.

Public Sub DoSomething()

    On Error GoTo Catch ' Try
    ' normal code here

    Exit Sub
Catch:

    'error code: you can get the specific error by checking Err.Number

End Sub

Or, with a Finally block:

Public Sub DoSomething()

    On Error GoTo Catch ' Try

    ' normal code here

    GoTo Finally
Catch:

    'error code

Finally:

    'cleanup code

End Sub

Find non-ASCII characters in varchar columns using SQL Server

Here is a UDF I built to detectc columns with extended ascii charaters. It is quick and you can extended the character set you want to check. The second parameter allows you to switch between checking anything outside the standard character set or allowing an extended set:

create function [dbo].[udf_ContainsNonASCIIChars]
(
@string nvarchar(4000),
@checkExtendedCharset bit
)
returns bit
as
begin

    declare @pos int = 0;
    declare @char varchar(1);
    declare @return bit = 0;

    while @pos < len(@string)
    begin
        select @char = substring(@string, @pos, 1)
        if ascii(@char) < 32 or ascii(@char) > 126 
            begin
                if @checkExtendedCharset = 1
                    begin
                        if ascii(@char) not in (9,124,130,138,142,146,150,154,158,160,170,176,180,181,183,184,185,186,192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,209,210,211,212,213,214,216,217,218,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255)
                            begin
                                select @return = 1;
                                select @pos = (len(@string) + 1)
                            end
                        else
                            begin
                                select @pos = @pos + 1
                            end
                    end
                else
                    begin
                        select @return = 1;
                        select @pos = (len(@string) + 1)    
                    end
            end
        else
            begin
                select @pos = @pos + 1
            end
    end

    return @return;

end

USAGE:

select Address1 
from PropertyFile_English
where udf_ContainsNonASCIIChars(Address1, 1) = 1

Detecting iOS / Android Operating system

You also can create Firbase Dynamic links which will work as per your requirement. It supports multiple platforms. This link can be created, manually as well as via programming. You can then embed this link in QR code.

If the target app is installed, the link will redirect user to app. If its not installed it will redirect to Play Store/App store/Any other configured website.

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

The above could also be written with less code as:

new List<SomeType>(items).ForEach(
    i => Console.WriteLine(i)
);

This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.

Splitting string with pipe character ("|")

Using Pattern.quote()

String[] value_split = rat_values.split(Pattern.quote("|"));

//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)

Using Escape characters(for metacharacters)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)

Using StringTokenizer(For avoiding regular expression issues)

public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}

Using Pattern class(java.util.regex.Pattern)

Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)

Output

[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]

How do I create a user account for basic authentication?

It looks to me like Windows 8 and IIS 7 no longer provides any UI to create a user name and password for basic authentication that is NOT a windows local user account. It is clearly a superior approach to create an IIS-only user/password authentication pair, but it is not clear and easy how it is done.

Command line tools exist for this purpose. Some people create a Windows account and then remove the Log on Locally User Privilege.

How to create a directive with a dynamic template in AngularJS?

You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

It can be use like this:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

What is base 64 encoding used for?

It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end.

Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants.

Wikipedia is a reasonably good source of more information.

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

What can I use for good quality code coverage for C#/.NET?

I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit Test With→Coverage, and it will pull up the report.

Make <body> fill entire screen?

I tried all the solutions above and I'm not discrediting any of them, but in my case, they didn't work.

For me, the problem was caused because the <header> tag had a margin-top of 5em and the <footer> had a margin-bottom of 5em. I removed them and instead put some padding (top and bottom, respectively). I'm not sure if replacing the margin was an ideal fix to the problem, but the point is that, if the first and last elements in your <body> has some margins, you might want to look into it and remove them.

My html and body tags had the following styles

body {
  line-height: 1;
  min-height: 100%;
  position: relative; }

html {
  min-height: 100%;
  background-color: #3c3c3c; }

Deserializing JSON data to C# using JSON.NET

You can use:

JsonConvert.PopulateObject(json, obj);

here: json is the json string,obj is the target object. See: example

Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++)

It's a for loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.

for (int i = 0; i < 8; i++)

Start by setting i = 0

for (int i = 0; i < 8; i++)

Continue looping while i < 8.

for (int i = 0; i < 8; i++)

Every time you've been around the loop, increase i by 1.

For example;

for (int i = 0; i < 8; i++)
    do(i);

will call do(0), do(1), ... do(7) in order, and stop when i reaches 8 (ie i < 8 is false)

How to make an HTML back link?

This solution has the benefit of showing the URL of the linked-to page on hover, as most browsers do by default, instead of history.go(-1) or similar:

<script>
    document.write('<a href="' + document.referrer + '">Go Back</a>');
</script>

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

#1071 - Specified key was too long; max key length is 1000 bytes

I was facing same issue, used below query to resolve it.

While creating DB you can use utf-8 encoding

eg. create database my_db character set utf8 collate utf8mb4;

EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4

How to obtain the query string from the current URL with JavaScript?

  window.location.href.slice(window.location.href.indexOf('?') + 1);

How to create a zip archive of a directory in Python?

You probably want to look at the zipfile module; there's documentation at http://docs.python.org/library/zipfile.html.

You may also want os.walk() to index the directory structure.

Difference between Mutable objects and Immutable objects

They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.

chart.js load totally new data

I ran into the same issue, I have 6 pie charts on a page which can all be updated at the same time. I am using the following function to reset chart data.

_x000D_
_x000D_
// sets chart segment data for previously rendered charts_x000D_
function _resetChartData(chart, new_segments) {_x000D_
    // remove all the segments_x000D_
    while (chart.segments.length) {_x000D_
        chart.removeData();_x000D_
    };_x000D_
_x000D_
    // add the new data fresh_x000D_
    new_segments.forEach (function (segment, index) {_x000D_
        chart.addData(segment, index);_x000D_
    });_x000D_
};_x000D_
_x000D_
// when I want to reset my data I call_x000D_
_resetChartData(some_chart, new_data_segments);_x000D_
some_chart.update();
_x000D_
_x000D_
_x000D_

What Vim command(s) can be used to quote/unquote words?

I don't know any builtin vim command for this, but using r"f'r" to change from ' to " and r'f"r' to change from " to ' works if you stand on the first ' or ". The command r' replaces whatever character is under your cursor with ', and f" moves you forward to the next ".

How to Specify "Vary: Accept-Encoding" header in .htaccess

I guess it's meant that you enable gzip compression for your css and js files, because that will enable the client to receive both gzip-encoded content and a plain content.

This is how to do it in apache2:

<IfModule mod_deflate.c>
    #The following line is enough for .js and .css
    AddOutputFilter DEFLATE js css

    #The following line also enables compression by file content type, for the following list of Content-Type:s
    AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml

    #The following lines are to avoid bugs with some browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html 
</IfModule>

And here's how to add the Vary Accept-Encoding header: [src]

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

The Vary: header tells the that the content served for this url will vary according to the value of a certain request header. Here it says that it will serve different content for clients who say they Accept-Encoding: gzip, deflate (a request header), than the content served to clients that do not send this header. The main advantage of this, AFAIK, is to let intermediate caching proxies know they need to have two different versions of the same url because of such change.

"Submit is not a function" error in JavaScript

giving a form element a name of submit will simple shadow the submit property . make sure you don't have a form element with the name submit and you should be able to access the submit function just fine .

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

SQL: IF clause within WHERE clause

There isn't a good way to do this in SQL. Some approaches I have seen:

1) Use CASE combined with boolean operators:

WHERE
    OrderNumber = CASE 
        WHEN (IsNumeric(@OrderNumber) = 1)
        THEN CONVERT(INT, @OrderNumber)
        ELSE -9999 -- Some numeric value that just cannot exist in the column
    END
    OR 
    FirstName LIKE CASE
        WHEN (IsNumeric(@OrderNumber) = 0)
        THEN '%' + @OrderNumber
        ELSE ''
    END

2) Use IF's outside the SELECT

IF (IsNumeric(@OrderNumber)) = 1
BEGIN
    SELECT * FROM Table
    WHERE @OrderNumber = OrderNumber
END ELSE BEGIN
    SELECT * FROM Table
    WHERE OrderNumber LIKE '%' + @OrderNumber
END

3) Using a long string, compose your SQL statement conditionally, and then use EXEC

The 3rd approach is hideous, but it's almost the only think that works if you have a number of variable conditions like that.

Bootstrap: wider input field

I am going to assume you were having the same issue I was. Even though you specify larger sizes for the TextBox and mark it as important, the box would not get larger. That is likely because in your site.css file the MaxWidth is being set to 280px.

Add a style attribute to your input to remove the MaxWidth like this:

<input type="text"  style="max-width:none !important" class="input-medium">

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

String to HashMap JAVA

I recommend using com.fasterxml.jackson.databind.ObjectMapper (Maven repo link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core) like

final ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mapFromString = new HashMap<>();
try {
    mapFromString = mapper.readValue(theStringToParse, new TypeReference<Map<String, Object>>() {
        });
} catch (IOException e) {
    LOG.error("Exception launched while trying to parse String to Map.", e);
}

Unordered List (<ul>) default indent

I found the following removed the indent and the margin from both the left AND right sides, but allowed the bullets to remain left-justified below the text above it. Add this to your css file:

ul.noindent {
    margin-left: 5px;
    margin-right: 0px;
    padding-left: 10px;
    padding-right: 0px;
}

To use it in your html file add class="noindent" to the UL tag. I've tested w/FF 14 and IE 9.

I have no idea why browsers default to the indents, but I haven't really had a reason for changing them that often.

iPhone App Development on Ubuntu

There are two things I think you could try to develop iPhone applications.

  1. You can try the Aptana mobile wep app plugin for eclipse which is nice, although still in early stage. It comes with a emulator for running the applications so this could be helpful

  2. You can try cocoa

  3. (Extra) Here is a nice guide I found of guy who managed to get the iPhone SDK running in ubuntu, hope this help -_-. iPhone on Ubuntu

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

Select first occurring element after another element

Just hit on this when trying to solve this type of thing my self.

I did a selector that deals with the element after being something other than a p.

.here .is.the #selector h4 + * {...}

Hope this helps anyone who finds it :)

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

Android Failed to install HelloWorld.apk on device (null) Error

If unplugging the device and plugging it back in doesn't work, try increasing the upload timeout to something really huge like 20000 ms. It's at Window ? Preferences ? Android ? DDMS ? "ADB connection time out (ms)".

Connecting to Microsoft SQL server using Python

Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.

Python Code

import pandas as pd
import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()

Calling a Stored Procedure

 dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )

C# Program to Check ODBC Connection

    static void Main(string[] args)
    {
        string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;";
        OdbcConnection cn = new OdbcConnection(connectionString);
        cn.Open();
        cn.Close();
    }

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

Javascript - check array for value

Try this:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === value) {
        return i;
      }
    }

    return -1;
  }
}

// example
if ([1, 2, 3].indexOf(2) != -1) {
  // yay!
}

change background image in body

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

SHA1 vs md5 vs SHA256: which to use for a PHP login?

What people seem to be missing is that if the hacker has access to the database he probably also has access to the php file that hashes the password and can likely just modify that to send him all the successful user name password combos. If he doesn't have access to the web directory he could always just pick a password hash it, and write that into the database. In other words the hash algorithm doesn't really matter as much as system security, and limiting login attempts also if you don't use SSL then the attacker can just listen in on the connection to get the information. Unless you need the algorithm to take a long time to compute (for your own purposes) then SHA-256 or SHA-512 with a user specific salt should be enough.

As an added security measure set up a script (bash, batch, python, etc) or program and give it an obscure name and have it check and see if login.php has changed (check date/time stamp) and send you an email if it has. Also should probably log all attempts at login with admin rights and log all failed attempts to log into the database and have the logs emailed to you.

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

How to run a cron job on every Monday, Wednesday and Friday?

The rule would be:

0 19 * * 1,3,5

I suggest that you use http://corntab.com for having a very convenient GUI to create your rules in the future :)

How can I do GUI programming in C?

This is guaranteed to have nothing to do with the compiler. All compilers do is compile the code that they are given. What you're looking for is a GUI library, which you can write code against using any compiler that you want.

Of course, that being said, your first order of business should be to ditch Turbo C. That compiler is about 20 years old and continuing to use it isn't doing you any favors. You can't write modern GUI applications, as it will only produce 16-bit code. All modern operating systems are 32-bit, and many are now 64-bit. It's also worth noting that 64-bit editions of Windows will not run 16-bit applications natively. You'll need an emulator for that; it's not really going to engender much feeling of accomplishment if you can only write apps that work in a DOS emulator. :-)

Microsoft's Visual Studio Express C++ is available as a free download. It includes the same compiler available in the full version of the suite. The C++ package also compiles pure C code.

And since you're working in Windows, the Windows API is a natural choice. It allows you to write native Windows applications that have access to the full set of GUI controls. You'll find a nice tutorial here on writing WinAPI applications in C. If you choose to go with Visual Studio, it also includes boilerplate code for a blank WinAPI application that will get you up and running quickly.

If you really care about learning to do this, Charles Petzold's Programming Windows is the canonical resource of the subject, and definitely worth a read. The entire Windows API was written in C, and it's entirely possible to write full-featured Windows applications in C. You don't need no stinkin' C++.

That's the way I'd do it, at least. As the other answers suggest, GTK is also an option. But the applications it generates are just downright horrible-looking on Windows.


EDIT: Oh dear... It looks like you're not alone in wanting to write "GUI" applications using an antiquated compiler. A Google search turns up the following library: TurboGUI: A GUI Framework for Turbo C/C++:

 TurboGUI interface sample

If you're another one of those poor people stuck in the hopelessly out-of-date Indian school system and forced to use Turbo C to complete your education, this might be an option. I'm loathe to recommend it, as learning to work around its limitations will be completely useless to you once you graduate, but apparently it's out there for you if you're interested.

Why is there an unexplainable gap between these inline-block div elements?

The easiest fix is to just float the container. (eg. float: left;) On another note, each id should be unique, meaning you can't use the same id twice in the same HTML document. You should use classes instead, where you can use the same class for multiple elements.

.container {
    position: relative;
    background: rgb(255, 100, 0);
    margin: 0;
    width: 40%;
    height: 100px;
    float: left;
}

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

MySQL - How to select data by string length

You are looking for CHAR_LENGTH() to get the number of characters in a string.

For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters.

Why are arrays of references illegal?

Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.

Use boost::reference_wrapper, or boost::tuple instead; or just pointers.

How do I use reflection to invoke a private method?

Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):

obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);

Or as an extension method:

public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
    var type = typeof(T);
    var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
    return method.Invoke(obj, args);
}

Note:

  • If the desired method is in a superclass of obj the T generic must be explicitly set to the type of the superclass.

  • If the method is asynchronous you can use await (Task) obj.InvokeMethod(…).

Reset the Value of a Select Box

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

<form>
  <select>
    <option>one</option>
    <option>two</option>
    <option selected>three</option>
  </select>
  <input type="reset" value="Reset" />
</form>

Or, using JavaScript, it can be done in following way:

HTML Code:

<select>
  <option selected>one</option>
  <option>two</option>
  <option>three</option>
</select>
<button id="revert">Reset</button>

And JavaScript code:

const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;
  }
}

Both of these methods will work if you have multiple selected items or single selected item.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to add composite primary key to table

alter table d add constraint pkc_Name primary key (id, code)

should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

Convert decimal to binary in python

Without the 0b in front:

"{0:b}".format(int)

Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:

f"{int:b}"

How do I remove a MySQL database?

From the MySQL prompt:

mysql> drop database <db_name>;

How are echo and print different in PHP?

As the PHP.net manual suggests, take a read of this discussion.

One major difference is that echo can take multiple parameters to output. E.g.:

echo 'foo', 'bar';   // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error

If you're looking to evaluate the outcome of an output statement (as below) use print. If not, use echo.

$res = print('test');
var_dump($res); //bool(true)

Computational complexity of Fibonacci Sequence

Recursive algorithm's time complexity can be better estimated by drawing recursion tree, In this case the recurrence relation for drawing recursion tree would be T(n)=T(n-1)+T(n-2)+O(1) note that each step takes O(1) meaning constant time,since it does only one comparison to check value of n in if block.Recursion tree would look like

          n
   (n-1)      (n-2)
(n-2)(n-3) (n-3)(n-4) ...so on

Here lets say each level of above tree is denoted by i hence,

i
0                        n
1            (n-1)                 (n-2)
2        (n-2)    (n-3)      (n-3)     (n-4)
3   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)

lets say at particular value of i, the tree ends, that case would be when n-i=1, hence i=n-1, meaning that the height of the tree is n-1. Now lets see how much work is done for each of n layers in tree.Note that each step takes O(1) time as stated in recurrence relation.

2^0=1                        n
2^1=2            (n-1)                 (n-2)
2^2=4        (n-2)    (n-3)      (n-3)     (n-4)
2^3=8   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)    ..so on
2^i for ith level

since i=n-1 is height of the tree work done at each level will be

i work
1 2^1
2 2^2
3 2^3..so on

Hence total work done will sum of work done at each level, hence it will be 2^0+2^1+2^2+2^3...+2^(n-1) since i=n-1. By geometric series this sum is 2^n, Hence total time complexity here is O(2^n)

Print a file's last modified date in Bash

I wanted to get a file's modification date in YYYYMMDDHHMMSS format. Here is how I did it:

date -d @$( stat -c %Y myfile.css ) +%Y%m%d%H%M%S

Explanation. It's the combination of these commands:

stat -c %Y myfile.css # Get the modification date as a timestamp
date -d @1503989421 +%Y%m%d%H%M%S # Convert the date (from timestamp)

Select datatype of the field in postgres

The information schema views and pg_typeof() return incomplete type information. Of these answers, psql gives the most precise type information. (The OP might not need such precise information, but should know the limitations.)

create domain test_domain as varchar(15);

create table test (
  test_id test_domain, 
  test_vc varchar(15), 
  test_n numeric(15, 3), 
  big_n bigint,
  ip_addr inet
);

Using psql and \d public.test correctly shows the use of the data type test_domain, the length of varchar(n) columns, and the precision and scale of numeric(p, s) columns.

sandbox=# \d public.test
             Table "public.test"
 Column  |         Type          | Modifiers
---------+-----------------------+-----------
 test_id | test_domain           |
 test_vc | character varying(15) |
 test_n  | numeric(15,3)         |
 big_n   | bigint                |
 ip_addr | inet                  |

This query against an information_schema view does not show the use of test_domain at all. It also doesn't report the details of varchar(n) and numeric(p, s) columns.

select column_name, data_type 
from information_schema.columns 
where table_catalog = 'sandbox'
  and table_schema = 'public'
  and table_name = 'test';
 column_name |     data_type
-------------+-------------------
 test_id     | character varying
 test_vc     | character varying
 test_n      | numeric
 big_n       | bigint
 ip_addr     | inet

You might be able to get all that information by joining other information_schema views, or by querying the system tables directly. psql -E might help with that.

The function pg_typeof() correctly shows the use of test_domain, but doesn't report the details of varchar(n) and numeric(p, s) columns.

select pg_typeof(test_id) as test_id, 
       pg_typeof(test_vc) as test_vc,
       pg_typeof(test_n) as test_n,
       pg_typeof(big_n) as big_n,
       pg_typeof(ip_addr) as ip_addr
from test;
   test_id   |      test_vc      | test_n  | big_n  | ip_addr
-------------+-------------------+---------+--------+---------
 test_domain | character varying | numeric | bigint | inet

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

I know this is not the solution to OPs post. However, this post is the first one indexed by Google when I searched for answers to this error. For this reason I feel this will benefit others.

The following error...

The POST method is not supported for this route. Supported methods: GET, HEAD.

was caused by not clearing the routing cache

php artisan route:cache

Html.RenderPartial() syntax with Razor

@Html.Partial("NameOfPartialView")

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

Executing a stored procedure within a stored procedure

Here is an example of one of our stored procedures that executes multiple stored procedures within it:

ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]
(
    @AssetID AS uniqueidentifier
)
AS

SET NOCOUNT ON

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

EXEC AssetLibrary_AssetDeleteAttributes @AssetID
EXEC AssetLibrary_AssetDeleteComponents @AssetID
EXEC AssetLibrary_AssetDeleteAgreements @AssetID
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID

DELETE FROM
    AssetLibrary_Asset
WHERE
    AssetLibrary_Asset.AssetID = @AssetID

RETURN (@@ERROR)

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

SyntaxError: Use of const in strict mode?

If this is happening in nodejs, it is due to the older version of nodejs. Update node by using,

1) Clear NPM's cache:

sudo npm cache clean -f

2) Install a little helper called 'n'

sudo npm install -g n

3) Install latest stable NodeJS version

sudo n stable

Update nodejs instructions taken from, https://stackoverflow.com/a/19584407/698072

How to change legend title in ggplot

The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.

I am giving the complete answer of the question below.

 library(ggplot2)
 rating <- c(rnorm(200), rnorm(200, mean=.8))
 cond <-factor(rep(c("A", "B"), each = 200))
 df <- data.frame(cond,rating 
             )

 k<- ggplot(data=df, aes(x=rating, fill=cond))+ 
 geom_density(alpha = .3) +
 xlab("NEW RATING TITLE") +
 ylab("NEW DENSITY TITLE")

 # to change the cond to a different label
 k$labels$fill="New Legend Title"

 # to change the axis titles
 k$labels$y="Y Axis"
 k$labels$x="X Axis"
 k

I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used

k$labels$fill ="New Legend Title"

to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-

k$labels$size ="Size of points"

and it will change that label title.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Here's some working C++ code which solves the problem.

Proof that the memory constraints are satisfied:

Editor: There is no proof of the maximum memory requirements offered by the author either in this post or in his blogs. Since the number of bits necessary to encode a value depends on the values previously encoded, such a proof is likely non-trivial. The author notes that the largest encoded size he could stumble upon empirically was 1011732, and chose the buffer size 1013000 arbitrarily.

typedef unsigned int u32;

namespace WorkArea
{
    static const u32 circularSize = 253250;
    u32 circular[circularSize] = { 0 };         // consumes 1013000 bytes

    static const u32 stageSize = 8000;
    u32 stage[stageSize];                       // consumes 32000 bytes

    ...

Together, these two arrays take 1045000 bytes of storage. That leaves 1048576 - 1045000 - 2×1024 = 1528 bytes for remaining variables and stack space.

It runs in about 23 seconds on my Xeon W3520. You can verify that the program works using the following Python script, assuming a program name of sort1mb.exe.

from subprocess import *
import random

sequence = [random.randint(0, 99999999) for i in xrange(1000000)]

sorter = Popen('sort1mb.exe', stdin=PIPE, stdout=PIPE)
for value in sequence:
    sorter.stdin.write('%08d\n' % value)
sorter.stdin.close()

result = [int(line) for line in sorter.stdout]
print('OK!' if result == sorted(sequence) else 'Error!')

A detailed explanation of the algorithm can be found in the following series of posts:

Read next word in java

You can just use Scanner to read word by word, Scanner.next() reads the next word

try {
  Scanner s = new Scanner(new File(filename));

  while (s.hasNext()) {
    System.out.println("word:" + s.next());
  }
} catch (IOException e) {
  System.out.println("Error accessing input file!");
}

Connect Android Studio with SVN

You should open File/Settings/Version Control/Subversion and uncheck 3 options: Use command line client, Use system default Subversion configuration directory and Use system default Subversion configuration directory like http://screencast.com/t/rlh9H2WVpgo

And then go to network tab. Choose SSLv3 instead of All in the field SSL protocols like http://screencast.com/t/l5yw1jqOxV

Lastly, check in or out your source via svn. It works well

How to hide a View programmatically?

Try this:

linearLayout.setVisibility(View.GONE);

Format date and time in a Windows batch script

I did it this way:

REM Generate FileName from date and time in format YYYYMMTTHHMM

Time /T > Time.dat
set /P ftime= < Time.dat

set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log

echo %FileName%

LogFile201310170928.log

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case (quasar and command quasar dev for testing), I just forgot to restart dev Quasar command.

It seemed to me that components was automatically loaded when any change was done. But in this case, I reused component in another page and I got this message.

Laravel Eloquent compare date from datetime field

Have you considered using:

where('date', '<', '2014-08-11')

You should avoid using the DATE() function on indexed columns in MySQL, as this prevents the engine from using the index.

UPDATE

As there seems to be some disagreement about the importance of DATE() and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS.

How to get IntPtr from byte[] in C#

Here's a twist on @user65157's answer (+1 for that, BTW):

I created an IDisposable wrapper for the pinned object:

class AutoPinner : IDisposable
{
   GCHandle _pinnedArray;
   public AutoPinner(Object obj)
   {
      _pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
   }
   public static implicit operator IntPtr(AutoPinner ap)
   {
      return ap._pinnedArray.AddrOfPinnedObject(); 
   }
   public void Dispose()
   {
      _pinnedArray.Free();
   }
}

then use it like thusly:

using (AutoPinner ap = new AutoPinner(MyManagedObject))
{
   UnmanagedIntPtr = ap;  // Use the operator to retrieve the IntPtr
   //do your stuff
}

I found this to be a nice way of not forgetting to call Free() :)

How can I search Git branches for a file or directory?

git log + git branch will find it for you:

% git log --all -- somefile

commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date:   Tue Dec 16 14:16:22 2008 -0800

    added somefile


% git branch -a --contains 55d2069
  otherbranch

Supports globbing, too:

% git log --all -- '**/my_file.png'

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

Converting PKCS#12 certificate into PEM using OpenSSL

You just need to supply a password. You can do it within the same command line with the following syntax:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]

You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes

More info: http://www.openssl.org/docs/apps/pkcs12.html

Generating random, unique values C#

You might try shuffling an array of possible ints if your range is only 0 through 9. This adds the benefit of avoiding any conflicts in the number generation.

var nums = Enumerable.Range(0, 10).ToArray();
var rnd = new Random();

// Shuffle the array
for (int i = 0;i < nums.Length;++i)
{
    int randomIndex = rnd.Next(nums.Length);
    int temp = nums[randomIndex];
    nums[randomIndex] = nums[i];
    nums[i] = temp;
}

// Now your array is randomized and you can simply print them in order
for (int i = 0;i < nums.Length;++i)
    Console.WriteLine(nums[i]);

Command prompt won't change directory to another drive

The short answer

The correct way to go from C:\...\Adminto D:\Docs\Java drive, is the following command :

cd /d d:\Docs\Java

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

cd d:\

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

cd d:\Docs\Java

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

cd /d d:\

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

cd /d d:\Docs\Java

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

cd /d d:

As a shorthand for cd /d d:, you can also use this command :

d:

Having Django serve downloadable files

For a very simple but not efficient or scalable solution, you can just use the built in django serve view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production.

from django.views.static import serve
filepath = '/some/path/to/local/file.txt'
return serve(request, os.path.basename(filepath), os.path.dirname(filepath))

shell script to remove a file if it already exist

Another one line command I used is:

[ -e file ] && rm file

Create list of single item repeated N times

Itertools has a function just for that:

import itertools
it = itertools.repeat(e,n)

Of course itertools gives you a iterator instead of a list. [e] * n gives you a list, but, depending on what you will do with those sequences, the itertools variant can be much more efficient.

How do I escape a reserved word in Oracle?

double quotes worked in oracle when I had the keyword as one of the column name.

eg:

select t."size" from table t 

ant build.xml file doesn't exist

may be you can specify where the buildfile is located and then invoke desired action.

Eg: ant -file {BuildfileLocation/build.xml} -v

Is it possible to change the radio button icon in an android radio button group

Here's probably a quick approach,

enter image description here

With two icons shown above, you shall have a RadioGroup something like this

enter image description here

  • change the RadioGroup's orientation to horizontal
  • for each RadioButton's Properties, try giving the icon for Button under CompoundButton,
  • adjust the Padding and size,
  • and set the Background attribute when checked.

Does VBA contain a comment block syntax?

Although there isn't a syntax, you can still get close by using the built-in block comment buttons:

If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:

enter image description here

Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:

enter image description here

Fast and easy!

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

Switching between GCC and Clang/LLVM using CMake

According to the help of cmake:

-C <initial-cache>
     Pre-load a script to populate the cache.

     When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project.  This option may be used to specify a  file  from
     which to load cache entries before the first pass through the project's cmake listfiles.  The loaded entries take priority over the project's default values.  The given file should be a CMake
     script containing SET commands that use the CACHE option, not a cache-format file.

You make be able to create files like gcc_compiler.txt and clang_compiler.txt to includes all relative configuration in CMake syntax.

Clang Example (clang_compiler.txt):

 set(CMAKE_C_COMPILER "/usr/bin/clang" CACHE string "clang compiler" FORCE)

Then run it as

GCC:

cmake -C gcc_compiler.txt XXXXXXXX

Clang:

cmake -C clang_compiler.txt XXXXXXXX

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

How to add pandas data to an existing csv file?

A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
     file_to=open(path,mode)
     yield file_to
     file_to.close()


##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
      saved_df.to_csv('yourcsv.csv',mode='a',header=False)`

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

Is there a way to split a widescreen monitor in to two or more virtual monitors?

I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.

DbEntityValidationException - How can I easily tell what caused the error?

To quickly find a meaningful error message by inspecting the error during debugging:

  • Add a quick watch for:

    ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
    
  • Drill down into EntityValidationErrors like this:

    (collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

How can I force a long string without any blank to be wrapped?

For word-wrap:break-word; to work for me, I had to make sure the display was set to block, and that the width was set on the element. In Safari, it had to have a p tag and the width had to be set in ex.

How do you convert an entire directory with ffmpeg?

For giggles, here's solution in fish-shell:

for i in *.avi; ffmpeg -i "$i" (string split -r -m1 . $i)[1]".mp4"; end

How do you convert a JavaScript date to UTC?

Simple and stupid

var date = new Date(); 
var now_utc =  Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
 date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());

 return new Date(now_utc);

Use custom build output folder when using create-react-app

Open Command Prompt inside your Application's source. Run the Command

npm run eject

Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line

'use strict';
....
process.env.PUBLIC_URL = './' 
// Provide the current path
.....

enter image description here

Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)

module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}

enter image description here

Run

npm run build

Note: Running Platform dependent scripts are not advisable

How to run an EXE file in PowerShell with parameters with spaces and quotes

An alternative answer is to use a Base64 encoded command switch:

powershell -EncodedCommand "QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA=="

When decoded, you'll see it's the OP's original snippet with all arguments and double quotes preserved.

powershell.exe -EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.

The original command:

 C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"

It turns into this when encoded as Base64:

QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA==

and here is how to replicate at home:

$command = 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand

#  The clip below copies the base64 string to your clipboard for right click and paste.
$encodedCommand | Clip

What's the difference between map() and flatMap() methods in Java 8?

.map is for A -> B mapping

Stream.of("dog", "cat")              // stream of 2 Strings
    .map(s -> s.length())            // stream of 2 Integers: [3, 3]

it converts any item A to any item B. Javadoc


.flatMap is for A -> Stream< B> concatinating

Stream.of("dog", "cat")             // stream of 2 Strings
    .flatMapToInt(s -> s.chars())   // stream of 6 ints:      [d, o, g, c, a, t]

it --1 converts any item A into Stream< B>, then --2 concatenates all the streams into one (flat) stream. Javadoc


Note 1: Although the latter example flats to a stream of primitives (IntStream) instead of a stream of objects (Stream), it still illustrates the idea of the .flatMap.

Note 2: Despite the name, String.chars() method returns ints. So the actual collection will be: [100, 111, 103, 99, 97, 116] , where 100 is the code of 'd', 111 is the code of 'o' etc. Again, for illustrative purposes, it's presented as [d, o, g, c, a, t].

How do I set the selected item in a drop down box

My suggestion is to leverage the hidden/collapse attribute. Try with this example:

<select>
    <option value="echo $row[month]" selected disabled hidden><? echo $row[month] ?></option>
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
</select>

in case of null for $row[month] the selected item is blank and with data, it would contain less codes for many options and always working for HTML5 and bootstrap etc...

How to config routeProvider and locationProvider in angularJS?

The only issue I see are relative links and templates not being properly loaded because of this.

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.

In your case you can add a forward slash / in href attributes ($location.path does this automatically) and also to templateUrl when configuring routes. This avoids routes like example.com/tags/another and makes sure templates load properly.

Here's an example that works:

<div>
    <a href="/">Home</a> | 
    <a href="/another">another</a> | 
    <a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>

And

app.config(function($locationProvider, $routeProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/', {
      templateUrl: '/partials/template1.html', 
      controller: 'ctrl1'
    })
    .when('/tags/:tagId', {
      templateUrl: '/partials/template2.html', 
      controller:  'ctrl2'
    })
    .when('/another', {
      templateUrl: '/partials/template1.html', 
      controller:  'ctrl1'
    })
    .otherwise({ redirectTo: '/' });
});

If using Chrome you will need to run this from a server.

Android webview launches browser when calling loadurl

If you see an empty page, enable JavaScript.

webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);

Python Timezone conversion

Please note: The first part of this answer is or version 1.x of pendulum. See below for a version 2.x answer.

I hope I'm not too late!

The pendulum library excels at this and other date-time calculations.

>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.datetime.strptime(heres_a_time, '%Y-%m-%d %H:%M %z')
>>> for tz in some_time_zones:
...     tz, pendulum_time.astimezone(tz)
...     
('Europe/Paris', <Pendulum [1996-03-25T17:03:00+01:00]>)
('Europe/Moscow', <Pendulum [1996-03-25T19:03:00+03:00]>)
('America/Toronto', <Pendulum [1996-03-25T11:03:00-05:00]>)
('UTC', <Pendulum [1996-03-25T16:03:00+00:00]>)
('Canada/Pacific', <Pendulum [1996-03-25T08:03:00-08:00]>)
('Asia/Macao', <Pendulum [1996-03-26T00:03:00+08:00]>)

Answer lists the names of the time zones that may be used with pendulum. (They're the same as for pytz.)

For version 2:

  • some_time_zones is a list of the names of the time zones that might be used in a program
  • heres_a_time is a sample time, complete with a time zone in the form '-0400'
  • I begin by converting the time to a pendulum time for subsequent processing
  • now I can show what this time is in each of the time zones in show_time_zones

...

>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.from_format('1996-03-25 12:03 -0400', 'YYYY-MM-DD hh:mm ZZ')
>>> for tz in some_time_zones:
...     tz, pendulum_time.in_tz(tz)
...     
('Europe/Paris', DateTime(1996, 3, 25, 17, 3, 0, tzinfo=Timezone('Europe/Paris')))
('Europe/Moscow', DateTime(1996, 3, 25, 19, 3, 0, tzinfo=Timezone('Europe/Moscow')))
('America/Toronto', DateTime(1996, 3, 25, 11, 3, 0, tzinfo=Timezone('America/Toronto')))
('UTC', DateTime(1996, 3, 25, 16, 3, 0, tzinfo=Timezone('UTC')))
('Canada/Pacific', DateTime(1996, 3, 25, 8, 3, 0, tzinfo=Timezone('Canada/Pacific')))
('Asia/Macao', DateTime(1996, 3, 26, 0, 3, 0, tzinfo=Timezone('Asia/Macao')))

jQuery: keyPress Backspace won't fire?

According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)

In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.

jQuery(el).keydown( function() { 
    var that = this; setTimeout( function(){ 
           /** Code that processes backspace, etc. **/ 
     }, 100 );  
 } );

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

$_POST Array from html form

<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>


$id = implode(',',$_POST['id']);
echo $id

you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r.

print_r($_POST['id']);

How to return Json object from MVC controller to view

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>

PHP check if url parameter exists

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

What is meant with "const" at end of function declaration?

I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).

create a text file using javascript

From a web page this cannot work since IE restricts the use of that object.

Using regular expression in css?

You can' just add a class to each of your DIVs and apply the rule to the class in this way:

HTML:

<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>

CSS:

//css
.myclass
{
   ...
}

How to send post request with x-www-form-urlencoded body

For HttpEntity, the below answer works

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

For reference: How to POST form data with Spring RestTemplate?

What does 'public static void' mean in Java?

It means that:

  • public - it can be called from anywhere
  • static - it doesn't have any object state, so you can call it without instantiating an object
  • void - it doesn't return anything

You'd think that the lack of a return means it isn't doing much, but it might be saving things in the database, for example.

CSS selectors ul li a {...} vs ul > li > a {...}

ul > li > a selects only the direct children. In this case only the first level <a> of the first level <li> inside the <ul> will be selected.

ul li a on the other hand will select ALL <a>-s in ALL <li>-s in the unordered list

Example of ul > li

_x000D_
_x000D_
ul > li.bg {_x000D_
  background: red;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="bg">affected</li>_x000D_
  <li class="bg">affected</li>    _x000D_
  <li>_x000D_
    <ol>_x000D_
      <li class="bg">NOT affected</li>_x000D_
      <li class="bg">NOT affected</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

if you'd be using ul li - ALL of the li-s would be affected

UPDATE The order of more to less efficient CSS selectors goes thus:

  • ID, e.g.#header
  • Class, e.g. .promo
  • Type, e.g. div
  • Adjacent sibling, e.g. h2 + p
  • Child, e.g. li > ul
  • Descendant, e.g. ul a
  • Universal, i.e. *
  • Attribute, e.g. [type="text"]
  • Pseudo-classes/-elements, e.g. a:hover

So your better bet is to use the children selector instead of just descendant. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.

How do I connect to a specific Wi-Fi network in Android programmatically?

This is an activity you can subclass to force the connecting to a specific wifi: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/WifiActivity.java

You will need to subclass this activity and implement its methods:

public class SampleActivity extends WifiBaseActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  }

  @Override
  protected int getSecondsTimeout() {
      return 10;
  }

  @Override
  protected String getWifiSSID() {
      return "WifiNetwork";
  }

  @Override
  protected String getWifiPass() {
      return "123456";
  }
}

How do I navigate to a parent route from a child route?

To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19

   let routerLink = this._aRoute.parent.snapshot.pathFromRoot
        .map((s) => s.url)
        .reduce((a, e) => {
            //Do NOT add last path!
            if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
                return a.concat(e);
            }
            return a;
        })
        .map((s) => s.path);
    this._router.navigate(routerLink);

This has the added bonus of being an absolute route you can use with the singleton Router.

(Angular 4+ for sure, probably Angular 2 too.)

How to read values from properties file?

Another way is using a ResourceBundle. Basically you get the bundle using its name without the '.properties'

private static final ResourceBundle resource = ResourceBundle.getBundle("config");

And you recover any value using this:

private final String prop = resource.getString("propName");

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

UDP vs TCP, how much faster is it?

There has been some work done to allow the programmer to have the benefits of both worlds.

SCTP

It is an independent transport layer protolol, but it can be used as a library providing additional layer over UDP. The basic unit of communication is a message (mapped to one or more UDP packets). There is congestion control built in. The protocol has knobs and twiddles to switch on

  • in order delivery of messages
  • automatic retransmission of lost messages, with user defined parameters

if any of this is needed for your particular application.

One issue with this is that the connection establishment is a complicated (and therefore slow process)

Other similar stuff

One more similar proprietary experimental thing

This also tries to improve on the triple way handshake of TCP and change the congestion control to better deal with fast lines.

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

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

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

How to update a value, given a key in a hashmap?

One line solution:

map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);

New to MongoDB Can not run command mongo

This worked for me (if it applies that you also see the lock file):

first>youridhere@ubuntu:/var/lib/mongodb$ sudo service mongodb start 
then >youridhere@ubuntu:/var/lib/mongodb$ sudo rm mongod.lock*

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

How to urlencode data for curl command?

If you wish to run GET request and use pure curl just add --get to @Jacob's solution.

Here is an example:

curl -v --get --data-urlencode "access_token=$(cat .fb_access_token)" https://graph.facebook.com/me/feed

JavaScript Infinitely Looping slideshow with delays?

try this:

window.onload = function start() {
    slide();
}
function slide() {
     setInterval("document.getElementById('container').style.marginLeft='-600px'",3000);
     setInterval("document.getElementById('container').style.marginLeft='-1200px'",6000);
     setInterval("document.getElementById('container').style.marginLeft='-1800px'",9000);
     setInterval("document.getElementById('container').style.marginLeft='0px'",12000);
}

setInterval is basically an 'infinite loop' and it wont black up the browser. it waits the required time, then goes again

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

Break string into list of characters in Python

fO = open(filename, 'rU')
lst = list(fO.read())

Log all requests from the python-requests module

I'm using python 3.4, requests 2.19.1:

'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel

Convert list of ints to one number?

if the list contains only integer:

reduce(lambda x,y: x*10+y, list)

What does status=canceled for a resource mean in Chrome Developer Tools?

Another place we've encountered the (canceled) status is in a particular TLS certificate misconfiguration. If a site such as https://www.example.com is misconfigured such that the certificate does not include the www. but is valid for https://example.com, chrome will cancel this request and automatically redirect to the latter site. This is not the case for Firefox.

Currently valid example: https://www.pthree.org/

Java: Local variable mi defined in an enclosing scope must be final or effectively final

What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.

Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).

I would suggest two workarounds : Either you make your own class that implements actionlistenner and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.

Or (and this is probably the best solution) just qualify a copy of the variable final to access it in the inner scope as the error suggests to make it a constant:

This would suit your case since you are not modifying the value of the variable.

Transparent scrollbar with css

Just set display:none; as an attribute in your stylesheet ;)
It's way better than loading pictures for nothing.

body::-webkit-scrollbar {
  width: 9px;
  height: 9px;
}

body::-webkit-scrollbar-button:start:decrement,
body::-webkit-scrollbar-button:end:increment {
  display: block;
  height: 0;
  background-color: transparent;
}

body::-webkit-scrollbar-track-piece {
  background-color: #ffffff;
  opacity: 0.2;

  /* Here */
  display: none;

  -webkit-border-radius: 0;
  -webkit-border-bottom-right-radius: 14px;
  -webkit-border-bottom-left-radius: 14px;
}

body::-webkit-scrollbar-thumb:vertical {
  height: 50px;
  background-color: #333333;
  -webkit-border-radius: 8px;
}

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

Ant error when trying to build file, can't find tools.jar?

Java ships in 2 versions: JRE & SDK (used to be called JDK)

The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)

When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.

Log4j: How to configure simplest possible file logging?

Here's a simple one that I often use:

# Set up logging to include a file record of the output
# Note: the file is always created, even if there is 
# no actual output.
log4j.rootLogger=error, stdout, R

# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

The format of the log is as follows:

ERROR   [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
        http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.

Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n. You can read the meaning of conversion characters in log4j javadoc for PatternLayout.

Included comments should help in understanding what it does. Further notes:

  • it logs both to console and to file; in this case the file is named owls_conditions.log: change it according to your needs;
  • files are rotated when they reach 10000KB, and one back-up file is kept

There was no endpoint listening at (url) that could accept the message

go to webconfig page of your site, look for the tag endpoint, and check the port in the address attribute, maybe there was a change in the port number

How can I get the sha1 hash of a string in node.js?

Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.

How do I add a simple jQuery script to WordPress?

I know what you mean about the tutorials. Here's how I do it:

First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script> tags in a .js file).

Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:

jQuery(document).ready(function($) {
  $('#nav a').last().addClass('last');
})

Notice that I use jQuery and not $ at the start of the function.

Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script() function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.

WordPress questions can be asked over at WordPress Answers.

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

How to clear the cache of nginx?

You can add configuration in nginx.conf like the following.

...
http {
proxy_cache_path  /tmp/nginx_cache levels=1:2 keys_zone=my-test-cache:8m max_size=5000m inactive=300m;

server {
    proxy_set_header X- Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_cache my-test-cache;
    proxy_cache_valid  200 302  1m;
    proxy_cache_valid  404      60m;
    proxy_cache_use_stale   error timeout invalid_header updating;
    proxy_redirect off;

    ....
}
...
}

From above, a folder named "nginx_cache" is dynamicly created in /tmp/ to store cached content.

Left-pad printf with spaces

I use this function to indent my output (for example to print a tree structure). The indent is the number of spaces before the string.

void print_with_indent(int indent, char * string)
{
    printf("%*s%s", indent, "", string);
}

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}