Programs & Examples On #Report builder2.0

How to iterate through a table rows and get the cell values using jQuery

Looping through a table for each row and reading the 1st column value works by using JQuery and DOM logic.

var i = 0;
var t = document.getElementById('flex1');

$("#flex1 tr").each(function() {
    var val1 = $(t.rows[i].cells[0]).text();
    alert(val1) ;
    i++;
});

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

In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.

Just check the following snapshot.

enter image description here

For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179

Remember: you can avoid server rebooting using setup's SkipRules switch:

setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck

setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck

Populate dropdown select with array using jQuery

Since I cannot add this as a comment, I will leave it here for anyone who finds backticks to be easier to read. Its basically @Reigel answer but with backticks

var numbers = [1, 2, 3, 4, 5];
var option = ``;
for (var i=0;i<numbers.length;i++){
   option += `<option value=${numbers[i]}>${numbers[i]}</option>`;
}
$('#items').append(option);

Path.Combine absolute with relative path strings

Be careful with Backslashes, don't forget them (neither use twice:)

string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

Bash syntax error: unexpected end of file

I got this answer from this similar problem on StackOverflow

Open the file in Vim and try

:set fileformat=unix

Convert eh line endings to unix endings and see if that solves the issue. If editing in Vim, enter the command :set fileformat=unix and save the file. Several other editors have the ability to convert line endings, such as Notepad++ or Atom

Thanks @lemongrassnginger

Passing arguments to "make run"

You can explicitly extract each n-th argument in the command line. To do this, you can use variable MAKECMDGOALS, it holds the list of command line arguments given to 'make', which it interprets as a list of targets. If you want to extract n-th argument, you can use that variable combined with the "word" function, for instance, if you want the second argument, you can store it in a variable as follows:

second_argument := $(word 2, $(MAKECMDGOALS) )

Benefits of using the conditional ?: (ternary) operator

If you need multiple branches on the same condition, use an if:

if (A == 6)
  f(1, 2, 3);
else
  f(4, 5, 6);

If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );

Also, you can use the ternary operator in initialization.

const int i = (A == 6)? 1 : 4;

Doing that with if is very messy:

int i_temp;
if (A == 6)
   i_temp = 1;
else
   i_temp = 4;
const int i = i_temp;

You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

How do I convert uint to int in C#?

Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:

uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);

The destination type will blindly pick the 32 bits and reinterpret them.

Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:

uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);

In this case, you'll get overflow exceptions if:

  • casting a negative int (eg: -1) to an uint
  • casting a positive uint between 2,147,483,648 and 4,294,967,295 to an int

In our case, we wanted the unchecked solution to preserve the 32bits as-is, so here are some examples:

Examples

int => uint

int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)

uint => int

uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------

Code

int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };

foreach (var Int in testInts)
{
    uint asUint = unchecked((uint)Int);
    Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
    Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
    Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
    int asInt = unchecked((int)Uint);
    Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
    Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
    Console.WriteLine(new string('-', 30));
}  

Why is Git better than Subversion?

David Richards WANdisco Blog on Subversion / GIT

The emergence of GIT has brought with it a breed of DVCS fundamentalists – the ‘Gitterons’ – that think anything other than GIT is crap. The Gitterons seem to think software engineering happens on their own island and often forget that most organizations don’t employ senior software engineers exclusively. That’s ok but it’s not how the rest of the market thinks, and I am happy to prove it: GIT, at the last look had less than three per cent of the market while Subversion has in the region of five million users and about half of the overall market.

The problem we saw was that the Gitterons were firing (cheap) shots at Subversion. Tweets like “Subversion is so [slow/crappy/restrictive/doesn't smell good/looks at me in a funny way] and now I have GIT and [everything works in my life/my wife got pregnant/I got a girlfriend after 30 years of trying/I won six times running on the blackjack table]. You get the picture.

How to pad zeroes to a string?

I am adding how to use a int from a length of a string within an f-string because it didn't appear to be covered:

>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

It's complaining about

COUNT(DISTINCT dNum) AS ud 

inside the subquery. Only one column can be returned from the subquery unless you are performing an exists query. I'm not sure why you want to do a count on the same column twice, superficially it looks redundant to what you are doing. The subquery here is only a filter it is not the same as a join. i.e. you use it to restrict data, not to specify what columns to get back.

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

Local Storage vs Cookies

Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).

I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.

What are the rules for casting pointers in C?

You have a pointer to a char. So as your system knows, on that memory address there is a char value on sizeof(char) space. When you cast it up to int*, you will work with data of sizeof(int), so you will print your char and some memory-garbage after it as an integer.

Sending images using Http Post

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

cURL POST command line on WINDOWS RESTful service

Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:

{ "syncheader" : {
    "servertimesync" : "20131126121749",
    "deviceid" : "testDevice"
  }
}

then in my case I issue:

curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt

Keeps the json more readable too.

Easy way to make a confirmation dialog in Angular?

You could use sweetalert: https://sweetalert.js.org/guides/

npm install sweetalert --save

Then, simply import it into your application:

import swal from 'sweetalert';

If you pass two arguments, the first one will be the modal's title, and the second one its text.

swal("Here's the title!", "...and here's the text!");

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Release generating .pdb files, why?

Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.

You should not use <Link> outside a <Router>

Make it simple:

render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));

and don't forget: import { BrowserRouter } from "react-router-dom";

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

I was trying to install some site-packages like numpy, xgboost and so on, but this error showed up every time:

Fatal error in launcher: Unable to create process using

I've tried many ways to solve this problem and found this one, that successfully helped me:

python -m pip freeze

Hope it'll help someone too.

P.S. I found this solution here: https://stackoverflow.com/a/39733705/10310794

jQuery: How to detect window width on the fly?

Changing a variable doesn't magically execute code within the if-block. Place the common code in a function, then bind the event, and call the function:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);
    var $pane = $('#pane1');

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize > 440) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $pane.jScrollPane({
               scrollbarWidth:15, 
               scrollbarMargin:52
            });
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
});

How to support UTF-8 encoding in Eclipse

You can set an explicit Java default character encoding operating system-wide by setting the environment variable JAVA_TOOL_OPTIONS with the value -Dfile.encoding="UTF-8". Next time you start Eclipse, it should adhere to UTF-8 as the default character set.

See https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html

c# Best Method to create a log file

Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.

Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.

How to keep the header static, always on top while scrolling?

here is one with css + jquery (javascript) solution.

here is demo link Demo

//html

<div id="uberbar">
    <a href="#top">Top of Page</a>
    <a href="#bottom">Bottom of Page</a>

</div>

//css 

#uberbar    { 
    border-bottom:1px solid #eb7429; 
    background:#fc9453; 
    padding:10px 20px; 
    position:fixed; 
    top:0; 
    left:0; 
    z-index:2000; 
    width:100%;
}

//jquery

$(document).ready(function() {
    (function() {
        //settings
        var fadeSpeed = 200, fadeTo = 0.5, topDistance = 30;
        var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
        var inside = false;
        //do
        $(window).scroll(function() {
            position = $(window).scrollTop();
            if(position > topDistance && !inside) {
                //add events
                topbarML();
                $('#uberbar').bind('mouseenter',topbarME);
                $('#uberbar').bind('mouseleave',topbarML);
                inside = true;
            }
            else if (position < topDistance){
                topbarME();
                $('#uberbar').unbind('mouseenter',topbarME);
                $('#uberbar').unbind('mouseleave',topbarML);
                inside = false;
            }
        });
    })();
});

What happens to a declared, uninitialized variable in C? Does it have a value?

The basic answer is, yes it is undefined.

If you are seeing odd behavior because of this, it may depended on where it is declared. If within a function on the stack then the contents will more than likely be different every time the function gets called. If it is a static or module scope it is undefined but will not change.

How to turn off Wifi via ADB?

  1. go to location android/android-sdk/platform-tools
  2. shift+right click
  3. open cmd here and type the following commands

    1. adb shell
    2. su
    3. svc wifi enable/disable
  4. done!!!!!

Eclipse error ... cannot be resolved to a type

  1. Right click your project name.

  2. Click Properties.

  3. Click Java Build Path.

  4. Click on Add Class Folder.

  5. Then choose your class.

Alternatively, Add Jars should work although you claim that you attempted that.

Also, "have you tried turning it off and back on again"? (Restart Eclipse).

Synchronous request in Node.js

I actually got exactly what you (and me) wanted, without the use of await, Promises, or inclusions of any (external) library (except our own).

Here's how to do it:

We're going to make a C++ module to go with node.js, and that C++ module function will make the HTTP request and return the data as a string, and you can use that directly by doing:

var myData = newModule.get(url);

ARE YOU READY to get started?

Step 1: make a new folder somewhere else on your computer, we're only using this folder to build the module.node file (compiled from C++), you can move it later.

In the new folder (I put mine in mynewFolder/src for organize-ness):

npm init

then

npm install node-gyp -g

now make 2 new files: 1, called something.cpp and for put this code in it (or modify it if you want):

#pragma comment(lib, "urlmon.lib")
#include <sstream>
#include <WTypes.h>  
#include <node.h>
#include <urlmon.h> 
#include <iostream>
using namespace std;
using namespace v8;

Local<Value> S(const char* inp, Isolate* is) {
    return String::NewFromUtf8(
        is,
        inp,
        NewStringType::kNormal
    ).ToLocalChecked();
}

Local<Value> N(double inp, Isolate* is) {
    return Number::New(
        is,
        inp
    );
}

const char* stdStr(Local<Value> str, Isolate* is) {
    String::Utf8Value val(is, str);
    return *val;
}

double num(Local<Value> inp) {
    return inp.As<Number>()->Value();
}

Local<Value> str(Local<Value> inp) {
    return inp.As<String>();
}

Local<Value> get(const char* url, Isolate* is) {
    IStream* stream;
    HRESULT res = URLOpenBlockingStream(0, url, &stream, 0, 0);

    char buffer[100];
    unsigned long bytesReadSoFar;
    stringstream ss;
    stream->Read(buffer, 100, &bytesReadSoFar);
    while(bytesReadSoFar > 0U) {
        ss.write(buffer, (long long) bytesReadSoFar);
        stream->Read(buffer, 100, &bytesReadSoFar);
    }
    stream->Release();
    const string tmp = ss.str();
    const char* cstr = tmp.c_str();
    return S(cstr, is);
}

void Hello(const FunctionCallbackInfo<Value>& arguments) {
    cout << "Yo there!!" << endl;

    Isolate* is = arguments.GetIsolate();
    Local<Context> ctx = is->GetCurrentContext();

    const char* url = stdStr(arguments[0], is);
    Local<Value> pg = get(url,is);

    Local<Object> obj = Object::New(is);
    obj->Set(ctx,
        S("result",is),
        pg
    );
    arguments.GetReturnValue().Set(
       obj
    );

}

void Init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "get", Hello);
}

NODE_MODULE(cobypp, Init);

Now make a new file in the same directory called something.gyp and put (something like) this in it:

{
   "targets": [
       {
           "target_name": "cobypp",
           "sources": [ "src/cobypp.cpp" ]
       }
   ]
}

Now in the package.json file, add: "gypfile": true,

Now: in the console, node-gyp rebuild

If it goes through the whole command and says "ok" at the end with no errors, you're (almost) good to go, if not, then leave a comment..

But if it works then go to build/Release/cobypp.node (or whatever its called for you), copy it into your main node.js folder, then in node.js:

var myCPP = require("./cobypp")
var myData = myCPP.get("http://google.com").result;
console.log(myData);

..

response.end(myData);//or whatever

Set value of textarea in jQuery

You can even use the below snippet.

$("textarea#ExampleMessage").append(result.exampleMessage);

How to detect orientation change in layout in Android?

For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView in onConfigurationChanged method.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.yourxmlinlayout-land);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.yourxmlinlayoutfolder);
    }
}

If you have only one layout then no necessary to make setContentView in This method. simply

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

How to declare or mark a Java method as deprecated?

since some minor explanations were missing

Use @Deprecated annotation on the method like this

 /**
 * @param basePrice
 * 
 * @deprecated  reason this method is deprecated <br/>
 *              {will be removed in next version} <br/>
 *              use {@link #setPurchasePrice()} instead like this: 
 * 
 * 
 * <blockquote><pre>
 * getProduct().setPurchasePrice(200) 
 * </pre></blockquote>
 * 
 */
@Deprecated
public void setBaseprice(int basePrice) {
}

remember to explain:

  1. Why is this method no longer recommended. What problems arise when using it. Provide a link to the discussion on the matter if any. (remember to separate lines for readability <br/>
  2. When it will be removed. (let your users know how much they can still rely on this method if they decide to stick to the old way)
  3. Provide a solution or link to the method you recommend {@link #setPurchasePrice()}

How to repair a serialized string which has been corrupted by an incorrect byte count length?

The corruption in this question is isolated to a single substring at the end of the serialized string with was probably manually replaced by someone who lazily wanted to update the image filename. This fact will be apparent in my demonstration link below using the OP's posted data -- in short, C:fakepath100.jpg does not have a length of 19, it should be 17.

Since the serialized string corruption is limited to an incorrect byte/character count number, the following will do a fine job of updating the corrupted string with the correct byte count value.

The following regex based replacement will only be effective in remedying byte counts, nothing more.

It looks like many of the earlier posts are just copy-pasting a regex pattern from someone else. There is no reason to capture the potentially corrupted byte count number if it isn't going to be used in the replacement. Also, adding the s pattern modifier is a reasonable inclusion in case a string value contains newlines/line returns.

*For those that are not aware of the treatment of multibyte characters with serializing, you must not use mb_strlen() in the custom callback because it is the byte count that is stored not the character count, see my output...

Code: (Demo with OP's data) (Demo with arbitrary sample data) (Demo with condition replacing)

$corrupted = <<<STRING
a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";}
STRING;

$repaired = preg_replace_callback(
        '/s:\d+:"(.*?)";/s',
        //  ^^^- matched/consumed but not captured because not used in replacement
        function ($m) {
            return "s:" . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted
    );

echo $corrupted , "\n" , $repaired;
echo "\n---\n";
var_export(unserialize($repaired));

Output:

a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
Newline2";i:3;s:6:"garçon";}
a:4:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
Newline2";i:3;s:7:"garçon";}
---
array (
  0 => 'three',
  1 => 'five',
  2 => 'newline1
Newline2',
  3 => 'garçon',
)

One leg down the rabbit hole... The above works fine even if double quotes occur in a string value, but if a string value contains "; or some other monkeywrenching sbustring, you'll need to go a little further and implement "lookarounds". My new pattern

checks that the leading s is:

  • the start of the entire input string or
  • preceded by ;

and checks that the "; is:

  • at the end of the entire input string or
  • followed by } or
  • followed by a string or integer declaration s: or i:

I haven't test each and every possibility; in fact, I am relatively unfamiliar with all of the possibilities in a serialized string because I never elect to work with serialized data -- always json in modern applications. If there are additional possible leading or trailing characters, leave a comment and I'll extend the lookarounds.

Extended snippet: (Demo)

$corrupted_byte_counts = <<<STRING
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
STRING;

$repaired = preg_replace_callback(
        '/(?<=^|;)s:\d+:"(.*?)";(?=$|}|[si]:)/s',
        //^^^^^^^^--------------^^^^^^^^^^^^^-- some additional validation
        function ($m) {
            return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted_byte_counts
    );

echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired));

Output:

corrupted serialized array:
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
---
repaired serialized array:
a:12:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
newline2";i:3;s:7:"garçon";i:4;s:24:"double " quote \"escaped";i:5;s:7:"a,comma";i:6;s:7:"a:colon";i:7;s:13:"single 'quote";i:8;s:10:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:39:"monkey";wrenching doublequote-semicolon";s:2:"s:";s:10:"val s: val";}
---
Array
(
    [0] => three
    [1] => five
    [2] => newline1
newline2
    [3] => garçon
    [4] => double " quote \"escaped
    [5] => a,comma
    [6] => a:colon
    [7] => single 'quote
    [8] => semi;colon
    [assoc] => yes
    [9] => monkey";wrenching doublequote-semicolon
    [s:] => val s: val
)

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

Is recursion ever faster than looping?

Most of the answers here are wrong. The right answer is it depends. For example, here are two C functions which walks through a tree. First the recursive one:

static
void mm_scan_black(mm_rc *m, ptr p) {
    SET_COL(p, COL_BLACK);
    P_FOR_EACH_CHILD(p, {
        INC_RC(p_child);
        if (GET_COL(p_child) != COL_BLACK) {
            mm_scan_black(m, p_child);
        }
    });
}

And here is the same function implemented using iteration:

static
void mm_scan_black(mm_rc *m, ptr p) {
    stack *st = m->black_stack;
    SET_COL(p, COL_BLACK);
    st_push(st, p);
    while (st->used != 0) {
        p = st_pop(st);
        P_FOR_EACH_CHILD(p, {
            INC_RC(p_child);
            if (GET_COL(p_child) != COL_BLACK) {
                SET_COL(p_child, COL_BLACK);
                st_push(st, p_child);
            }
        });
    }
}

It's not important to understand the details of the code. Just that p are nodes and that P_FOR_EACH_CHILD does the walking. In the iterative version we need an explicit stack st onto which nodes are pushed and then popped and manipulated.

The recursive function runs much faster than the iterative one. The reason is because in the latter, for each item, a CALL to the function st_push is needed and then another to st_pop.

In the former, you only have the recursive CALL for each node.

Plus, accessing variables on the callstack is incredibly fast. It means you are reading from memory which is likely to always be in the innermost cache. An explicit stack, on the other hand, has to be backed by malloc:ed memory from the heap which is much slower to access.

With careful optimization, such as inlining st_push and st_pop, I can reach roughly parity with the recursive approach. But at least on my computer, the cost of accessing heap memory is bigger than the cost of the recursive call.

But this discussion is mostly moot because recursive tree walking is incorrect. If you have a large enough tree, you will run out of callstack space which is why an iterative algorithm must be used.

Search for a string in Enum and return the Enum

var color =  Enum.Parse<Colors>("Green");

How do I draw a set of vertical lines in gnuplot?

Here is a snippet from my perl script to do this:

print OUTPUT "set arrow from $x1,$y1 to $x1,$y2 nohead lc rgb \'red\'\n";

As you might guess from above, it's actually drawn as a "headless" arrow.

PHP decoding and encoding json with unicode characters

A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.

$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
    if(is_string($item)) {
        $item = htmlentities($item);
    }
});
$json = json_encode($array);

// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);

Chart.js v2 hide dataset labels

You can also put the tooltip onto one line by removing the "title":

this.chart = new Chart(ctx, {
    type: this.props.horizontal ? 'horizontalBar' : 'bar',
    options: {
        legend: {
            display: false,
        },
        tooltips: {
            callbacks: {
                label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`, 
                title: () => null,
            }
        },
    },
});

enter image description here

Hidden features of Windows batch files

For loops with numeric counters (outputs 1 through 10):

for /l %i in (1,1,10) do echo %i

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

How to call a method function from another class?

For calling the method of one class within the second class, you have to first create the object of that class which method you want to call than with the object reference you can call the method.

class A {
   public void fun(){
     //do something
   }
}

class B {
   public static void main(String args[]){
     A obj = new A();
     obj.fun();
   }
}

But in your case you have the static method in Date and TemperatureRange class. You can call your static method by using the class name directly like below code or by creating the object of that class like above code but static method ,mostly we use for creating the utility classes, so best way to call the method by using class name. Like in your case -

public static void main (String[] args){
  String dateVal = Date.date("01","11,"12"); // calling the date function by passing some parameter.

  String tempRangeVal = TemperatureRange.TempRange("80","20"); 
}

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How to get element by class name?

You need to use the document.getElementsByClassName('class_name');

and dont forget that the returned value is an array of elements so if you want the first one use:

document.getElementsByClassName('class_name')[0]

UPDATE

Now you can use:

document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)

or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).

docker container ssl certificates

I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD your certificate, then RUN update-ca-certificates. This way you will have a consistent state each time you start a container from this new image.

# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates

Let's say a docker build against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID, the container started by that command will have your certificate info. Simple and reproducible.

Animate change of view background color on Android

best way is to use ValueAnimator and ColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.setDuration(325);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

              view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
                                    , Color.parseColor("#000000")
                                    , fractionAnim));
        }
});
valueAnimator.start();

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Image Example

Prevent double submission of forms in jQuery

Why not just this -- this will submit the form but also disable the submitting button,

   $('#myForm').on('submit', function(e) {
       var clickedSubmit = $(this).find('input[type=submit]:focus');
       $(clickedSubmit).prop('disabled', true);
   });

Also, if you're using jQuery Validate, you can put these two lines under if ($('#myForm').valid()).

javascript compare strings without being case sensitive

Another method using a regular expression (this is more correct than Zachary's answer):

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

RegExp.test() will return true or false.

Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.

It might just be easier to use the string.toLowerCase() method.

So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.

There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php

This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

How to specify a multi-line shell variable?

read does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.

I use it like this

export LS_COLORS=$(printf %s    \
    ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33'   \
    ...
    ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')

in a file sourced from both my .bashrc and .zshrc.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

using javascript to detect whether the url exists before display in iframe

You could test the url via AJAX and read the status code - that is if the URL is in the same domain.

If it's a remote domain, you could have a server script on your own domain check out a remote URL.

Remove a cookie

Just set the expiration date to one hour ago, if you want to "remove" the cookie, like this:

setcookie ("TestCookie", "", time() - 3600);

or

setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);

Source: http://www.php.net/manual/en/function.setcookie.php

You should use the filter_input() function for all globals which a visitor can enter/manipulate, like this:

$visitors_ip = filter_input(INPUT_COOKIE, 'id');

You can read more about it here: http://www.php.net/manual/en/function.filter-input.php and here: http://www.w3schools.com/php/func_filter_input.asp

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Which ORM should I use for Node.js and MySQL?

May I suggest Node ORM?

https://github.com/dresende/node-orm2

There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.

MongoDB is available since version 2.1.x (released in July 2013)

UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize

How can I remove or replace SVG content?

You could also just use jQuery to remove the contents of the div that contains your svg.

$("#container_div_id").html("");

Constructors in JavaScript objects

It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming).

lunched-dan was closer but the example didn't work in jsFiddle.

This example creates a private constructor function that only runs during the creation of the object.

var color = 'black';

function Box()
{
   // private property
   var color = '';

   // private constructor 
   var __construct = function() {
       alert("Object Created.");
       color = 'green';
   }()

   // getter
   this.getColor = function() {
       return color;
   }

   // setter
   this.setColor = function(data) {
       color = data;
   }

}

var b = new Box();

alert(b.getColor()); // should be green

b.setColor('orange');

alert(b.getColor()); // should be orange

alert(color); // should be black

If you wanted to assign public properties then the constructor could be defined as such:

var color = 'black';

function Box()
{
   // public property
   this.color = '';

   // private constructor 
   var __construct = function(that) {
       alert("Object Created.");
       that.color = 'green';
   }(this)

   // getter
   this.getColor = function() {
       return this.color;
   }

   // setter
   this.setColor = function(color) {
       this.color = color;
   }

}

var b = new Box();

alert(b.getColor()); // should be green

b.setColor('orange'); 

alert(b.getColor()); // should be orange

alert(color); // should be black

jquery: get id from class selector

Be careful if you use fat arrow functions as you will get undefined for this.id Wasted 10 minutes today wondering what the hell was going on

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

If all you have is a public key from a user in PuTTY-style format, you can convert it to standard openssh format like so:

ssh-keygen -i -f keyfile.pub > newkeyfile.pub

References

Copy of article

I keep forgetting this so I'm gonna write it here. Non-geeks, just keep walking.

The most common way to make a key on Windows is using Putty/Puttygen. Puttygen provides a neat utility to convert a linux private key to Putty format. However, what isn't addressed is that when you save the public key using puttygen it won't work on a linux server. Windows puts some data in different areas and adds line breaks.

The Solution: When you get to the public key screen in creating your key pair in puttygen, copy the public key and paste it into a text file with the extension .pub. You will save you sysadmin hours of frustration reading posts like this.

HOWEVER, sysadmins, you invariably get the wonky key file that throws no error message in the auth log except, no key found, trying password; even though everyone else's keys are working fine, and you've sent this key back to the user 15 times.

ssh-keygen -i -f keyfile.pub > newkeyfile.pub

Should convert an existing puttygen public key to OpenSSH format.

Make an existing Git branch track a remote branch?

You can do the following (assuming you are checked out on master and want to push to a remote branch master):

Set up the 'remote' if you don't have it already

git remote add origin ssh://...

Now configure master to know to track:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

And push:

git push origin master

How do I find a default constraint using INFORMATION_SCHEMA?

Necromancing.
If you only need to check if a default-constraint exists
(default-constraint(s) may have different name in poorly-managed DBs),
use INFORMATION_SCHEMA.COLUMNS (column_default):

IF NOT EXISTS(
    SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE (1=1) 
    AND TABLE_SCHEMA = 'dbo' 
    AND TABLE_NAME = 'T_VWS_PdfBibliothek' 
    AND COLUMN_NAME = 'PB_Text'
    AND COLUMN_DEFAULT IS NOT NULL  
)
BEGIN 
    EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek 
                ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; 
    '); 
END 

If you want to check by the constraint-name only:

-- Alternative way: 
IF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL 
BEGIN
    -- constraint exists, deal with it.
END 

And last but not least, you can just create a view called
INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS:

CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS 
AS 
SELECT 
     DB_NAME() AS CONSTRAINT_CATALOG 
    ,csch.name AS CONSTRAINT_SCHEMA
    ,dc.name AS CONSTRAINT_NAME 
    ,DB_NAME() AS TABLE_CATALOG 
    ,sch.name AS TABLE_SCHEMA 
    ,syst.name AS TABLE_NAME 
    ,sysc.name AS COLUMN_NAME 
    ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION 
    ,dc.type_desc AS CONSTRAINT_TYPE 
    ,dc.definition AS COLUMN_DEFAULT 

    -- ,dc.create_date 
    -- ,dc.modify_date 
FROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where 
-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where 

INNER JOIN sys.tables AS syst 
    ON syst.object_id = sysc.object_id 

INNER JOIN sys.schemas AS sch
    ON sch.schema_id = syst.schema_id 

INNER JOIN sys.default_constraints AS dc 
    ON sysc.default_object_id = dc.object_id

INNER JOIN sys.schemas AS csch
    ON csch.schema_id = dc.schema_id 

WHERE (1=1) 
AND dc.is_ms_shipped = 0 

/*
WHERE (1=1) 
AND sch.name = 'dbo'
AND syst.name = 'tablename'
AND sysc.name = 'columnname'
*/

How does Java resolve a relative path in new File()?

On windows and Netbeans you can set the relative path as:

    new FileReader("src\\PACKAGE_NAME\\FILENAME");

On Linux and Netbeans you can set the relative path as:

    new FileReader("src/PACKAGE_NAME/FILENAME");

If you have your code inside Source Packages I do not know if it is the same for eclipse or other IDE

How to format a float in javascript?

_x000D_
_x000D_
countDecimals = value => {
    if (Math.floor(value) === value) return 0;
    let stringValue = value.toString().split(".")[1];
    if (stringValue) {
      return value.toString().split(".")[1].length
        ? value.toString().split(".")[1].length
        : 0;
    } else {
      return 0;
    }
  };
  
formatNumber=(ans)=>{
    let decimalPlaces = this.countDecimals(ans);
    ans = 1 * ans;
    if (decimalPlaces !== 0) {
      let onePlusAns = ans + 1;
      let decimalOnePlus = this.countDecimals(onePlusAns);
      if (decimalOnePlus < decimalPlaces) {
        ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
      } else {
        let tenMulAns = ans * 10;
        let decimalTenMul = this.countDecimals(tenMulAns);
        if (decimalTenMul + 1 < decimalPlaces) {
          ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
        }
      }
    }
}
_x000D_
_x000D_
_x000D_

I just add 1 to the value and count the decimal digits present in the original value and the added value. If I find the decimal digits after adding one less than the original decimal digits, I just call the toFixed() with (original decimals - 1). I also check by multiplying the original value by 10 and follow the same logic in case adding one doesn't reduce redundant decimal places. A simple workaround to handle floating-point number rounding in JS. Works in most cases I tried.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

javascript, is there an isObject function like isArray?

In jQuery there is $.isPlainObject() method for that:

Description: Check to see if an object is a plain object (created using "{}" or "new Object").

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

This is a useful article which graphically shows the explanation of the reset command.

https://git-scm.com/docs/git-reset

Reset --hard can be quite dangerous as it overwrites your working copy without checking, so if you haven't commited the file at all, it is gone.

As for Source tree, there is no way I know of to undo commits. It would most likely use reset under the covers anyway

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

PHP Unset Array value effect on other indexes

They are as they were. That one key is JUST DELETED

How can I use an array of function pointers?

This simple example for multidimensional array with function pointers":

void one( int a, int b){    printf(" \n[ ONE ]  a =  %d   b = %d",a,b);}
void two( int a, int b){    printf(" \n[ TWO ]  a =  %d   b = %d",a,b);}
void three( int a, int b){    printf("\n [ THREE ]  a =  %d   b = %d",a,b);}
void four( int a, int b){    printf(" \n[ FOUR ]  a =  %d   b = %d",a,b);}
void five( int a, int b){    printf(" \n [ FIVE ]  a =  %d   b = %d",a,b);}
void(*p[2][2])(int,int)   ;
int main()
{
    int i,j;
    printf("multidimensional array with function pointers\n");

    p[0][0] = one;    p[0][1] = two;    p[1][0] = three;    p[1][1] = four;
    for (  i  = 1 ; i >=0; i--)
        for (  j  = 0 ; j <2; j++)
            (*p[i][j])( (i, i*j);
    return 0;
}

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

load external URL into modal jquery ui dialog

Modals always load the content into an element on the page, which more often than not is a div. Think of this div as the iframe equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:

<!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" lang="en">

<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>

</head>

<body>

    <p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
    <div id="dialog"></div>
</body>

<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>

<script type="text/javascript">

$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
    showDialog();
    var titletext=$(this).attr("title");
    var openpage=$(this).attr("href");
    $("#dialog").dialog( "option", "title", titletext );
    $("#dialog").dialog( "option", "resizable", false );
    $("#dialog").dialog( "option", "buttons", { 
        "Close": function() { 
            $(this).dialog("close");
            $(this).dialog("destroy");
        } 
    });
    $("#dialog").load(openpage);
    return false;
});

//modal window end

//Modal Window Initiation start

function showDialog(){
    $("#dialog").dialog({
        height: 400,
        width: 500,
        modal: true 
    }
</script>

</html>

There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

How do I remove all non alphanumeric characters from a string except dash?

I´ve made a different solution, by eliminating the Control characters, which was my original problem.

It is better than putting in a list all the "special but good" chars

char[] arr = str.Where(c => !char.IsControl(c)).ToArray();    
str = new string(arr);

it´s simpler, so I think it´s better !

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If you have a manifest file which lists all the files that were installed with make install you can run this command which I have from another answer:

cat install_manifest.txt | xargs echo rm | sh

If you have sudo make install you will need to add a sudo to your uninstall:

cat install_manifest.txt | xargs echo sudo rm | sh

Example for boost shared_mutex (multiple reads/one write)?

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Using .stop() on the stream works on chrome when connected via http. It does not work when using ssl (https).

jQuery validate: How to add a rule for regular expression validation?

I got it to work like this:

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        return this.optional(element) || regexp.test(value);
    },
    "Please check your input."
);


$(function () {
    $('#uiEmailAdress').focus();
    $('#NewsletterForm').validate({
        rules: {
            uiEmailAdress:{
                required: true,
                email: true,
                minlength: 5
            },
            uiConfirmEmailAdress:{
                required: true,
                email: true,
                equalTo: '#uiEmailAdress'
            },
            DDLanguage:{
                required: true
            },
            Testveld:{
                required: true,
                regex: /^[0-9]{3}$/
            }
        },
        messages: {
            uiEmailAdress:{
                required: 'Verplicht veld',
                email: 'Ongeldig emailadres',
                minlength: 'Minimum 5 charaters vereist'
            },
            uiConfirmEmailAdress:{
                required: 'Verplicht veld',
                email: 'Ongeldig emailadres',
                equalTo: 'Veld is niet gelijk aan E-mailadres'
            },
            DDLanguage:{
                required: 'Verplicht veld'
            },
            Testveld:{
                required: 'Verplicht veld',
                regex: '_REGEX'
            }
        }
    });
});

Make sure that the regex is between / :-)

.bashrc: Permission denied

If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:

nano ~/.bashrc

or

gedit ~/.bashrc

And in general, for any type of file:

xdg-open ~/.bashrc

Writing only ~/.bashrc in terminal, this will try to execute that file, but .bashrc file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:

source ~/.bashrc

or simple:

. ~/.bashrc 

How to save/restore serializable object to/from file?

**1. Convert the json string to base64string and Write or append it to binary file. 2. Read base64string from binary file and deserialize using BsonReader. **

 public static class BinaryJson
{
    public static string SerializeToBase64String(this object obj)
    {
        JsonSerializer jsonSerializer = new JsonSerializer();
        MemoryStream objBsonMemoryStream = new MemoryStream();
        using (BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream))
        {
            jsonSerializer.Serialize(bsonWriterObject, obj);
            return Convert.ToBase64String(objBsonMemoryStream.ToArray());
        }           
        //return Encoding.ASCII.GetString(objBsonMemoryStream.ToArray());
    }
    public static T DeserializeToObject<T>(this string base64String)
    {
        byte[] data = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(data);
        using (BsonReader reader = new BsonReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }
    }
}

How do I get list of all tables in a database using TSQL?

SELECT * FROM INFORMATION_SCHEMA.TABLES 

OR

SELECT * FROM Sys.Tables

Why is &#65279; appearing in my HTML?

If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.

Split Div Into 2 Columns Using CSS

This is best answered here Question 211383

These days, any self-respecting person should be using the stated "micro-clearfix" approach of clearing floats.

ng-mouseover and leave to toggle item using mouse in angularjs

Here is example with only CSS for that. In example I'm using SASS and SLIM.

https://codepen.io/Darex1991/pen/zBxPxe

Slim:

a.btn.btn--joined-state
  span joined
  span leave

SASS:

=animate($property...)
  @each $vendor in ('-webkit-', '')
    #{$vendor}transition-property: $property
    #{$vendor}transition-duration: .3s
    #{$vendor}transition-timing-function: ease-in

=visible
  +animate(opacity, max-height, visibility)
  max-height: 150px
  opacity: 1
  visibility: visible

=invisible
  +animate(opacity, max-height, visibility)
  max-height: 0
  opacity: 0
  visibility: hidden

=transform($var)
  @each $vendor in ('-webkit-', '-ms-', '')
    #{$vendor}transform: $var

.btn
  border: 1px solid blue

  &--joined-state
    position: relative
    span
      +animate(opacity)

    span:last-of-type
      +invisible
      +transform(translateX(-50%))
      position: absolute
      left: 50%

    &:hover
      span:first-of-type
        +invisible
      span:last-of-type
        +visible
        border-color: blue

mysql extract year from date format

This should work:

SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;

eg:

SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y'));  /* shows "2009" */

printf and long double

printf and scanf function in C/C++ uses Microsoft C library and this library has no support for 10 byte long double. So when you are using printf and scanf function in your C/C++ code to print a long double as output and to take some input as a long double, it will always give you wrong result.

If you want to use long double then you have to use " __mingw_printf " and " __mingw_scanf " function instead of printf and scanf. It has support for 10 byte long double.

Or you can define two macro like this : " #define printf __mingw_printf " and " #define scanf __mingw_scanf "

Use standard format for long double : %Lf

How to disable phone number linking in Mobile Safari?

To disable phone number detection on part of a page, wrap the affected text in an anchor tag with href="#". If you do this, mobile Safari and UIWebView should leave it alone.

<a href="#"> 1234567 </a>

Xcode swift am/pm time to 24 hour format

Unfortunately apple priority the device date format, so in some cases against what you put, swift change your format to 12hrs

To fix this is necessary to use setLocalizedDateFormatFromTemplate instead of dateFormat an hide the AM and PM

let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss a")
formatter.amSymbol = ""
formatter.pmSymbol = ""
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var prettyDate = formatter.string(from: Date())

You can check a very useful post with more information detailed in https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift

How to debug a bash script?

Use eclipse with the plugins shelled & basheclipse.

https://sourceforge.net/projects/shelled/?source=directory https://sourceforge.net/projects/basheclipse/?source=directory

For shelled: Download the zip and import it into eclipse via help -> install new software : local archive For basheclipse: Copy the jars into dropins directory of eclipse

Follow the steps provides https://sourceforge.net/projects/basheclipse/files/?source=navbar

enter image description here

I wrote a tutorial with many screenshots at http://dietrichschroff.blogspot.de/2017/07/bash-enabling-eclipse-for-bash.html

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

Select query to remove non-numeric characters

Here's a version which pulls all digits from a string; i.e. given I'm 35 years old; I was born in 1982. The average family has 2.4 children. this would return 35198224. i.e. it's good where you've got numeric data which may have been formatted as a code (e.g. #123,456,789 / 123-00005), but isn't appropriate if you're looking to pull out specific numbers (i.e. as opposed to digits / just the numeric characters) from the text. Also it only handles digits; so won't return negative signs (-) or periods .).

declare @table table (id bigint not null identity (1,1), data nvarchar(max)) 
insert @table (data) 
values ('hello 123 its 45613 then') --outputs: 12345613
,('1 some other string 98 example 4') --outputs: 1984
,('AB ABCDE # 123') --outputs: 123 
,('ABCDE# 123') --outputs: 123
,('AB: ABC# 123') --outputs: 123
; with NonNumerics as (
    select id
    , data original
    --the below line replaces all digits with blanks
    , replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(data,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9','') nonNumeric
    from @table
)
--each iteration of the below CTE removes another non-numeric character from the original string, putting the result into the numerics column
, Numerics as (
    select id
    , replace(original, substring(nonNumeric,1,1), '') numerics
    , replace(nonNumeric, substring(nonNumeric,1,1), '') charsToreplace
    , len(replace(nonNumeric, substring(nonNumeric,1,1), '')) charsRemaining
    from NonNumerics

    union all

    select id
    , replace(numerics, substring(charsToreplace,1,1), '') numerics
    , replace(charsToreplace, substring(charsToreplace,1,1), '') charsToreplace
    , len(replace(charsToreplace, substring(charsToreplace,1,1), '')) charsRemaining
    from Numerics
    where charsRemaining > 0
)
--we select only those strings with `charsRemaining=0`; i.e. the rows for which all non-numeric characters have been removed; there should be 1 row returned for every 1 row in the original data set.
select * from Numerics where charsRemaining = 0

This code works by removing all the digits (i.e. the characters we want) from a the given strings by replacing them with blanks. Then it goes through the original string (which includes the digits) removing all of the characters that were left (i.e. the non-numeric characters), thus leaving only the digits.

The reason we do this in 2 steps, rather than just removing all non-numeric characters in the first place is there are only 10 digits, whilst there are a huge number of possible characters; so replacing that small list is relatively fast; then gives us a list of those non-numeric characters which actually exist in the string, so we can then replace that small set.

The method makes use of recursive SQL, using common table expressions (CTEs).

extract digits in a simple way from a python string

The simplest way to extract a number from a string is to use regular expressions and findall.

>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']

It might be that you need something more complex, but this is a good first step.

Note that you'll still have to call int on the result to get a proper numeric type (rather than another string):

>>> map(int, re.findall('\d+', s))
[300, 200, 439843]

How to get directory size in PHP

if you are hosted on Linux:

passthru('du -h -s ' . $DIRECTORY_PATH)

It's better than foreach

Getting value from table cell in JavaScript...not jQuery

A few problems:

  • The loop conditional in your for statements is an assignment, not a loop check, so it might infinite loop

  • You should use the item() function on those rows/cells collections, not sure if array index works on those (not actually JS arrays)

  • You should declare the row/col objects to ensure their scope is correct.

Here is an updated example:

var refTab=document.getElementById("ddReferences") 
var  ttl; 
// Loop through all rows and columns of the table and popup alert with the value 
// /content of each cell. 
for ( var i = 0; i<refTab.rows.length; i++ ) { 
  var row = refTab.rows.item(i); 
  for ( var j = 0; j<row.cells.length; j++ ) { 
    var col = row.cells.item(j);
    alert(col.firstChild.innerText); 
  } 
}

Replace innerText with innerHTML if you want HTML, not the text contents.

How can I output leading zeros in Ruby?

Can't you just use string formatting of the value before you concat the filename?

"%03d" % number

jQuery Dialog Box

Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:

$(document).ready({
    $('a.TOClink').click(function(){
        showTOC();
    });
});

function showTOC() {
    $('#example').dialog({modal:true});
}

A more concise example which accomplishes the desired effect using the jQuery UI dialog is:

   <div id="terms" style="display:none;">
       Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
   <a id="showTerms" href="#">Show Terms &amp; Conditions</a>      
   <script type="text/javascript">
       $(document).ready(function(){
           $('#showTerms').click(function(){
               $('#terms').dialog({modal:true});   
           });
       });
   </script>

How to create a notification with NotificationCompat.Builder?

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

Node.js client for a socket.io server

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

Iterating through map in template

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

Is there a way to change the spacing between legend items in ggplot2?

A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):

  scale_fill_manual(values=c("red","blue","white"),
                    labels=c("Label of category 1          ",
                             "Label of category 2          ",
                             "Label of category 3"))

JS search in object values

I've found a way that you can search in nested object like everything search , for example list of student that have nested lesson object:

_x000D_
_x000D_
var students=[{name:"ali",family:"romandeh",age:18,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]},_x000D_
   {name:"hadi",family:"porkar",age:48,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]},_x000D_
   {name:"majid",family:"porkar",age:30,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]}_x000D_
   ];_x000D_
  _x000D_
    function searchInChild(objects, toSearch){_x000D_
        var _finded=false;_x000D_
        for(var i=0; i<objects.length; i++) {_x000D_
            for(key in objects[i]) {_x000D_
                if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){_x000D_
                    if (typeof objects[i][key] == 'object') {_x000D_
                        _finded= searchInChild(objects[i][key],toSearch);_x000D_
_x000D_
                    }_x000D_
                    else if(objects[i][key].indexOf(toSearch)!=-1) {_x000D_
                        _finded=true;_x000D_
                    }_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
        return _finded;_x000D_
    }_x000D_
    function findNested(objects, toSearch) {_x000D_
        var _results=[];_x000D_
        for(var i=0; i<objects.length; i++) {_x000D_
            for(key in objects[i]) {_x000D_
                if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){_x000D_
                    if (typeof objects[i][key] == 'object') {_x000D_
                        if(searchInChild(objects[i][key],toSearch)){_x000D_
                            _results.push(objects[i]);_x000D_
                        }_x000D_
                    }_x000D_
                    else if(objects[i][key].indexOf(toSearch)!=-1) {_x000D_
                        _results.push(objects[i]);_x000D_
                    }_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return _results;_x000D_
_x000D_
    }_x000D_
    $('.quickSearch').on('click',function(){_x000D_
          var _inputSeach=$('#evertingSearch').val();_x000D_
          if(_inputSeach!=''){_x000D_
          var _finded=findNested(students,_inputSeach);_x000D_
          $('.count').html(_finded.length);}_x000D_
    _x000D_
    });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<span>_x000D_
<pre><code>_x000D_
       var students=[{name:"ali",family:"romandeh",age:18,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]},_x000D_
   {name:"hadi",family:"porkar",age:48,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]},_x000D_
   {name:"majid",family:"rezaeiye",age:30,curse:[_x000D_
   {lesson1:"arabic"},_x000D_
   {lesson2:"english"},_x000D_
   {lesson3:"history"}_x000D_
   ]}_x000D_
   ];_x000D_
</code></pre>_x000D_
_x000D_
<span>_x000D_
_x000D_
<input id="evertingSearch" placeholder="Search on students" />_x000D_
<input type="button" class="quickSearch" value="search" />_x000D_
<lable>count:</lable><span class="count"></span>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to append text to an existing file in Java?

Using java.nio.Files along with java.nio.file.StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.

The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.

Paths.get("path here") can be replaced with new File("path here").toPath(). And Charset.forName("charset name") can be modified to accommodate the desired Charset.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Had an issue similar to this, Ended up using UTF-16 to decode. my code is below.

with open(path_to_file,'rb') as f:
    contents = f.read()
contents = contents.rstrip("\n").decode("utf-16")
contents = contents.split("\r\n")

this would take the file contents as an import, but it would return the code in UTF format. from there it would be decoded and seperated by lines.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How do you resize a form to fit its content automatically?

This might be useful. It resizes a new form to a user control, and then anchors the user control to the new form:

Form f = new Form();
MyUserControl muc = new MyUserControl();
f.ClientSize = muc.Size;
f.Controls.Add(muc);
muc.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
f.ShowDialog();

How can I match on an attribute that contains a certain string?

Be aware that bobince's answer might be overly complicated if you can assume that the class name you are interested in is not a substring of another possible class name. If this is true, you can simply use substring matching via the contains function. The following will match any element whose class contains the substring 'atag':

//*[contains(@class,'atag')]

If the assumption above does not hold, a substring match will match elements you don't intend. In this case, you have to find the word boundaries. By using the space delimiters to find the class name boundaries, bobince's second answer finds the exact matches:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

This will match atag and not matag.

Safely override C++ virtual functions

Make the function abstract, so that derived classes have no other choice than to override it.

@Ray Your code is invalid.

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

Abstract functions cannot have bodies defined inline. It must be modified to become

class parent {
public:
  virtual void handle_event(int something) const = 0;
};

void parent::handle_event( int something ) { /* do w/e you want here. */ }

How do I open a Visual Studio project in design view?

My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

How do I find the install time and date of Windows?

After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see this link ) I wanted a method without an additional utility. I settled on the creation date of "C:\System Volume Information" and it seemed to check out in various cases.

One-line of PowerShell to get it is:

([DateTime](Get-Item -Force 'C:\System Volume Information\').CreationTime).ToString('MM/dd/yyyy')

how to check the dtype of a column in python pandas

I know this is a bit of an old thread but with pandas 19.02, you can do:

df.select_dtypes(include=['float64']).apply(your_function)
df.select_dtypes(exclude=['string','object']).apply(your_other_function)

http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.select_dtypes.html

How to check if there exists a process with a given pid in Python?

The answers involving sending 'signal 0' to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError due to permissions, even if the pid exists in the system.

In order to bypass this limitation you can check if /proc/<pid> exists:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

This applies to linux based systems only, obviously.

How to pass command line arguments to a shell alias?

Here's a simple example function using python. You can stick in ~/.bashrc
You gotta have a space after the first left curly bracket
The python command needs to be in double quotes to get the variable substitution
Don't forget that semicolon at the end

function count(){ python -c "for num in xrange($1):print num";}

$ count 6
0
1
2
3
4
5
$

How to show Snackbar when Activity starts?

A utils function for show snack bar

fun showSnackBar(activity: Activity, message: String, action: String? = null,
    actionListener: View.OnClickListener? = null, duration: Int = Snackbar.LENGTH_SHORT) {
    val snackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, duration)
        .setBackgroundColor(Color.parseColor("#CC000000")) // todo update your color
        .setTextColor(Color.WHITE)
    if (action != null && actionListener!=null) {
        snackBar.setAction(action, actionListener)
    }
    snackBar.show()
}

Example using in Activity

  showSnackBar(this, "No internet")
  showSnackBar(this, "No internet", duration = Snackbar.LENGTH_LONG)
  showSnackBar(activity, "No internet", "OK", View.OnClickListener { 
       // handle click 
  })

Example using in Fragment

  showSnackBar(getActivity(), "No internet")

Hope it help

Confused about __str__ on list in Python

It provides human readable version of output rather "Object": Example:

class Pet(object):

    def __init__(self, name, species):
        self.name = name
        self.species = species

    def getName(self):
        return self.name

    def getSpecies(self):
        return self.species

    def Norm(self):
        return "%s is a %s" % (self.name, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 

returns

<__main__.Pet object at 0x029E2F90>

while code with "str" return something different

class Pet(object):

    def __init__(self, name, species):
        self.name = name
        self.species = species

    def getName(self):
        return self.name

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (self.name, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 

returns:

jax is a human

Breaking out of nested loops

If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.

What is the difference between HTTP status code 200 (cache) vs status code 304?

For your last question, why ? I'll try to explain with what I know

A brief explanation of those three status codes in layman's terms.

  • 200 - success (browser requests and get file from server)

If caching is enabled in the server

  • 200 (from memory cache) - file found in browser, so browser is not going request from server
  • 304 - browser request a file but it is rejected by server

For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so

If a file is not expired then the browser will use from cache (200 cache).

If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.

look at this nginx configuration

location / {
    add_header Cache-Control must-revalidate;
    expires     60;
    etag on;

    ...
}

Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).

I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).

So, if the servers are configured with different expiring and caching headers (policies), the status may differ.

In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.

Does Java SE 8 have Pairs or Tuples?

Since Java 9, you can create instances of Map.Entry easier than before:

Entry<Integer, String> pair = Map.entry(1, "a");

Map.entry returns an unmodifiable Entry and forbids nulls.

C# using streams

A stream is an object used to transfer data. There is a generic stream class System.IO.Stream, from which all other stream classes in .NET are derived. The Stream class deals with bytes.

The concrete stream classes are used to deal with other types of data than bytes. For example:

  • The FileStream class is used when the outside source is a file
  • MemoryStream is used to store data in memory
  • System.Net.Sockets.NetworkStream handles network data

Reader/writer streams such as StreamReader and StreamWriter are not streams - they are not derived from System.IO.Stream, they are designed to help to write and read data from and to stream!

How to get process ID of background process?

You can use the jobs -l command to get to a particular jobL

^Z
[1]+  Stopped                 guard

my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18           guard

In this case, 46841 is the PID.

From help jobs:

-l Report the process group ID and working directory of the jobs.

jobs -p is another option which shows just the PIDs.

Difference between "read commited" and "repeatable read"

I think this picture can also be useful, it helps me as a reference when I want to quickly remember the differences between isolation levels (thanks to kudvenkat on youtube)

enter image description here

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

Get the string representation of a DOM node

You can simply use outerHTML property over the element. It will return what you desire.

Let's create a function named get_string(element)

_x000D_
_x000D_
var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

function get_string(element) {
 console.log(element.outerHTML);
}

get_string(el); // your desired output
_x000D_
_x000D_
_x000D_ enter image description here

nodejs module.js:340 error: cannot find module

While i tried to run my first node application i had encountered the same issue but when i tried to see what the issue might be it was the path of the file. I was running the node .js from different location and hence encountered the issue. When i fixed the path this worked fine.

Count the items from a IEnumerable<T> without iterating?

Going beyond your immediate question (which has been thoroughly answered in the negative), if you're looking to report progress whilst processing an enumerable, you might want to look at my blog post Reporting Progress During Linq Queries.

It lets you do this:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (sender, e) =>
      {
          // pretend we have a collection of 
          // items to process
          var items = 1.To(1000);
          items
              .WithProgressReporting(progress => worker.ReportProgress(progress))
              .ForEach(item => Thread.Sleep(10)); // simulate some real work
      };

Android turn On/Off WiFi HotSpot programmatically

We can programmatically turn on and off

setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);

Using callback class, to programmatically turn on hotspot in pie(9.0) u need to turn off programmatically and the switch on.

Swift days between two NSDates

You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).

If your purpose is to get the exact day number between two dates, you can work around this issue like this:

// Assuming that firstDate and secondDate are defined
// ...

let calendar = NSCalendar.currentCalendar()

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)

let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

components.day  // This will return the number of day(s) between dates

Swift 3 and Swift 4 Version

let calendar = Calendar.current

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)

let components = calendar.dateComponents([.day], from: date1, to: date2)

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

How to update record using Entity Framework 6?

I have the same problem when trying to update record using Attach() and then SaveChanges() combination, but I am using SQLite DB and its EF provider (the same code works in SQLServer DB without problem).

I found out, when your DB column has GUID (or UniqueIdentity) in SQLite and your model is nvarchar, SQLIte EF treats it as Binary(i.e., byte[]) by default. So when SQLite EF provider tries to convert GUID into the model (string in my case) it will fail as it will convert to byte[]. The fix is to tell the SQLite EF to treat GUID as TEXT (and therefore conversion is into strings, not byte[]) by defining "BinaryGUID=false;" in the connectionstring (or metadata, if you're using database first) like so:

  <connectionStrings>
    <add name="Entities" connectionString="metadata=res://savetyping...=System.Data.SQLite.EF6;provider connection string=&quot;data source=C:\...\db.sqlite3;Version=3;BinaryGUID=false;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Link to the solution that worked for me: How does the SQLite Entity Framework 6 provider handle Guids?

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

How to set the JDK Netbeans runs on?

Go to Tools -> Java Platforms. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25. You can either set the another JDK version or remove existing versions.

Another solution suggested in the oracle (sun) site is,

netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"

I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms dialog. Then, go to Run -> Set Project Configuration -> Customize. After that, in the opened Dialog box go to Build -> Compile. Set the version.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

However I have set the path as C:\Program Files\Java\jdk1.6.0_41 from eclipse Kepler toolbar->windows->preferences->java->installed jre

If you have already added JRE and still showing error. try follow

right click on your project

project->build path-> configure build path -> java build path -> libraries tab -> select JRE system library and click edit button -> If alternative JRE is selected choose workspace default JRE.

this is how my error gone.

How do you install an APK file in the Android emulator?

(TESTED ON MACOS)

The first step is to run the emulator

emulator -avd < avd_name>

then use adb to install the .apk

adb install < path to .apk file>

If adb throws error like APK already exists or something alike. Run the adb shell while emulator is running

adb shell

cd data/app

adb uninstall < apk file without using .apk>

If adb and emulator are commands not found do following

export PATH=$PATH://android-sdk-macosx/platform-tools://android-sdk-macosx/android-sdk-macosx/tools:

For future use put the above line at the end of .bash_profile

vi ~/.bash_profile

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

I had the exact same problem. Running mvn clean install instead of mvn clean compile resolved it. The difference only occurs when using multi-maven-project since the project dependencies are uploaded to the local repository by using install.

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I'm stumbling into the same issue. For me it seems to be caused by having 2 projects with the same name, one depending on the other.

For example, I have one project named Foo which produces Foo.lib. I then have another project that's also named Foo which produces Foo.exe and links in Foo.lib.

I watched the file activity w/ Process Monitor. What seems to be happening is Foo(lib) is built first--which is proper because Foo(exe) is marked as depending on Foo(lib). This is all fine and builds successfully, and is placed in the output directory--$(OutDir)$(TargetName)$(TargetExt). Then Foo(exe) is triggered to rebuild. Well, a rebuild is a clean followed by a build. It seems like the 'clean' stage of Foo.exe is deleting Foo.lib from the output directory. This also explains why a subsequent 'build' works--that doesn't delete output files.

A bug in VS I guess.

Unfortunately I don't have a solution to the problem as it involves Rebuild. A workaround is to manually issue Clean, and then Build.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

try the following query.

select object_name(sfc.constraint_object_id) AS constraint_name,
       OBJECT_Name(parent_object_id) AS table_name ,
       ac1.name as table_column_name,
       OBJECT_name(referenced_object_id) as reference_table_name,      
       ac2.name as reference_column_name
from  sys.foreign_key_columns sfc
join sys.all_columns ac1 on (ac1.object_id=sfc.parent_object_id and ac1.column_id=sfc.parent_column_id)
join sys.all_columns ac2 on (ac2.object_id=sfc.referenced_object_id and ac2.column_id=sfc.referenced_column_id) 
where sfc.parent_object_id=OBJECT_ID(<main table name>);

this will give the constraint_name, column_names which will be referring and tables which will be depending on the constraint will be there.

cleanup php session files

In case someone want's to do this with a cronjob, please keep in mind that this:

find .session/ -atime +7  -exec rm {} \;

is really slow, when having a lot of files.

Consider using this instead:

find .session/ -atime +7 | xargs -r rm

In Case you have spaces in you file names use this:

find .session/ -atime +7 -print0 | xargs -0 -r rm

xargs will fill up the commandline with files to be deleted, then run the rm command a lot lesser than -exec rm {} \;, which will call the rm command for each file.

Just my two cents

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

How to parse JSON string in Typescript

You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:

import { Field } from "sparkson";
class Response {
   constructor(
      @Field("name") public name: string,
      @Field("error") public error: boolean
   ) {}
}

The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.

How to write log to file

os.Open() must have worked differently in the past, but this works for me:

f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()

log.SetOutput(f)
log.Println("This is a test log entry")

Based on the Go docs, os.Open() can't work for log.SetOutput, because it opens the file "for reading:"

func Open

func Open(name string) (file *File, err error) Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

EDIT

Moved defer f.Close() to after if err != nil check

Where is SQL Profiler in my SQL Server 2008?

Management Studio->Tools->SQL Server Profiler.

If it is not installed see this link

Python: Random numbers into a list

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

Showing Difference between two datetime values in hours

WOW, I gotta say: keep it simple:

MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));

Result: True

and:

MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));

Result: 10.00:00:00

The DateTime object has all the builtin logic to handle the Boolean result.

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

How do I convert a Swift Array to a String?

use this when you want to convert list of struct type into string

struct MyStruct {
  var name : String
  var content : String
}

let myStructList = [MyStruct(name: "name1" , content: "content1") , MyStruct(name: "name2" , content: "content2")]

and covert your array like this way

let myString = myStructList.map({$0.name}).joined(separator: ",")

will produce ===> "name1,name2"

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

How to scroll to the bottom of a UITableView on the iPhone before the view appears

If you have to load the data asynchronously prior to scrolling down, here's the possible solution:

tableView.alpha = 0 // We want animation!
lastMessageShown = false // This is ivar

viewModel.fetch { [unowned self] result in
    self.tableView.reloadData()

    if !self.lastMessageShown {
        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            if self.rowCount > 0 {
                self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: self.rowCount, inSection: 0), atScrollPosition: .Bottom, animated: false)
            }

            UIView.animateWithDuration(0.1) {
                self.tableView.alpha = 1
                self.lastMessageShown = true // Do it once
            }
        }
    }
}

How to keep environment variables when using sudo

You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"

You should also consider specifying env_keep for only a single command like this:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"

Error in plot.new() : figure margins too large in R

enter image description here

Just zoom this area if you use RStudio.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How do I get an OAuth 2.0 authentication token in C#

Clearly:

Server side generating a token example

private string GenerateToken(string userName)
{
    var someClaims = new Claim[]{
        new Claim(JwtRegisteredClaimNames.UniqueName, userName),
        new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
        new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
    };

    SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
    var token = new JwtSecurityToken(
        issuer: _settings.Tokenizer.Issuer,
        audience: _settings.Tokenizer.Audience,
        claims: someClaims,
        expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

(note: Tokenizer is my helper class that contains Issuer Audience etc..)

Definitely:

Client side getting a token for authentication

    public async Task<string> GetToken()
    {
        string token = "";
        var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();

        var client = new HttpClient();
        client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StatisticUserModel user = new StatisticUserModel()
        {
            Password = siteSettings.PopularSearchRequest.Password,
            Username = siteSettings.PopularSearchRequest.Username
        };

        string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
        var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
        token = await response.Content.ReadAsStringAsync();

        return token;
    }

You can use this token for the authorization (that is in the subsequent requests)

Hive insert query like SQL

Enter the following command to insert data into the testlog table with some condition:

INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

How to enable CORS in ASP.NET Core

If you are hosting on IIS, one possible reason is you are getting this is because IIS is blocking OPTIONS verb. I spent almost an hour because of this:

One telltale indication is you are getting 404 error during OPTIONS request.

To fix this, you need to explicitly tell IIS not to block OPTIONS request.

Go to Request Filtering:

IIS Request Filtering

Make sure OPTIONS is allowed:

Make sure OPTIONS is True

Or, just create a web.config with the following setting:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>

Get all directories within directory nodejs

If you need to use all async version. You can have something like this.

  1. Record the directory length, uses it as an indicator to tell if all async stat tasks are finished.

  2. If the async stat tasks are finished, all the file stat has been checked, so call the callback

This will only work as long as Node.js is single thread, because it assumes no two async tasks will increase the counter at the same time.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    files.forEach((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        fs.stat(fullPath, (err, stat) => {
            // this will work because Node.js is single thread
            // therefore, the counter will not increment at the same time by two callback
            finished++;

            if (stat.isFile()) {
                results.push({
                    fileName: fileName,
                    isFile: stat.isFile()
                });
            }

            if (finished == total) {
                result_callback(results);
            }
        });
    });
});

As you can see, this is a "depth first" approach, and this could result in callback hell, and it is not quite "functional" . People try to solve this problem with Promise, by wrapping the async task into an Promise object.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    var promises = files.map((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        return new Promise((resolve, reject) => {
            // try to replace fullPath wil "aaa", it will reject
            fs.stat(fullPath, (err, stat) => {
                if (err) {
                    reject(err);
                    return;
                }

                var obj = {
                    fileName: fileName,
                    isFile: stat.isFile()
                };

                resolve(obj);
            });
        });
    });

    Promise.all(promises).then((values) => {
        console.log("All the promise resolved");
        console.log(values);
        console.log("Filter out folder: ");
        values
            .filter((obj) => obj.isFile)
            .forEach((obj) => {
                console.log(obj.fileName);
            });
    }, (reason) => {
        console.log("Not all the promise resolved");
        console.log(reason);
    });
});

How to refresh an access form

to refresh the form you need to type - me.refresh in the button event on click

java.util.Date and getYear()

Don't use Date, use Calendar:

// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR);  // 2012
int month = date.get(Calendar.MONTH);  // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH);  // 5

It supports time as well:

Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY);  // 15
int minute = dateTime.get(Calendar.MINUTE);  // 16
int second = dateTime.get(Calendar.SECOND);  // 17

What is the difference between a token and a lexeme?

LEXEME - Sequence of characters matched by PATTERN forming the TOKEN

PATTERN - The set of rule that define a TOKEN

TOKEN - The meaningful collection of characters over the character set of the programming language ex:ID, Constant, Keywords, Operators, Punctuation, Literal String

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

A very simple solution: replace https:// with git://

Use git://the.repository instead of https://the.repository and will work.

I've had this problem on Windows with TortoiseGit and this solved it.

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

What's the difference between lists enclosed by square brackets and parentheses in Python?

Square brackets are lists while parentheses are tuples.

A list is mutable, meaning you can change its contents:

>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]

while tuples are not:

>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:

>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Note that, as many people have pointed out, you can add tuples together. For example:

>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)

However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:

>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)

Whereas, if you were to construct this same example with a list, y would also be updated:

>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]

Optimistic vs. Pessimistic locking

In most cases, optimistic locking is more efficient and offers higher performance. When choosing between pessimistic and optimistic locking, consider the following:

  • Pessimistic locking is useful if there are a lot of updates and relatively high chances of users trying to update data at the same time. For example, if each operation can update a large number of records at a time (the bank might add interest earnings to every account at the end of each month), and two applications are running such operations at the same time, they will have conflicts.

  • Pessimistic locking is also more appropriate in applications that contain small tables that are frequently updated. In the case of these so-called hotspots, conflicts are so probable that optimistic locking wastes effort in rolling back conflicting transactions.

  • Optimistic locking is useful if the possibility for conflicts is very low – there are many records but relatively few users, or very few updates and mostly read-type operations.

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

php date validation

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

Filter dataframe rows if value in column is in a set list of values

Use the isin method:

rpt[rpt['STK_ID'].isin(stk_list)]

How to view unallocated free space on a hard disk through terminal

Use GNU parted and print free command:

root@sandbox:~# parted
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print free
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 64.4GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type      File system  Flags
        32.3kB  1049kB  1016kB            Free Space
 1      1049kB  256MB   255MB   primary   ext2         boot
        256MB   257MB   1048kB            Free Space
 2      257MB   64.4GB  64.2GB  extended
 5      257MB   64.4GB  64.2GB  logical                lvm
        64.4GB  64.4GB  1049kB            Free Space

How to set root password to null

Worked for me and "5.7.11 MySQL Community Server":

use mysql;
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';

I had to change the 'plugin' field as well because it was set to 'auth_socket'.

After that I could connect as mysql -u root without a password.

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

How to save DataFrame directly to Hive?

You can create an in-memory temporary table and store them in hive table using sqlContext.

Lets say your data frame is myDf. You can create one temporary table using,

myDf.createOrReplaceTempView("mytempTable") 

Then you can use a simple hive statement to create table and dump the data from your temp table.

sqlContext.sql("create table mytable as select * from mytempTable");

Cast received object to a List<object> or IEnumerable<object>

Do you actually need more information than plain IEnumerable gives you? Just cast it to that and use foreach with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable (or IList to access it like a list) works very well.

invalid use of non-static data member

In C++, nested classes are not connected to any instance of the outer class. If you want bar to access non-static members of foo, then bar needs to have access to an instance of foo. Maybe something like:

class bar {
  public:
    int getA(foo & f ) {return foo.a;}
};

Or maybe

class bar {
  private:
    foo & f;

  public:
    bar(foo & g)
    : f(g)
    {
    }

    int getA() { return f.a; }
};

In any case, you need to explicitly make sure you have access to an instance of foo.

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...