Programs & Examples On #Syswow64

The %windir%\System32 directory is reserved for 64-bit applications. Most DLL file names were not changed when 64-bit versions of the DLLs were created, so 32-bit versions of the DLLs are stored in a different directory. WOW64 hides this difference by using a file system redirector.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.

SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.

This article explains a bit:

"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."

Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.

Running vbscript from batch file

You can use %~dp0 to get the path of the currently running batch file.

Edited to change directory to the VBS location before running

If you want the VBS to synchronously run in the same window, then

@echo off
pushd %~dp0
cscript necdaily.vbs

If you want the VBS to synchronously run in a new window, then

@echo off
pushd %~dp0
start /wait "" cmd /c cscript necdaily.vbs

If you want the VBS to asynchronously run in the same window, then

@echo off
pushd %~dp0
start /b "" cscript necdaily.vbs

If you want the VBS to asynchronously run in a new window, then

@echo off
pushd %~dp0
start "" cmd /c cscript necdaily.vbs

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

Class constants in python

You can get to SIZES by means of self.SIZES (in an instance method) or cls.SIZES (in a class method).

In any case, you will have to be explicit about where to find SIZES. An alternative is to put SIZES in the module containing the classes, but then you need to define all classes in a single module.

Running interactive commands in Paramiko

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

Checking for multiple conditions using "when" on single task in ansible

Also you can use default() filter. Or just a shortcut d()

- name: Generating a new SSH key for the current user it's not exists already
  local_action:
    module: user
    name: "{{ login_user.stdout }}"
    generate_ssh_key: yes 
    ssh_key_bits: 2048
  when: 
    - sshkey_result.rc == 1
    - github_username | d('none') | lower == 'none'

What is a good Hash Function?

A good hash function should

  1. be bijective to not loose information, where possible, and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.
  3. if used in a cryptographic context there should not exist an efficient way to invert it.

A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).

To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.

Useful permutations, among others, are:

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.

If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:

First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k many applications of (n*(n+1)/2) mod 2^k interspersed with an xorshift when k is the number of bits in the resulting hash.

Creating and appending text to txt file in VB.NET

Try this:

Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
    sw.WriteLine( _
        IIf(fileExists, _
            "Error Message in  Occured at-- " & DateTime.Now, _
            "Start Error Log for today"))
End Using

c++ compile error: ISO C++ forbids comparison between pointer and integer

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

Replace forward slash "/ " character in JavaScript string?

Just use the split - join approach:

my_string.split('/').join('replace_with_this')

Split function in oracle to comma separated values with automatic sequence

Use this 'Split' function:

CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sys_refcursor is
v_res sys_refcursor;

begin
  open v_res for 
  WITH TAB AS 
  (SELECT p_str STR FROM DUAL)
  select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name 
  from
    ( select ',' || STR || ',' as STR from TAB ),
    ( select level as lvl from dual connect by level <= 100 )
    where lvl <= length(STR) - length(replace(STR, ',')) - 1;

     return v_res;
   end;

You can't use this function in select statement like you described in question, but I hope you will find it still useful.

EDIT: Here are steps you need to do. 1. Create Object: create or replace type empy_type as object(value varchar2(512)) 2. Create Type: create or replace type t_empty_type as table of empy_type 3. Create Function:

CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sms.t_empty_type is
v_emptype t_empty_type := t_empty_type();
v_cnt     number := 0;
v_res sys_refcursor;
v_value nvarchar2(128);
begin
  open v_res for
  WITH TAB AS
  (SELECT p_str STR FROM DUAL)
  select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl +     1) - instr(STR, ',', 1, lvl) - 1) name
  from
    ( select ',' || STR || ',' as STR from TAB ),
    ( select level as lvl from dual connect by level <= 100 )
    where lvl <= length(STR) - length(replace(STR, ',')) - 1;


  loop
     fetch v_res into v_value;
      exit when v_res%NOTFOUND;
      v_emptype.extend;
      v_cnt := v_cnt + 1;
     v_emptype(v_cnt) := empty_type(v_value);
    end loop;
    close v_res;

    return v_emptype;
end;

Then just call like this:

SELECT * FROM (TABLE(split('a,b,c,d,g'))) 

Execute action when back bar button of UINavigationController is pressed

Before leave current controller I need to show alert. So I did it this way:

  1. Add extention to UINavigationController with UINavigationBarDelegate
  2. Add selector to your controller navigationShouldPopOnBack(completion:)

It's worked)

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        if let items = navigationBar.items, viewControllers.count < items.count {
            return true
        }

        let clientInfoVC = topViewController as? ClientInfoVC
        if clientInfoVC?.responds(to: #selector(clientInfoVC?.navigationShouldPopOnBack)) ?? false {
            clientInfoVC?.navigationShouldPopOnBack(completion: { isAllowPop in
                if isAllowPop {
                    DispatchQueue.main.async {
                        self.popViewController(animated: true)
                    }
                }
            })
        }

        DispatchQueue.main.async {
            self.popViewController(animated: true)
        }

        return false
    }
}

@objc func navigationShouldPopOnBack(completion: @escaping (Bool) -> ()) {
        let ok = UIAlertAction(title: R.string.alert.actionOk(), style: .default) { _ in
            completion(true)
        }
        let cancel = UIAlertAction(title: R.string.alert.actionCancel(), style: .cancel) { _ in
            completion(false)
        }
        let alertController = UIAlertController(title: "", message: R.string.alert.contractMessage(), preferredStyle: .alert)
        alertController.addAction(ok)
        alertController.addAction(cancel)
        present(alertController, animated: true, completion: nil)
    }

iOS 7.0 No code signing identities found

I had this ambiguous error, "Command /usr/bin/codesign failed with exit code 1", when I was setting up new Jenkins boxes for iOS builds with Xcode 7.3, OSX 10.11.4.

In my case I had several things right: 1.Yes I had added my certificates to the keychain, both Apple's root and the team's cert. 2.Yes I downloaded the correct provisioning profile via xcode preferences. 3.Yes it even built manually in xcode.

However, for jenkins, there was perhaps a caching issue on xcode. What worked was: 1.Exit the Xcode GUI. 2.Get back in, and run the build manually once. 3.Only then will Xcode prompt to allow keychain access authorization. 4.Jenkins has some settings that might be able to fix this, but my machines are secure, so I click 'always allow xcode to access the keychain'.

How to do a SOAP wsdl web services call from the command line

It's a standard, ordinary SOAP web service. SSH has nothing to do here. I just called it with (one-liner):

$ curl -X POST -H "Content-Type: text/xml" \
    -H 'SOAPAction: "http://api.eyeblaster.com/IAuthenticationService/ClientLogin"' \
    --data-binary @request.xml \
    https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc

Where request.xml file has the following contents:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.eyeblaster.com/">
           <soapenv:Header/>
           <soapenv:Body>
              <api:ClientLogin>
                 <api:username>user</api:username>
                 <api:password>password</api:password>
                 <api:applicationKey>key</api:applicationKey>
              </api:ClientLogin>
          </soapenv:Body>
</soapenv:Envelope>

I get this beautiful 500:

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode>s:Security.Authentication.UserPassIncorrect</faultcode>
      <faultstring xml:lang="en-US">The username, password or application key is incorrect.</faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>

Have you tried ?

Read more

Image Greyscale with CSS & re-color on mouse-over?

I use the following code on http://www.diagnomics.com/

Smooth transition from b/w to color with magnifying effect (scale)

    img.color_flip {
      filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
      filter: gray; /* IE5+ */
      -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
      -webkit-transition: all .5s ease-in-out;
    }

    img.color_flip:hover {
      filter: none;
      -webkit-filter: grayscale(0);
      -webkit-transform: scale(1.1);
    }

Submitting form and pass data to controller method of type FileStreamResult

here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.

make the following changes in FormMethod

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){

}

and inside your home controller for binding the string you should specify [FromBody]

using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
     // Set a local variable with the incoming data
     string str = id;

}

FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Could not find main class HelloWorld

You either want to add "." to your CLASSPATH to specify the current directory, or add it manually at run time the way unbeli suggested.

jQuery Selector: Id Ends With?

If you know the element type then: (eg: replace 'element' with 'div')

$("element[id$='txtTitle']")

If you don't know the element type:

$("[id$='txtTitle']")

More information available


_x000D_
_x000D_
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
  $("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
_x000D_
_x000D_

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Using the :not() pseudo class:

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class. The :not() pseudo class requires a CSS selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

Examples:

_x000D_
_x000D_
/* This query selects All div elements except for   */_x000D_
div:not(.foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
   for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
  color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
  <nav id="foo">test</nav>_x000D_
  <nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

_x000D_
_x000D_
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
  color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing 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_x000D_
  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>
_x000D_
_x000D_
_x000D_

Sending data back to the Main Activity in Android

Activity 1 uses startActivityForResult:

startActivityForResult(ActivityTwo, ActivityTwoRequestCode);

Activity 2 is launched and you can perform the operation, to close the Activity do this:

Intent output = new Intent();
output.putExtra(ActivityOne.Number1Code, num1);
output.putExtra(ActivityOne.Number2Code, num2);
setResult(RESULT_OK, output);
finish();

Activity 1 - returning from the previous activity will call onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ActivityTwoRequestCode && resultCode == RESULT_OK && data != null) {
        num1 = data.getIntExtra(Number1Code);
        num2 = data.getIntExtra(Number2Code);
    }
}

UPDATE: Answer to Seenu69's comment, In activity two,

int result = Integer.parse(EditText1.getText().toString()) 
           + Integer.parse(EditText2.getText().toString());
output.putExtra(ActivityOne.KEY_RESULT, result);

Then in activity one,

int result = data.getExtra(KEY_RESULT);

Case insensitive regular expression without re.compile?

To perform case-insensitive operations, supply re.IGNORECASE

>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']

and if we want to replace text matching the case...

>>> def matchcase(word):
        def replace(m):
            text = m.group()
            if text.isupper():
                return word.upper()
            elif text.islower():
                return word.lower()
            elif text[0].isupper():
                return word.capitalize()
            else:
                return word
        return replace

>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

How to clear/delete the contents of a Tkinter Text widget?

I checked on my side by just adding '1.0' and it start working

tex.delete('1.0', END)

you can also try this

How to program a fractal?

The Sierpinski triangle and the Koch curve are special types of flame fractals. Flame fractals are a very generalized type of Iterated function system, since it uses non-linear functions.

An algorithm for IFS:es are as follows:

Start with a random point.

Repeat the following many times (a million at least, depending on final image size):

Apply one of N predefined transformations (matrix transformations or similar) to the point. An example would be that multiply each coordinate with 0.5. Plot the new point on the screen.

If the point is outside the screen, choose randomly a new one inside the screen instead.

If you want nice colors, let the color depend on the last used transformation.

how to refresh page in angular 2

Updated

How to implement page refresh in Angular 2+ note this is done within your component:

location.reload();

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

What does the Excel range.Rows property really do?

I've found myself using range.Rows for its effects in the Copy method. It copies the height of the rows from the origin to the destination, which is the behaviour I want.

rngLastRecord.Rows.Copy Destination:=Sheets("Availability").Range("a" & insertRow)

If I had used rngLastRecord.Copy instead of rngLastRecord.Rows.Copy, the row heights would be whatever was there before the copy.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall was changed from DefaultHttpFirewall to StrictHttpFirewall by default. So just define it in XML configuration like below:

<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>

set HTTPFirewall as DefaultHttpFirewall

Returning a value from callback function in Node.js

Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.

First, your function. Pass it a callback:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        return callback(finalData);
    });
}

Now:

var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
    // Here you have access to your variable
    console.log(response);
})

@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.

How do you test to see if a double is equal to NaN?

Beginners needs practical examples. so try the following code.

public class Not_a_Number {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";        
    String dottedLine = "------------------------------------------------";     

    Double numerator = -2.0;
    Double denominator = -2.0;      
    while (denominator <= 1) {
        Double x = numerator/denominator;           
        Double y = new Double (x);
        boolean z = y.isNaN();
        System.out.println("y =  " + y);
        System.out.println("z =  " + z);
        if (z == true){
            System.out.println(message);                
        }
        else {
            System.out.println("Hi, everyone"); 
        }
        numerator = numerator + 1;
        denominator = denominator +1;
        System.out.println(dottedLine);         
    } // end of while

} // end of main

} // end of class

How to escape single quotes in MySQL

$var = mysqli_real_escape_string($conn, $_POST['varfield']);

How to do jquery code AFTER page loading?

I am looking for the same problem and here is what help me. Here is the jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead, you can use on method and bind the JavaScript load event:

$(window).on('load', function () {
  alert("Window Loaded");
});

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

What is this Javascript "require"?

So what is this "require?"

require() is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.

Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include, Python's import, and so on.

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.

  • In browser JavaScript, scripts are added via the <script> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.

  • In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports or module.exports. For a module to access another module's exports or module.exports, it must use require().

In your code, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable.

Why does it work in node but not in a webpage?

require(), module.exports and exports are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.

Also, before I got it to work in node, I had to do npm install pg. What's that about?

NPM is a package repository service that hosts published JavaScript modules. npm install is a command that lets you download packages from their repository.

Where did it put it, and how does Javascript find it?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory.

IE6/IE7 css border on select element

You'd need a custom-designed select box with CSS and JavaScript. You'd need to make absolutely sure it degrades perfectly to a standard select element should a user have JavaScript disabled.

IMO, it's just not worth the effort. Stick with font stylings within the select to make it close to your site's design; leave the borders, etc., to the box elements.

How to get all keys with their values in redis

I refined the bash solution a bit, so that the more efficient scan is used instead of keys, and printing out array and hash values is supported. My solution also prints out the key name.

redis_print.sh:

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
do
    type=$(redis-cli type $key)
    if [ $type = "list" ]
    then
        printf "$key => \n$(redis-cli lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [ $type = "hash" ]
    then
        printf "$key => \n$(redis-cli hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli get $key)\n"
    fi
done

Note: you can formulate a one-liner of this script by removing the first line of redis_print.sh and commanding: cat redis_print.sh | tr '\n' ';' | awk '$1=$1'

Table with table-layout: fixed; and how to make one column wider

What you could do is something like this (pseudocode):

<container table>
  <tr>
    <td>
      <"300px" table>
    <td>
      <fixed layout table>

Basically, split up the table into two tables and have it contained by another table.

Android load from URL to Bitmap

Follow method to get url to bitmap in android just pass link of this image and get bitmap.

public static Bitmap getBitmapFromURL(String imgUrl) {
    try {
        URL url = new URL(imgUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

Remove trailing newline from the elements of a string list

list comprehension? [x.strip() for x in lst]

How to implement WiX installer upgrade?

I read the WiX documentation, downloaded examples, but I still had plenty of problems with upgrades. Minor upgrades don't execute uninstall of the previous products despite of possibility to specify those uninstall. I spent more that a day for investigations and found that WiX 3.5 intoduced a new tag for upgrades. Here is the usage:

<MajorUpgrade Schedule="afterInstallInitialize"
        DowngradeErrorMessage="A later version of [ProductName] is already installed. Setup will now exit." 
        AllowDowngrades="no" />

But the main reason of problems was that documentation says to use the "REINSTALL=ALL REINSTALLMODE=vomus" parameters for minor and small upgrades, but it doesn't say that those parameters are FORBIDDEN for major upgrades - they simply stop working. So you shouldn't use them with major upgrades.

How SQL query result insert in temp table?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select *
into #TempTable
from YourTable

select *
from #TempTable

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

There's another easy way, you can type in terminal

sudo apt-get install python-opencv

Install OpenCV-Python in Ubuntu

After installing it, you can use opencv version 2.4 in both c++ and python.

But I recommend you should use opencv 3.2.0 and opencv-contrib, it gives more features

Hope this can help!

OpenCV Python rotate image by X degrees around specific point

import imutils

vs = VideoStream(src=0).start()
...

while (1):
   frame = vs.read()
   ...

   frame = imutils.rotate(frame, 45)

More: https://github.com/jrosebr1/imutils

Page Redirect after X seconds wait using JavaScript

You can use this JavaScript function. Here you can display Redirection message to the user and redirected to the given URL.

<script type="text/javascript">   
    function Redirect() 
    {  
        window.location="http://www.newpage.com"; 
    } 
    document.write("You will be redirected to a new page in 5 seconds"); 
    setTimeout('Redirect()', 5000);   
</script>

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Is it possible to serialize and deserialize a class in C++?

You can check the amef protocol, an example of C++ encoding in amef would be like,

    //Create a new AMEF object
    AMEFObject *object = new AMEFObject();

    //Add a child string object
    object->addPacket("This is the Automated Message Exchange Format Object property!!","adasd");   

    //Add a child integer object
    object->addPacket(21213);

    //Add a child boolean object
    object->addPacket(true);

    AMEFObject *object2 = new AMEFObject();
    string j = "This is the property of a nested Automated Message Exchange Format Object";
    object2->addPacket(j);
    object2->addPacket(134123);
    object2->addPacket(false);

    //Add a child character object
    object2->addPacket('d');

    //Add a child AMEF Object
    object->addPacket(object2);

    //Encode the AMEF obejct
    string str = new AMEFEncoder()->encode(object,false);

Decoding in java would be like,

    string arr = amef encoded byte array value;
    AMEFDecoder decoder = new AMEFDecoder()
    AMEFObject object1 = AMEFDecoder.decode(arr,true);

The Protocol implementation has codecs for both C++ and Java, the interesting part is it can retain object class representation in the form of name value pairs, I required a similar protocol in my last project, when i incidentally stumbled upon this protocol, i had actually modified the base library according to my requirements. Hope this helps you.

How to add local .jar file dependency to build.gradle file?

The solution which worked for me is the usage of fileTree in build.gradle file. Keep the .jar which need to add as dependency in libs folder. The give the below code in dependenices block in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Using LINQ to remove elements from a List<T>

You cannot do this with standard LINQ operators because LINQ provides query, not update support.

But you can generate a new list and replace the old one.

var authorsList = GetAuthorList();

authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();

Or you could remove all items in authors in a second pass.

var authorsList = GetAuthorList();

var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();

foreach (var author in authors)
{
    authorList.Remove(author);
}

Evaluating string "3*(4+2)" yield int 18

This is a simple Expression Evaluator using Stacks

public class MathEvaluator
{
    public static void Run()
    {
        Eval("(1+2)");
        Eval("5*4/2");
        Eval("((3+5)-6)");
    }

    public static void Eval(string input)
    {
        var ans = Evaluate(input);
        Console.WriteLine(input + " = " + ans);
    }

    public static double Evaluate(String input)
    {
        String expr = "(" + input + ")";
        Stack<String> ops = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();

        for (int i = 0; i < expr.Length; i++)
        {
            String s = expr.Substring(i, 1);
            if (s.Equals("(")){}
            else if (s.Equals("+")) ops.Push(s);
            else if (s.Equals("-")) ops.Push(s);
            else if (s.Equals("*")) ops.Push(s);
            else if (s.Equals("/")) ops.Push(s);
            else if (s.Equals("sqrt")) ops.Push(s);
            else if (s.Equals(")"))
            {
                int count = ops.Count;
                while (count > 0)
                {
                    String op = ops.Pop();
                    double v = vals.Pop();
                    if (op.Equals("+")) v = vals.Pop() + v;
                    else if (op.Equals("-")) v = vals.Pop() - v;
                    else if (op.Equals("*")) v = vals.Pop()*v;
                    else if (op.Equals("/")) v = vals.Pop()/v;
                    else if (op.Equals("sqrt")) v = Math.Sqrt(v);
                    vals.Push(v);

                    count--;
                }
            }
            else vals.Push(Double.Parse(s));
        }
        return vals.Pop();
    }
}

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

What is default list styling (CSS)?

http://www.w3schools.com/tags/tag_ul.asp

ul { 
    display: block;
    list-style-type: disc;
    margin-top: 1em;
    margin-bottom: 1em;
    margin-left: 0;
    margin-right: 0;
    padding-left: 40px;
}

Pad a number with leading zeros in JavaScript

For fun, instead of using a loop to create the extra zeros:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}

Extension mysqli is missing, phpmyadmin doesn't work

Checking the extension_dir is one of the thing you like to check from phpinfo().In my case it was extension_dir = "./" by default which was wrong. Change it to extension_dir = './ext/' or where all your extension dlls are currently residing.

How to insert close button in popover for Bootstrap

FWIW, here's the generic solution that I'm using. I'm using Bootstrap 3, but I think the general approach should work with Bootstrap 2 as well.

The solution enables popovers and adds a 'close' button for all popovers identified by the 'rel="popover"' tag using a generic block of JS code. Other than the (standard) requirement that there be a rel="popover" tag, you can put an arbitrary number of popovers on the page, and you don't need to know their IDs -- in fact they don't need IDs at all. You do need to use the 'data-title' HTML tag format to set the title attribute of your popovers, and have data-html set to "true".

The trick that I found necessary was to build an indexed map of references to the popover objects ("po_map"). Then I can add an 'onclick' handler via HTML that references the popover object via the index that JQuery gives me for it ("p_list['+index+'].popover(\'toggle\')"). That way I don't need to worry about the ids of the popover objects, since I have a map of references to the objects themselves with a JQuery-provided unique index.

Here's the javascript:

var po_map = new Object();
function enablePopovers() {
  $("[rel='popover']").each(function(index) {
    var po=$(this);
    po_map[index]=po;
    po.attr("data-title",po.attr("data-title")+
    '<button id="popovercloseid" title="close" type="button" class="close" onclick="po_map['+index+'].popover(\'toggle\')">&times;</button>');
    po.popover({});
  });
}
$(document).ready(function() { enablePopovers() });

this solution let me easily put a close button on all the popovers all across my site.

Merge two array of objects based on a key

Well... assuming both arrays are of the same length, I would probably do something like this:

var newArr = []
for (var i = 0; i < array1.length; i++ {
    if (array1[i].id === array2[i].id) {
      newArr.push({id: array1[i].id, date: array1[i].date, name: array2[i].name});
  }
}

How does jQuery work when there are multiple elements with the same ID value?

Having 2 elements with the same ID is not valid html according to the W3C specification.

When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


If you absolutely must select by duplicate ID, use an attribute selector:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note: if possible, you should qualify that selector with a tag selector, like this:

$('span[id="a"]');

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

I would recommend doing it like this to keep things in line with HTML5.

<meta charset="UTF-8">

EG:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
</body>
</html>

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How do I get a list of installed CPAN modules?

Here's a Perl one-liner that will print out a list of installed modules:

perl -MExtUtils::Installed -MData::Dumper -e  'my ($inst) = ExtUtils::Installed->new(); print Dumper($inst->modules());'

Just make sure you have Data::Dumper installed.

How to load json into my angular.js ng-model?

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

You can load it like this

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

Changing the Git remote 'push to' default

Working with Git 2.3.2 ...

git branch --set-upstream-to myfork/master

Now status, push and pull are pointed to myfork remote

Check if a string contains an element from a list (of strings)

Based on your patterns one improvement would be to change to using StartsWith instead of Contains. StartsWith need only iterate through each string until it finds the first mismatch instead of having to restart the search at every character position when it finds one.

Also, based on your patterns, it looks like you may be able to extract the first part of the path for myString, then reverse the comparison -- looking for the starting path of myString in the list of strings rather than the other way around.

string[] pathComponents = myString.Split( Path.DirectorySeparatorChar );
string startPath = pathComponents[0] + Path.DirectorySeparatorChar;

return listOfStrings.Contains( startPath );

EDIT: This would be even faster using the HashSet idea @Marc Gravell mentions since you could change Contains to ContainsKey and the lookup would be O(1) instead of O(N). You would have to make sure that the paths match exactly. Note that this is not a general solution as is @Marc Gravell's but is tailored to your examples.

Sorry for the C# example. I haven't had enough coffee to translate to VB.

How to count the number of set bits in a 32-bit integer?

I got bored, and timed a billion iterations of three approaches. Compiler is gcc -O3. CPU is whatever they put in the 1st gen Macbook Pro.

Fastest is the following, at 3.7 seconds:

static unsigned char wordbits[65536] = { bitcounts of ints between 0 and 65535 };
static int popcount( unsigned int i )
{
    return( wordbits[i&0xFFFF] + wordbits[i>>16] );
}

Second place goes to the same code but looking up 4 bytes instead of 2 halfwords. That took around 5.5 seconds.

Third place goes to the bit-twiddling 'sideways addition' approach, which took 8.6 seconds.

Fourth place goes to GCC's __builtin_popcount(), at a shameful 11 seconds.

The counting one-bit-at-a-time approach was waaaay slower, and I got bored of waiting for it to complete.

So if you care about performance above all else then use the first approach. If you care, but not enough to spend 64Kb of RAM on it, use the second approach. Otherwise use the readable (but slow) one-bit-at-a-time approach.

It's hard to think of a situation where you'd want to use the bit-twiddling approach.

Edit: Similar results here.

Java : How to determine the correct charset encoding of a stream

An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.

Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();

How to open a new tab in GNOME Terminal from command line?

To bring together a number of different points above, here's a script that will run any arguments passed to the script vim new_tab.sh:

#!/bin/bash
#
# Dependencies:
#   sudo apt install xdotool

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID
sleep 1; xdotool type --delay 1 --clearmodifiers "$@"; xdotool key Return;

Next make it executable: chmod +x new_tab.sh

Now you can use it to run whatever you'd like in a new tab: ./new_tab.sh "watch ls -l"

How can I send an inner <div> to the bottom of its parent <div>?

This is one way

<div style="position: relative; 
            width: 200px; 
            height: 150px; 
            border: 1px solid black;">

    <div style="position: absolute; 
                bottom: 0; 
                width: 100%; 
                height: 50px; 
                border: 1px solid red;">
    </div>
</div>

But because the inner div is positioned absolutely, you'll always have to worry about other content in the outer div overlapping it (and you'll always have to set fixed heights).

If you can do it, it's better to make that inner div the last DOM object in your outer div and have it set to "clear: both".

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

How to allow <input type="file"> to accept only image files?

Use the accept attribute of the input tag. So to accept only PNG's, JPEG's and GIF's you can use the following code:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
_x000D_
_x000D_
_x000D_

Or simply:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/*" />
_x000D_
_x000D_
_x000D_

Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.

It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.

For detailed browser support, see http://caniuse.com/#feat=input-file-accept

Nexus 5 USB driver

You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time

Trim a string in C

static inline void ut_trim(char * str) {
   char * start = str;
   char * end = start + strlen(str);

   while (--end >= start) {   /* trim right */
      if (!isspace(*end))
         break;
   }
   *(++end) = '\0';

   while (isspace(*start))    /* trim left */
      start++;

   if (start != str)          /* there is a string */
      memmove(str, start, end - start + 1);
}

How to get past the login page with Wget?

I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:

wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'

(This is one line, though it likely wraps on your browser)

If you want the output saved to a file, change -O - to -O /some/file/name.ext

Dynamic Web Module 3.0 -- 3.1

If you want to use version 3.1 you need to use the following schema:

  • http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd

Note that 3.0 and 3.1 are different: in 3.1 there's no Sun mentioned, so simply changing 3_0.xsd to 3_1.xsd won't work.

This is how it should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

</web-app>

Also, make sure you're depending on the latest versions in your pom.xml. That is,

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        ...
    </configuration>
</plugin>

and

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Finally, you should compile with Java 7 or 8:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
    </configuration>
</plugin>

Display an image into windows forms

I display images in windows forms when I put it in Load event like this:

    private void Form1_Load( object sender , EventArgs e )
    {
        pictureBox1.ImageLocation = "./image.png"; //path to image
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

How to get Django and ReactJS to work together?

A note for anyone who is coming from a backend or Django based role and trying to work with ReactJS: No one manages to setup ReactJS enviroment successfully in the first try :)

There is a blog from Owais Lone which is available from http://owaislone.org/blog/webpack-plus-reactjs-and-django/ ; however syntax on Webpack configuration is way out of date.

I suggest you follow the steps mentioned in the blog and replace the webpack configuration file with the content below. However if you're new to both Django and React, chew one at a time because of the learning curve you will probably get frustrated.

var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    context: __dirname,
    entry: './static/assets/js/index',
    output: {
        path: path.resolve('./static/assets/bundles/'),
        filename: '[name]-[hash].js'
    },
    plugins: [
        new BundleTracker({filename: './webpack-stats.json'})
    ],

 module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },


  resolve: {
        modules: ['node_modules', 'bower_components'],
        extensions: ['.js', '.jsx']
    }
};

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

How to set image in imageview in android?

If you created ImageView from Java Class

ImageView img = new ImageView(this);

//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

Opening the Settings app from another app

Tested with iOS 10. Working

NSArray* urlStrings = @[@"prefs:root=WIFI", @"App-Prefs:root=WIFI"];
for(NSString* urlString in urlStrings){
NSURL* url = [NSURL URLWithString:urlString];
if([[UIApplication sharedApplication] canOpenURL:url]){
    [[UIApplication sharedApplication] openURL:url];
    break;
}
}

Happy Coding :)

HTML form submit to PHP script

<form method="POST" action="chk_kw.php">
    <select name="website_string"> 
        <option selected="selected"></option>
        <option value="abc">abc</option>
        <option value="def">def</option>
        <option value="hij">hij</option>   
    </select>
    <input type="submit">
</form>


  • As your form gets more complex, you can a quick check at top of your php script using print_r($_POST);, it'll show what's being submitted an the respective element name.
  • To get the submitted value of the element in question do:

    $website_string = $_POST['website_string'];

Chrome Extension: Make it run every page load

If it needs to run on the onload event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload.

Go / golang time.Now().UnixNano() convert to milliseconds?

Simple-read but precise solution would be:

func nowAsUnixMilliseconds(){
    return time.Now().Round(time.Millisecond).UnixNano() / 1e6
}

This function:

  1. Correctly rounds the value to the nearest millisecond (compare with integer division: it just discards decimal part of the resulting value);
  2. Does not dive into Go-specifics of time.Duration coercion — since it uses a numerical constant that represents absolute millisecond/nanosecond divider.

P.S. I've run benchmarks with constant and composite dividers, they showed almost no difference, so feel free to use more readable or more language-strict solution.

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

Properties private set;

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

public class Person
{
    public Person(int id)
    {
         this.Id=id;
    }

    public string Name { get;  set; }
    public int Id { get; internal set; }
    public int Age { get; set; }
}

AssemblyInfo.cs for Entities.dll

[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]

That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

Why is my method undefined for the type object?

Try this.

public static void main(String[] args) {
    EchoServer0 myServer;
    myServer = new EchoServer0();
    myServer.listen();
}

What you were trying to do was declaring a variable of type Object, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object) on an object that hadn't been created. It was never going to work.

Get a specific bit from byte

[Flags]
enum Relays : byte
{
    relay0 = 1 << 0,
    relay1 = 1 << 1,
    relay2 = 1 << 2,
    relay3 = 1 << 3,
    relay4 = 1 << 4,
    relay5 = 1 << 5,
    relay6 = 1 << 6,
    relay7 = 1 << 7
}

public static bool GetRelay(byte b, Relays relay)
{
    return (Relays)b.HasFlag(relay);
}

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

You have used regular expression for this format : DD - MM- YYYY

If you need this format DD/MM/YYYY use

var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

How can I find out if an .EXE has Command-Line Options?

Really this is an extension to Marcin's answer.

But you could also try passing "rubbish" arguments to see if you get any errors back. Getting any response from the executable directly in the shell will mean that it is likely looking at the arguments you're passing, with an error response being close to a guarantee that it is.

Failing that you might have to directly ask the publishers/creators/owners... sniffing the binaries yourself just seems like far too much work for an end-user.

How to assign bean's property an Enum value in Spring config file?

I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:

<util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />

As described in the spring documentation.

How can I run a program from a batch file without leaving the console open after the program starts?

Look at the START command, you can do this:

START rest-of-your-program-name

For instance, this batch-file will wait until notepad exits:

@echo off
notepad c:\test.txt

However, this won't:

@echo off
start notepad c:\test.txt

Why shouldn't I use "Hungarian Notation"?

Debunking the benefits of Hungarian Notation

  • It provides a way of distinguishing variables.

If the type is all that distinguishes the one value from another, then it can only be for the conversion of one type to another. If you have the same value that is being converted between types, chances are you should be doing this in a function dedicated to conversion. (I have seen hungarianed VB6 leftovers use strings on all of their method parameters simply because they could not figure out how to deserialize a JSON object, or properly comprehend how to declare or use nullable types.) If you have two variables distinguished only by the Hungarian prefix, and they are not a conversion from one to the other, then you need to elaborate on your intention with them.

  • It makes the code more readable.

I have found that Hungarian notation makes people lazy with their variable names. They have something to distinguish it by, and they feel no need to elaborate to its purpose. This is what you will typically find in Hungarian notated code vs. modern: sSQL vs. groupSelectSql (or usually no sSQL at all because they are supposed to be using the ORM that was put in by earlier developers.), sValue vs. formCollectionValue (or usually no sValue either, because they happen to be in MVC and should be using its model binding features), sType vs. publishSource, etc.

It can't be readability. I see more sTemp1, sTemp2... sTempN from any given hungarianed VB6 leftover than everybody else combined.

  • It prevents errors.

This would be by virtue of number 2, which is false.

How to completely remove a dialog on close

You can do use

$(dialogElement).empty();    
$(dialogElement).remove();

How can I merge two MySQL tables?

If you need to do it manually, one time:

First, merge in a temporary table, with something like:

create table MERGED as select * from table 1 UNION select * from table 2

Then, identify the primary key constraints with something like

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Where PK is the primary key field...

Solve the duplicates.

Rename the table.

[edited - removed brackets in the UNION query, which was causing the error in the comment below]

How can I conditionally require form inputs with AngularJS?

In AngularJS (version 1.x), there is a build-in directive ngRequired

<input type='email'
       name='email'
       ng-model='user.email' 
       placeholder='[email protected]'
       ng-required='!user.phone' />

<input type='text'
       ng-model='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!user.email' /> 

In Angular2 or above

<input type='email'
       name='email'
       [(ngModel)]='user.email' 
       placeholder='[email protected]'
       [required]='!user.phone' />

<input type='text'
       [(ngModel)]='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       [required]='!user.email' /> 

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

Changing the color of an hr element

I think this can be useful. this was simple CSS selector.

_x000D_
_x000D_
hr { background-color: red; height: 1px; border: 0; }
_x000D_
<hr>
_x000D_
_x000D_
_x000D_

How to upload files in asp.net core?

 <form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">

     <div class="form-group">
        <input type="file" class="form-control" name="image" />
     </div>

     <div class="form-group">
        <button type="submit" class="btn btn-primary col-xs-12">Add</button>
     </div>
  </form>

My Action Is

        [HttpPost]
        public IActionResult AddNews(IFormFile image)
        {
            Tbl_News tbl_News = new Tbl_News();
            if (image!=null)
            {

                //Set Key Name
                string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);

                //Get url To Save
                string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);

                using(var stream=new FileStream(SavePath, FileMode.Create))
                {
                    image.CopyTo(stream);
                }
            }
            return View();
        }

could not extract ResultSet in hibernate

Another solution is add @JsonIgnore :

@OneToMany(mappedBy="catalog", fetch = FetchType.LAZY)
@JsonIgnore
private Set<Product> products = new HashSet<Product>(0);

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

How to find the privileges and roles granted to a user in Oracle?

always make SQL re-usuable: -:)

-- ===================================================
-- &role_name will be "enter value for 'role_name'".
-- Date:  2015 NOV 11.

-- sample code:   define role_name=&role_name
-- sample code:   where role like '%&&role_name%'
-- ===================================================


define role_name=&role_name

select * from ROLE_ROLE_PRIVS where ROLE = '&&role_name';
select * from ROLE_SYS_PRIVS  where ROLE = '&&role_name';


select role, privilege,count(*)
 from ROLE_TAB_PRIVS
where ROLE = '&&role_name'
group by role, privilege
order by role, privilege asc
;

How to fix error Base table or view not found: 1146 Table laravel relationship table?

This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin

How do I check if a string is valid JSON in Python?

I came up with an generic, interesting solution to this problem:

class SafeInvocator(object):
    def __init__(self, module):
        self._module = module

    def _safe(self, func):
        def inner(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                return None

        return inner

    def __getattr__(self, item):
        obj = getattr(self.module, item)
        return self._safe(obj) if hasattr(obj, '__call__') else obj

and you can use it like so:

safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
    # do something

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

How do I use StringUtils in Java?

StringUtils is part of Apache Commons Lang (http://commons.apache.org/lang/, and as the name suggest it provides some nice utilities for dealing with Strings, going beyond what is offered in java.lang.String. It consists of over 50 static methods.

There are two different versions available, the newer org.apache.commons.lang3.StringUtils and the older org.apache.commons.lang.StringUtils. There are not really any significant differences between the two. lang3.StringUtils requires Java 5.0 and is probably the version you'll want to use.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

>>> import arrow

>>> now = arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS')
>>> now
'2018-11-28T21:34:59.235'
>>> zulu = "{}Z".format(now)
>>> zulu
'2018-11-28T21:34:59.235Z'

Or, to get it in one fell swoop:

>>> zulu = "{}Z".format(arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS'))
>>> zulu
'2018-11-28T21:54:49.639Z'

Including external jar-files in a new jar-file build with Ant

Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!

Retrieve column names from java.sql.ResultSet

When you need the column names, but do not want to grab entries:

PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");

ResultSet set = stmt.executeQuery();

//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }

NOTE: Only works with MySQL

How to add screenshot to READMEs in github repository?

With the images located in /screen-shots directory. The outer <div> allows the images to be positioned. Padding is achieved using <img width="desired-padding" height="0">.

<div align="center">
        <img width="45%" src="screen-shots/about.PNG" alt="About screen" title="About screen"</img>
        <img height="0" width="8px">
        <img width="45%" src="screen-shots/list.PNG" alt="List screen" title="List screen"></img>
</div>

How to avoid using Select in Excel VBA

I noticed that none of these answers mention the .Offset Property. This also can be used to avoid using the Select action when manipulating certain cells, particularly in reference to a selected cell (as the OP mentions with ActiveCell).

Here are a couple examples.

I will also assume the "ActiveCell" is J4.

ActiveCell.Offset(2, 0).Value = 12

  • This will change the cell J6 to be a value of 12
  • A minus -2 would have referenced J2

ActiveCell.Offset(0,1).Copy ActiveCell.Offset(,2)

  • This will copy the cell in k4 to L4.
  • Note that "0" is not needed in the offset parameter if not needed (,2)
  • Similar to the previous example a minus 1 would be i4

ActiveCell.Offset(, -1).EntireColumn.ClearContents

  • This will clear values in all cells in the column k.

These aren't to say they are "better" than the above options, but just listing alternatives.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

Java Set retain order?

Only SortedSet can do the ordering of the Set

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here
            }
        });

JavaScript: Create and save file

function SaveBlobAs(blob, file_name) {
    if (typeof navigator.msSaveBlob == "function")
        return navigator.msSaveBlob(blob, file_name);

    var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    var blobURL = saver.href = URL.createObjectURL(blob), 
        body = document.body;

    saver.download = file_name;

    body.appendChild(saver);
    saver.dispatchEvent(new MouseEvent("click"));
    body.removeChild(saver);
    URL.revokeObjectURL(blobURL);
}

ICommand MVVM implementation

@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel

First implement ICommand

public class Command : ICommand
{
    public delegate void ICommandOnExecute();
    public delegate bool ICommandOnCanExecute();

    private ICommandOnExecute _execute;
    private ICommandOnCanExecute _canExecute;

    public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
    {
        _execute = onExecuteMethod;
        _canExecute = onCanExecuteMethod;
    }

    #region ICommand Members

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke() ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }

    #endregion
}

Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor

Then to use in the ViewModel

public Command CommandToRun_WithCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        }, () =>
        {
            // Code to check to see if we can run 
            // Return true or false
        });
    }
}

public Command CommandToRun_NoCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        });
    }
}

I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.

Xcode 'CodeSign error: code signing is required'

Be sure you code sign on the line "any iOS SDK" and not "Debug/Distribution/Release"

Here is exactly what I did :

Code signing identity -> don't code sign
* Debug -> don't code sign
** any iOS SDK -> [my developer profile]
* Distribution -> don't code sign
** any iOS SDK -> [my AppStore profile]
* Release -> don't code sign
** any iOS SDK -> [my AdHoc profile]

When I put my profiles one level above (at Debug/Ditribution/Release), it doesn't work for some reason (bug ?).

Hope it helps some of us !

Easiest way to convert int to string in C++

Using the plain standard stdio header, you can cast the integer over sprintf into a buffer, like so:

#include <stdio.h>
int main()
  {
  int x=23;
  char y[2]; //the output buffer
  sprintf(y,"%d",x);
  printf("%s",y)
  }

Remember to take care of your buffer size according to your needs [the string output size]

Disabling Chrome Autofill

This is the most recent solution that I have used.

$('#email').prop('autocomplete', true);

Composer: The requested PHP extension ext-intl * is missing from your system

I have solved this problem by adding --ignore-platform-reqs command with composer install in ubuntu.

composer install --ignore-platform-reqs

How do I convert datetime to ISO 8601 in PHP

After PHP 5 you can use this: echo date("c"); form ISO 8601 formatted datetime.

http://ideone.com/nD7piL

Note for comments:

Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh].

But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c"). A similar discussion here.

Automatically plot different colored lines

Late answer, but two things to add:

  • For information on how to change the 'ColorOrder' property and how to set a global default with 'DefaultAxesColorOrder', see the "Appendix" at the bottom of this post.
  • There is a great tool on the MATLAB Central File Exchange to generate any number of visually distinct colors, if you have the Image Processing Toolbox to use it. Read on for details.

The ColorOrder axes property allows MATLAB to automatically cycle through a list of colors when using hold on/all (again, see Appendix below for how to set/get the ColorOrder for a specific axis or globally via DefaultAxesColorOrder). However, by default MATLAB only specifies a short list of colors (just 7 as of R2013b) to cycle through, and on the other hand it can be problematic to find a good set of colors for more data series. For 10 plots, you obviously cannot rely on the default ColorOrder.

A great way to define N visually distinct colors is with the "Generate Maximally Perceptually-Distinct Colors" (GMPDC) submission on the MATLAB Central File File Exchange. It is best described in the author's own words:

This function generates a set of colors which are distinguishable by reference to the "Lab" color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries.

For example, when 25 colors are requested:

25 "maximally perceptually-distinct colors"

The GMPDC submission was chosen on MathWorks' official blog as Pick of the Week in 2010 in part because of the ability to request an arbitrary number of colors (in contrast to MATLAB's built in 7 default colors). They even made the excellent suggestion to set MATLAB's ColorOrder on startup to,

distinguishable_colors(20)

Of course, you can set the ColorOrder for a single axis or simply generate a list of colors to use in any way you like. For example, to generate 10 "maximally perceptually-distinct colors" and use them for 10 plots on the same axis (but not using ColorOrder, thus requiring a loop):

% Starting with X of size N-by-P-by-2, where P is number of plots
mpdc10 = distinguishable_colors(10) % 10x3 color list
hold on
for ii=1:size(X,2),
    plot(X(:,ii,1),X(:,ii,2),'.','Color',mpdc10(ii,:));
end

The process is simplified, requiring no for loop, with the ColorOrder axis property:

% X of size N-by-P-by-2
mpdc10 = distinguishable_colors(10)
ha = axes; hold(ha,'on')
set(ha,'ColorOrder',mpdc10)    % --- set ColorOrder HERE ---
plot(X(:,:,1),X(:,:,2),'-.')   % loop NOT needed, 'Color' NOT needed. Yay!

APPENDIX

To get the ColorOrder RGB array used for the current axis,

get(gca,'ColorOrder')

To get the default ColorOrder for new axes,

get(0,'DefaultAxesColorOrder')

Example of setting new global ColorOrder with 10 colors on MATLAB start, in startup.m:

set(0,'DefaultAxesColorOrder',distinguishable_colors(10))

Common CSS Media Queries Break Points

Media Queries for Standard Devices

In General for Mobile, Tablets, Desktop and Large Screens

1. Mobiles

 /* Smartphones (portrait and landscape) ----------- */
    @media only screen 
    and (min-device-width : 320px) 
    and (max-device-width : 480px) {

    /* Styles */

    }

2. Tablets

@media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) {

         /* Styles */

    }

3. Desktops & laptops

@media only screen 
and (min-width : 1224px) {

    /* Styles */

}

4. Larger Screens

@media only screen 
and (min-width : 1824px) {

    /* Styles */

}

In Detail including landscape and portrait

/* Smartphones (portrait and landscape) ----------- */
    @media only screen 
    and (min-device-width : 320px) 
    and (max-device-width : 480px) {
    /* Styles */
    }

    /* Smartphones (landscape) ----------- */
    @media only screen 
    and (min-width : 321px) {
    /* Styles */
    }

    /* Smartphones (portrait) ----------- */
    @media only screen 
    and (max-width : 320px) {
    /* Styles */
    }

    /* Tablets, iPads (portrait and landscape) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) {
    /* Styles */
    }

    /* Tablets, iPads (landscape) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) 
    and (orientation : landscape) {
    /* Styles */
    }

    /* Tablets, iPads (portrait) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) 
    and (orientation : portrait) {
    /* Styles */
    }

    /* Desktops and laptops ----------- */
    @media only screen 
    and (min-width : 1224px) {
    /* Styles */
    }

    /* Large screens ----------- */
    @media only screen 
    and (min-width : 1824px) {
    /* Styles */
    }

    /* iPhone 4 ----------- */
    @media
    only screen and (-webkit-min-device-pixel-ratio : 1.5),
    only screen and (min-device-pixel-ratio : 1.5) {
    /* Styles */
    }

Reference

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

Bash scripting missing ']'

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

How to include CSS file in Symfony 2 and Twig?

You are doing everything right, except passing your bundle path to asset() function.

According to documentation - in your example this should look like below:

{{ asset('bundles/webshome/css/main.css') }}

Tip: you also can call assets:install with --symlink key, so it will create symlinks in web folder. This is extremely useful when you often apply js or css changes (in this way your changes, applied to src/YouBundle/Resources/public will be immediately reflected in web folder without need to call assets:install again):

app/console assets:install web --symlink

Also, if you wish to add some assets in your child template, you could call parent() method for the Twig block. In your case it would be like this:

{% block stylesheets %}
    {{ parent() }}

    <link href="{{ asset('bundles/webshome/css/main.css') }}" rel="stylesheet">
{% endblock %}

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Using ios_base::sync_with_stdio(false); is sufficient to decouple the C and C++ streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.

The cin.tie(NULL) call seems to be requesting a decoupling between the activities on cin and cout. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

JAVA_HOME does not point to the JDK

I know this question is old but the accepted answer does not work anymore and since this is the fist link on google search i'll tell how i solved this problem.

for eclipse using ubuntu:

go to Window->Preferences->Ant->Runtime->Select Ant_Home_Entries and click on add external jars then find in file explorer where your jdk is (default is in /usr/lib/jvm/) and in the lib folder of your jdk you will find the tool.jar. select this one and click apply.

try to build your project and things should work!

note: i hadn't used ant for a long time but needed it for ycsb couchbase workload generator (http://www.couchbase.com/wiki/display/couchbase/Load+Generator+Setup) if anyone is/was stuck on this.

String comparison using '==' vs. 'strcmp()'

Always remember, when comparing strings, you should use === operator (strict comparison) and not == operator (loose comparison).

What is a database transaction?

I would suggest that a definition of 'transaction processing' would be more useful, as it covers transactions as a concept in computer science.

From wikipedia:

In computer science, transaction processing is information processing that is divided into individual, indivisible operations, called transactions. Each transaction must succeed or fail as a complete unit; it cannot remain in an intermediate state.

http://en.wikipedia.org/wiki/Transaction_processing#Implementations

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

The following worked for me:

$(':input').val('');

However, it is submitting the form, so it might not be what you are looking for.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

I want to start by thanking everyone that answered. But cleaning and rebuilding was not enough in my case because the problem was still there and needed fixing.

Turned out that one of my package directories had accidentally been copied so that an extra directory now existed called "Copy of dagskra" containing Java files with wrong package declarations. In addition the errors in this "new" directory don't show up with a "red-x" in the package that it exists in:

Snapshot from Package Explorer showing errorous "Copy of dagskra" directoryr http://www.freeimagehosting.net/uploads/a824304b18.png

It was the hint of reading the "Problems" tab :-) that turned me into the right direction, so I'm selecting that answer as the accepted answer because this is what I needed:

Snapshot from Problems tab http://www.freeimagehosting.net/uploads/dea26d5dd0.png

Hoping this will help others...

Lotus Notes email as an attachment to another email

You can slecet sent item /email and drag to desktop , it will automatic created new file on desktop. Then you can attach and send it in to new emails.

sql server #region

Another option is

if your purpose is analyse your query, Notepad+ has useful automatic wrapper for Sql.

MVC 5 Access Claims Identity User Data

You can also do this.

IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

Which concurrent Queue implementation should I use in Java?

Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

Tips for debugging .htaccess rewrite rules

Make sure you use the percent sign in front of variables, not the dollar sign.

It's %{HTTP_HOST}, not ${HTTP_HOST}. There will be nothing in the error_log, there will be no Internal Server Errors, your regexp is still correct, the rule will just not match. This is really hideous if you work with django / genshi templates a lot and have ${} for variable substitution in muscle memory.

What is git tag, How to create tags & How to checkout git remote tag(s)

Let's start by explaining what a tag in git is

enter image description here

A tag is used to label and mark a specific commit in the history.
It is usually used to mark release points (eg. v1.0, etc.).

Although a tag may appear similar to a branch, a tag, however, does not change. It points directly to a specific commit in the history and will not change unless explicitly updated.

enter image description here


You will not be able to checkout the tags if it's not locally in your repository so first, you have to fetch the tags to your local repository.

First, make sure that the tag exists locally by doing

# --all will fetch all the remotes.
# --tags will fetch all tags as well
$ git fetch --all --tags --prune

Then check out the tag by running

$ git checkout tags/<tag_name> -b <branch_name>

Instead of origin use the tags/ prefix.


In this sample you have 2 tags version 1.0 & version 1.1 you can check them out with any of the following:

$ git checkout A  ...
$ git checkout version 1.0  ...
$ git checkout tags/version 1.0  ...

All of the above will do the same since the tag is only a pointer to a given commit.

enter image description here
origin: https://backlog.com/git-tutorial/img/post/stepup/capture_stepup4_1_1.png


How to see the list of all tags?

# list all tags
$ git tag

# list all tags with given pattern ex: v-
$ git tag --list 'v-*'

How to create tags?

There are 2 ways to create a tag:

# lightweight tag 
$ git tag 

# annotated tag
$ git tag -a

The difference between the 2 is that when creating an annotated tag you can add metadata as you have in a git commit:
name, e-mail, date, comment & signature

enter image description here

How to delete tags?

Delete a local tag

$ git tag -d <tag_name>
Deleted tag <tag_name> (was 000000)

Note: If you try to delete a non existig Git tag, there will be see the following error:

$ git tag -d <tag_name>
error: tag '<tag_name>' not found.

Delete remote tags

# Delete a tag from the server with push tags
$ git push --delete origin <tag name>

How to clone a specific tag?

In order to grab the content of a given tag, you can use the checkout command. As explained above tags are like any other commits so we can use checkout and instead of using the SHA-1 simply replacing it with the tag_name

Option 1:

# Update the local git repo with the latest tags from all remotes
$ git fetch --all

# checkout the specific tag
$ git checkout tags/<tag> -b <branch>

Option 2:

Using the clone command

Since git supports shallow clone by adding the --branch to the clone command we can use the tag name instead of the branch name. Git knows how to "translate" the given SHA-1 to the relevant commit

# Clone a specific tag name using git clone 
$ git clone <url> --branch=<tag_name>

git clone --branch=

--branch can also take tags and detaches the HEAD at that commit in the resulting repository.


How to push tags?

git push --tags

To push all tags:

# Push all tags
$ git push --tags 

Using the refs/tags instead of just specifying the <tagname>.

Why?

  • It's recommended to use refs/tags since sometimes tags can have the same name as your branches and a simple git push will push the branch instead of the tag

To push annotated tags and current history chain tags use:

git push --follow-tags

This flag --follow-tags pushes both commits and only tags that are both:

  • Annotated tags (so you can skip local/temp build tags)
  • Reachable tags (an ancestor) from the current branch (located on the history)

enter image description here

From Git 2.4 you can set it using configuration

$ git config --global push.followTags true

Cheatsheet: enter image description here


dyld: Library not loaded: @rpath/libswiftCore.dylib

Following these steps worked for me:

  • Click on your project name (very top of the navigator)
  • Click on your project name again, (not on target)
  • Click the tab Build Settings
  • Search for Runpath Search Paths

  • Change its value to $(inherited) flag (remove @executable_path/Frameworks).

What does 'git remote add upstream' help achieve?

This is useful when you have your own origin which is not upstream. In other words, you might have your own origin repo that you do development and local changes in and then occasionally merge upstream changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

how to add or embed CKEditor in php page

After reading the Quick Start Guide

In your HTML page add an element that CKEditor should replace:

<textarea name="content" id="editor"></textarea>

Load the classic editor build (here CDN location is used):

<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>

Call the ClassicEditor.create() method.

<script>
    ClassicEditor
        .create( document.querySelector( '#editor' ) )
        .catch( error => {
            console.error( error );
        } );
</script>

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
</head>
<body>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor">
        <p>This is some sample content.</p>
    </textarea>
    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>
</body>
</html>

This example is for the specific classic editor. FOr other variants, only CDN will change.

Max or Default?

Another possibility would be grouping, similar to how you might approach it in raw SQL:

from y in context.MyTable
group y.MyCounter by y.MyField into GrpByMyField
where GrpByMyField.Key == value
select GrpByMyField.Max()

The only thing is (testing again in LINQPad) switching to the VB LINQ flavor gives syntax errors on the grouping clause. I'm sure the conceptual equivalent is easy enough to find, I just don't know how to reflect it in VB.

The generated SQL would be something along the lines of:

SELECT [t1].[MaxValue]
FROM (
    SELECT MAX([t0].[MyCounter) AS [MaxValue], [t0].[MyField]
    FROM [MyTable] AS [t0]
    GROUP BY [t0].[MyField]
    ) AS [t1]
WHERE [t1].[MyField] = @p0

The nested SELECT looks icky, like the query execution would retrieve all rows then select the matching one from the retrieved set... the question is whether or not SQL Server optimizes the query into something comparable to applying the where clause to the inner SELECT. I'm looking into that now...

I'm not well-versed in interpreting execution plans in SQL Server, but it looks like when the WHERE clause is on the outer SELECT, the number of actual rows resulting in that step is all rows in the table, versus only the matching rows when the WHERE clause is on the inner SELECT. That said, it looks like only 1% cost is shifted to the following step when all rows are considered, and either way only one row ever comes back from the SQL Server so maybe it's not that big of a difference in the grand scheme of things.

Rename multiple files based on pattern in Unix

rename might not be in every system. so if you don't have it, use the shell this example in bash shell

for f in fgh*; do mv "$f" "${f/fgh/xxx}";done

Best/Most Comprehensive API for Stocks/Financial Data

Markit On Demand provides a set of free financial APIs for playing around with. Looks like there is a stock quote API, a stock ticker/company search and a charting API available. Look at http://dev.markitondemand.com

'AND' vs '&&' as operator

Depending on how it's being used, it might be necessary and even handy. http://php.net/manual/en/language.operators.logical.php

// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

But in most cases it seems like more of a developer taste thing, like every occurrence of this that I've seen in CodeIgniter framework like @Sarfraz has mentioned.

How to call a .NET Webservice from Android using KSOAP2?

It's very simple. You are getting the result into an Object which is a primitive one.

Your code:

Object result = (Object)envelope.getResponse();

Correct code:

SoapObject result=(SoapObject)envelope.getResponse();

//To get the data.
String resultData=result.getProperty(0).toString();
// 0 is the first object of data.

I think this should definitely work.

Laravel 5 – Clear Cache in Shared Hosting Server

You can do it via router as well, similar to Francesco answer but with less clutter in router config

Route::get('/artisan/{cmd}', function($cmd) {
    $cmd = trim(str_replace("-",":", $cmd));
    $validCommands = ['cache:clear', 'optimize', 'route:cache', 'route:clear', 'view:clear', 'config:cache'];
    if (in_array($cmd, $validCommands)) {
        Artisan::call($cmd);
        return "<h1>Ran Artisan command: {$cmd}</h1>";
    } else {
        return "<h1>Not valid Artisan command</h1>";
    }
});

Then run them via visiting http://myapp.test/artisan/cache-clear etc If you need to add/edit valid Artisan commands just update the $validCommands array.

How do I apply the for-each loop to every character in a String?

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 

Create an array of strings

Another solution to this old question is the new container string array, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:

a=repmat('Some text', 10, 1);

This solution resembles a Rich C's solution applied to string array.

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Jackson Serializer, here is a way to use the date modules:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.kafka.common.serialization.Serializer;

public class JacksonSerializer<T> implements Serializer<T> {

    private final ObjectMapper mapper = new ObjectMapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());

    @Override
    public byte[] serialize(String s, T object) {
        try {
            return mapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

How to set underline text on textview?

Use this

tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

What's the difference between .bashrc, .bash_profile, and .environment?

The main difference with shell config files is that some are only read by "login" shells (eg. when you login from another host, or login at the text console of a local unix machine). these are the ones called, say, .login or .profile or .zlogin (depending on which shell you're using).

Then you have config files that are read by "interactive" shells (as in, ones connected to a terminal (or pseudo-terminal in the case of, say, a terminal emulator running under a windowing system). these are the ones with names like .bashrc, .tcshrc, .zshrc, etc.

bash complicates this in that .bashrc is only read by a shell that's both interactive and non-login, so you'll find most people end up telling their .bash_profile to also read .bashrc with something like

[[ -r ~/.bashrc ]] && . ~/.bashrc

Other shells behave differently - eg with zsh, .zshrc is always read for an interactive shell, whether it's a login one or not.

The manual page for bash explains the circumstances under which each file is read. Yes, behaviour is generally consistent between machines.

.profile is simply the login script filename originally used by /bin/sh. bash, being generally backwards-compatible with /bin/sh, will read .profile if one exists.

Angular 2 Cannot find control with unspecified name attribute on formArrays

Instead of

formGroupName="i"

You must use:

[formGroupName]="i"

Tips:

Since you're looping over the controls, you've already the variable area, so you can replace this:

*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"

by:

*ngIf="area.hasError('required', 'name')"

Convert Enum to String

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToString and GetName would be that GetName has to verify a few things first:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.

.ToString doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString method doesn't have the same verification issues as the static methods, I would conclude that .ToString is the fastest way to get the value as a string.

Get contentEditable caret index position

If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. &#10);.

_x000D_
_x000D_
function showCursPos(){
    selection = document.getSelection();
    childOffset = selection.focusOffset;
    const range = document.createRange();
    eDiv = document.getElementById("eDiv");
    range.setStart(eDiv, 0);
    range.setEnd(selection.focusNode, childOffset);
    var sHtml = range.toString();
    p = sHtml.length; 
    sHtml=sHtml.replace(/(\r)/gm, "\\r");
    sHtml=sHtml.replace(/(\n)/gm, "\\n");
    document.getElementById("caretPosHtml").value=p;
    document.getElementById("exHtml").value=sHtml;   
  }
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"  
     onkeyup="showCursPos()" onclick="showCursPos()" 
     style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
     >123&#13;&#10;456&#10;789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>  
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
_x000D_
_x000D_

What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

Shell equality operators (=, ==, -eq)

It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test.

If you use (()), you are testing arithmetic equality with == as in C:

$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1

(Note: 0 means true in the Unix sense and a failed test results in a non-zero number.)

Using -eq inside of double parentheses is a syntax error.

If you are using [] (or single brackets) or [[]] (or double brackets), or test you can use one of -eq, -ne, -lt, -le, -gt, or -ge as an arithmetic comparison.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

The == inside of single or double brackets (or the test command) is one of the string comparison operators:

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1

As a string operator, = is equivalent to ==. Also, note the whitespace around = or ==: it’s required.

While you can do [[ 1 == 1 ]] or [[ $(( 1+1 )) == 2 ]] it is testing the string equality — not the arithmetic equality.

So -eq produces the result probably expected that the integer value of 1+1 is equal to 2 even though the right-hand side is a string and has a trailing space:

$ [[ $(( 1+1 )) -eq  "2 " ]]; echo $?
0

While a string comparison of the same picks up the trailing space and therefore the string comparison fails:

$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1

And a mistaken string comparison can produce a completely wrong answer. 10 is lexicographically less than 2, so a string comparison returns true or 0. So many are bitten by this bug:

$ [[ 10 < 2 ]]; echo $?
0

The correct test for 10 being arithmetically less than 2 is this:

$ [[ 10 -lt 2 ]]; echo $?
1

In comments, there is a question about the technical reason why using the integer -eq on strings returns true for strings that are not the same:

$ [[ "yes" -eq "no" ]]; echo $?
0

The reason is that Bash is untyped. The -eq causes the strings to be interpreted as integers if possible including base conversion:

$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0

And 0 if Bash thinks it is just a string:

$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1

So [[ "yes" -eq "no" ]] is equivalent to [[ 0 -eq 0 ]]


Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]] and ((...)) or ==.

How to declare global variables in Android?

The approach of subclassing has also been used by the BARACUS framework. From my point of view subclassing Application was intended to work with the lifecycles of Android; this is what any Application Container does. Instead of having globals then, I register beans to this context an let them beeing injected into any class manageable by the context. Every injected bean instance actually is a singleton.

See this example for details

Why do manual work if you can have so much more?

How to debug external class library projects in visual studio?

I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:

Build Events:

  • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

  • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

Debug:

  • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

  • Working Directory C:\<path-to-main>\bin\debug

This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

Android Studio: Gradle: error: cannot find symbol variable

make sure that the imported R is not from another module. I had moved a class from a module to the main project, and the R was the one from the module.

How to make g++ search for header files in a specific directory?

it's simple, use the "-B" option to add .h files' dir to search path.

E.g. g++ -B /header_file.h your.cpp -o bin/your_command

delete map[key] in go?

From Effective Go:

To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.

delete(timeZone, "PDT")  // Now on Standard Time

Disable sorting for a particular column in jQuery DataTables

What I use is just add a custom attribute in thead td and control sorting by checking that attr value automatically.

So the HTML code will be

<table class="datatables" cellspacing="0px" >

    <thead>
        <tr>
            <td data-bSortable="true">Requirements</td>
            <td>Test Cases</td>
            <td data-bSortable="true">Automated</td>
            <td>Created On</td>
            <td>Automated Status</td>
            <td>Tags</td>
            <td>Action</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>

And JavaScript for initializing datatables will be (it will dynamically get the sorting information from table iteself ;)

$('.datatables').each(function(){
    var bFilter = true;
    if($(this).hasClass('nofilter')){
        bFilter = false;
    }
    var columnSort = new Array; 
    $(this).find('thead tr td').each(function(){
        if($(this).attr('data-bSortable') == 'true') {
            columnSort.push({ "bSortable": true });
        } else {
            columnSort.push({ "bSortable": false });
        }
    });
    $(this).dataTable({
        "sPaginationType": "full_numbers",
        "bFilter": bFilter,
        "fnDrawCallback": function( oSettings ) {
        },
        "aoColumns": columnSort
    });
});

Initializing a member array in constructor initializer

  1. No, unfortunately.
  2. You just can't in the way you want, as it's not allowed by the grammar (more below). You can only use ctor-like initialization, and, as you know, that's not available for initializing each item in arrays.
  3. I believe so, as they generalize initialization across the board in many useful ways. But I'm not sure on the details.

In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.

T var = {...};

Python: Remove division decimal

def division(a, b):
    return a / b if a % b else a // b

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

How to exit from Python without traceback?

Use the built-in python function quit() and that's it. No need to import any library. I'm using python 3.4

Make the current Git branch a master branch

I found the answer I wanted in the blog post Replace the master branch with another branch in git:

git checkout feature_branch
git merge -s ours --no-commit master
git commit      # Add a message regarding the replacement that you just did
git checkout master
git merge feature_branch

It's essentially the same as Cascabel's answer. Except that the "option" he added below his solution is already embedded in my main code block.

It's easier to find this way.

I'm adding this as a new answer, because if I need this solution later, I want to have all the code I am going to use in one code block.

Otherwise, I may copy-paste, then read details below to see the line that I should have changed - after I already executed it.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

How to get href value using jQuery?

It's worth mentioning that

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

MySQL: Set user variable from result of query

Just add parenthesis around the query:

set @user = 123456;
set @group = (select GROUP from USER where User = @user);
select * from USER where GROUP = @group;

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

How can I use UIColorFromRGB in Swift?

You can use this:

//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
                      ,green: CGFloat(0xCC)/255
                      ,blue: CGFloat(0x4B)/255
                      ,alpha: 1.0)

Difference between Statement and PreparedStatement

I followed all the answers of this question to change a working legacy code using - Statement ( but having SQL Injections ) to a solution using PreparedStatement with a much slower code because of poor understanding of semantics around Statement.addBatch(String sql) & PreparedStatement.addBatch().

So I am listing my scenario here so others don't make same mistake.

My scenario was

Statement statement = connection.createStatement();

for (Object object : objectList) {
    //Create a query which would be different for each object 
    // Add this query to statement for batch using - statement.addBatch(query);
}
statement.executeBatch();

So in above code , I had thousands of different queries, all added to same statement and this code worked faster because statements not being cached was good & this code executed rarely in the app.

Now to fix SQL Injections, I changed this code to ,

List<PreparedStatement> pStatements = new ArrayList<>();    
for (Object object : objectList) {
    //Create a query which would be different for each object 
    PreparedStatement pStatement =connection.prepareStatement(query);
    // This query can't be added to batch because its a different query so I used list. 
    //Set parameter to pStatement using object 
    pStatements.add(pStatement);
}// Object loop
// In place of statement.executeBatch(); , I had to loop around the list & execute each update separately          
for (PreparedStatement ps : pStatements) {
    ps.executeUpdate();
}

So you see, I started creating thousands of PreparedStatement objects & then eventually not able to utilize batching because my scenario demanded that - there are thousands of UPDATE or INSERT queries & all of these queries happen to be different.

Fixing SQL injection was mandatory at no cost of performance degradation and I don't think that it is possible with PreparedStatement in this scenario.

Also, when you use inbuilt batching facility, you have to worry about closing only one Statement but with this List approach, you need to close statement before reuse , Reusing a PreparedStatement

How to check if a query string value is present via JavaScript?

var field = 'q';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
    return true;
else if(url.indexOf('&' + field + '=') != -1)
    return true;
return false

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.

Dynamic Height Issue for UITableView Cells (Swift)

Set proper constraint and update delegate methods as:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

This will resolve dynamic cell height issue. IF not you need to check constraints.

How to checkout a specific Subversion revision from the command line?

svn checkout to revision where your repository is on another server

Use svn log command to find out which revisions are available:

svn log

Which prints:

------------------------------------------------------------------------
r762 | machines | 2012-12-02 13:00:16 -0500 (Sun, 02 Dec 2012) | 2 lines

------------------------------------------------------------------------
r761 | machines | 2012-12-02 12:59:40 -0500 (Sun, 02 Dec 2012) | 2 lines

Note the number r761. Here is the command description:

svn export http://url-to-your-file@761 /tmp/filename

I used this command specifically:

svn export svn+ssh://[email protected]/home1/oct/calc/calcFeatures.m@761 calcFeatures.m

Which causes calcFeatures.m revision 761 to be checked out to the current directory.

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

Convert HTML to PDF in .NET

Instead of parsing HTML directly to PDF, you can create an Bitmap of your HTML-page and then insert the Bitmap into your PDF, using for example iTextSharp.

Here's a code how to get an Bitmap of an URL. I found it somewhere here on SO, if I find the source I'll link it.

public System.Drawing.Bitmap HTMLToImage(String strHTML)
{
    System.Drawing.Bitmap myBitmap = null;

    System.Threading.Thread myThread = new System.Threading.Thread(delegate()
    {
        // create a hidden web browser, which will navigate to the page
        System.Windows.Forms.WebBrowser myWebBrowser = new System.Windows.Forms.WebBrowser();
        // we don't want scrollbars on our image
        myWebBrowser.ScrollBarsEnabled = false;
        // don't let any errors shine through
        myWebBrowser.ScriptErrorsSuppressed = true;
        // let's load up that page!    
        myWebBrowser.Navigate("about:blank");

        // wait until the page is fully loaded
        while (myWebBrowser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
            System.Windows.Forms.Application.DoEvents();

        myWebBrowser.Document.Body.InnerHtml = strHTML;

        // set the size of our web browser to be the same size as the page
        int intScrollPadding = 20;
        int intDocumentWidth = myWebBrowser.Document.Body.ScrollRectangle.Width + intScrollPadding;
        int intDocumentHeight = myWebBrowser.Document.Body.ScrollRectangle.Height + intScrollPadding;
        myWebBrowser.Width = intDocumentWidth;
        myWebBrowser.Height = intDocumentHeight;
        // a bitmap that we will draw to
        myBitmap = new System.Drawing.Bitmap(intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding);
        // draw the web browser to the bitmap
        myWebBrowser.DrawToBitmap(myBitmap, new System.Drawing.Rectangle(0, 0, intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding));
    });
    myThread.SetApartmentState(System.Threading.ApartmentState.STA);
    myThread.Start();
    myThread.Join();

    return myBitmap;
}

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

Prevent BODY from scrolling when a modal is opened

Bootstrap's modal automatically adds the class modal-open to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS:

body.modal-open {
    overflow: hidden;
}

You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site.

Update 8th feb, 2013
This has now stopped working in Twitter Bootstrap v. 2.3.0 -- they no longer add the modal-open class to the body.

A workaround would be to add the class to the body when the modal is about to be shown, and remove it when the modal is closed:

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});

Update 11th march, 2013 Looks like the modal-open class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:

Reintroduces .modal-open on the body (so we can nuke the scroll there)

See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.

How to change Hash values?

You may want to go a step further and do this on a nested hash. Certainly this happens a fair amount with Rails projects.

Here's some code to ensure a params hash is in UTF-8:

  def convert_hash hash
    hash.inject({}) do |h,(k,v)|
      if v.kind_of? String
        h[k] = to_utf8(v) 
      else
        h[k] = convert_hash(v)
      end
      h
    end      
  end    

  # Iconv UTF-8 helper
  # Converts strings into valid UTF-8
  #
  # @param [String] untrusted_string the string to convert to UTF-8
  # @return [String] your string in UTF-8
  def to_utf8 untrusted_string=""
    ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
    ic.iconv(untrusted_string + ' ')[0..-2]
  end