Programs & Examples On #Libdispatch

The libdispatch project consists of the user space implementation of the Grand Central Dispatch API.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

in Xcode 8 use:

DispatchQueue.global(qos: .userInitiated).async { }

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".

Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.

When you add or edit a web site, your new application pools will now show up in the list.

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

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

How do you do exponentiation in C?

use the pow function (it takes floats/doubles though).

man pow:

   #include <math.h>

   double pow(double x, double y);
   float powf(float x, float y);
   long double powl(long double x, long double y);

EDIT: For the special case of positive integer powers of 2, you can use bit shifting: (1 << x) will equal 2 to the power x. There are some potential gotchas with this, but generally, it would be correct.

cannot find module "lodash"

For me, I update node and npm to the latest version and it works.

Return JsonResult from web api without its properties

I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

Here is how I solved it. First I declared a utility class

public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example

public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

Verifying that a string contains only letters in C#

bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

Sort a Map<Key, Value> by values

as map is unordered to sort it ,we can do following

Map<String, String> map= new TreeMap<String, String>(unsortMap);

You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

How to dismiss notification after action has been clicked

When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:

notify(int id, Notification notification)

To cancel, you would call:

cancel(int id)

with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?

How to check whether a string is a valid HTTP URL?

All the answers here either allow URLs with other schemes (e.g., file://, ftp://) or reject human-readable URLs that don't start with http:// or https:// (e.g., www.google.com) which is not good when dealing with user inputs.

Here's how I do it:

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

Usage:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

Output:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

Convert a Python int into a big-endian string of bytes

Probably the best way is via the built-in struct module:

>>> import struct
>>> x = 1245427
>>> struct.pack('>BH', x >> 16, x & 0xFFFF)
'\x13\x00\xf3'
>>> struct.pack('>L', x)[1:]  # could do it this way too
'\x13\x00\xf3'

Alternatively -- and I wouldn't usually recommend this, because it's mistake-prone -- you can do it "manually" by shifting and the chr() function:

>>> x = 1245427
>>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF)
'\x13\x00\xf3'

Out of curiosity, why do you only want three bytes? Usually you'd pack such an integer into a full 32 bits (a C unsigned long), and use struct.pack('>L', 1245427) but skip the [1:] step?

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

Determine the line of code that causes a segmentation fault?

There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).

Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.

According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:

int main() {
  volatile int *ptr = (int*)0;
  *ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
    #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
    #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
    #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING

The output is slightly more complicated than what gdb would output but there are upsides:

  • There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.

  • ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.


¹ That is Clang 3.1+ and GCC 4.8+.

Oracle Age calculation from Date of birth and Today

This seems considerably easier than what anyone else has suggested

select sysdate-to_date('30-jul-1977') from dual; 

How Do I Make Glyphicons Bigger? (Change Size?)

Yes, and basically you can also use inline style:

<span style="font-size: 15px" class="glyphicon glyphicon-cog"></span>

Jmeter - get current date and time

it seems to be the java SimpleDateFormat : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

here are some tests i did around 11:30pm on the 20th of May 2015

${__time(dd-mmm-yyyy HHmmss)} 20-032-2015 233224
${__time(d-MMM-yyyy hhmmss)}  20-May-2015 113224
${__time(dd-m-yyyy hhmmss)}   20-32-2015 113224
${__time(D-M-yyyy hhmmss)}    140-5-2015 113224
${__time(DD-MM-yyyy)}         140-05-2015

How to cd into a directory with space in the name?

Use the backslash symbol to escape the space

C:\> cd my folder

will be

 C:\> cd my\folder 

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

npm install error - unable to get local issuer certificate

In case you use yarn:

yarn config set strict-ssl false

Facebook Open Graph not clearing cache

  1. Go to http://developers.facebook.com/tools/debug
  2. Enter the URL following by fbrefresh=CAN_BE_ANYTHING

Examples:

  1. http://www.example.com?fbrefresh=CAN_BE_ANYTHING
  2. http://www.example.com?postid=1234&fbrefresh=CAN_BE_ANYTHING
  3. OR visit: http://developers.facebook.com/tools/debug/og/object?q=http://www.example.com/?p=3568&fbrefresh=89127348912

I was having the same issue last night, and I got this solution from some website.

Facebook saves your cache thumbnail. It won't refresh even if you delete the thumnail/image from your server. But Facebook allows you to refresh by using fbrefresh

I hope this helps.

Centering FontAwesome icons vertically and horizontally

I just lowered the height to 28px on the .login-icon [class*='icon-'] Here's the fiddle: http://jsfiddle.net/mZHg7/

.login-icon [class*='icon-']{
    height: 28px;
    width: 50px;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

Nullable types: better way to check for null or zero in c#

Using generics:

static bool IsNullOrDefault<T>(T value)
{
    return object.Equals(value, default(T));
}

//...
double d = 0;
IsNullOrDefault(d); // true
MyClass c = null;
IsNullOrDefault(c); // true

If T it's a reference type, value will be compared with null ( default(T) ), otherwise, if T is a value type, let's say double, default(t) is 0d, for bool is false, for char is '\0' and so on...

Take multiple lists into dataframe

Just adding that using the first approach it can be done as -

pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

How can I make window.showmodaldialog work in chrome 37?

    (function() {
        window.spawn = window.spawn || function(gen) {
            function continuer(verb, arg) {
                var result;
                try {
                    result = generator[verb](arg);
                } catch (err) {
                    return Promise.reject(err);
                }
                if (result.done) {
                    return result.value;
                } else {
                    return Promise.resolve(result.value).then(onFulfilled, onRejected);
                }
            }
            var generator = gen();
            var onFulfilled = continuer.bind(continuer, 'next');
            var onRejected = continuer.bind(continuer, 'throw');
            return onFulfilled();
        };
        window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
            url = url || ''; //URL of a dialog
            arg = arg || null; //arguments to a dialog
            opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
            var caller = showModalDialog.caller.toString();
            var dialog = document.body.appendChild(document.createElement('dialog'));
            dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
            dialog.innerHTML = '<a href="#" id="dialog-close" style="position: absolute; top: 0; right: 4px; font-size: 20px; color: #000; text-decoration: none; outline: none;">&times;</a><iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
            document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
            document.getElementById('dialog-close').addEventListener('click', function(e) {
                e.preventDefault();
                dialog.close();
            });
            dialog.showModal();
            //if using yield
            if(caller.indexOf('yield') >= 0) {
                return new Promise(function(resolve, reject) {
                    dialog.addEventListener('close', function() {
                        var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                        document.body.removeChild(dialog);
                        resolve(returnValue);
                    });
                });
            }
            //if using eval
            var isNext = false;
            var nextStmts = caller.split('\n').filter(function(stmt) {
                if(isNext || stmt.indexOf('showModalDialog(') >= 0)
                    return isNext = true;
                return false;
            });
            dialog.addEventListener('close', function() {
                var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                document.body.removeChild(dialog);
                nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
                eval('{\n' + nextStmts.join('\n'));
            });
            throw 'Execution stopped until showModalDialog is closed';
        };
    })()

;

**Explanation:
------------**
The best way to deal with showModalDialog for older application conversions is use to `https://github.com/niutech/showModalDialog` inorder to work with show modal dialogs  and if modal dailog has ajax calls you need to create object and set the parameters of function to object and pass below...before that check for browser and set the useragent...example: agentStr = navigator.userAgent; and then check for chrome

var objAcceptReject={}; // create empty object and set the parameters to object and send to the other functions as dialog when opened in chrome breaks the functionality
    function rejectClick(index, transferId) {
        objAcceptReject.index=index;
        objAcceptReject.transferId=transferId;

     agentStr = navigator.userAgent;

                var msie = ua.indexOf("MSIE ");

                if (msie > 0) // If Internet Explorer, return version number
                {
                    var ret = window.showModalDialog("/abc.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }

                } else if ((agentStr.indexOf("Chrome")) >- 1){
                spawn(function() {

                    var ret = window.showModalDialog("/abcd.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {// create an object and store values in objects and send as parameters
                        doSomeClick(objAcceptReject.index);
                    }

                });

                }
                else {
                    var ret = window.showModalDialog("/xtz.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }
                }

How do I get the MAX row with a GROUP BY in LINQ query?

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
    {
        Serial_Number = g.Key,
        uid = g.Max(row => row.uid)
    });

Intent from Fragment to Activity

Hope this code will help

public class ThisFragment extends Fragment {

public Button button = null;
Intent intent;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.yourlayout, container, false);

    intent = new Intent(getActivity(), GoToThisActivity.class);
    button = (Button) rootView.findViewById(R.id.theButtonid);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(intent);
        }
    });
    return rootView;
}

You can use this code, make sure you change "ThisFragment" as your fragment name, "yourlayout" as the layout name, "GoToThisActivity" change it to which activity do you want and then "theButtonid" change it with your button id you used.

What is the easiest way to remove all packages installed by pip?

the easy robust way cross-platform and work in pipenv as well is:

pip freeze 
pip uninstall -r requirement

by pipenv:

pipenv run pip freeze 
pipenv run pip uninstall -r requirement

but won't update piplock or pipfile so be aware

How can I pass arguments to anonymous functions in JavaScript?

Example:

<input type="button" value="Click me" id="myButton">
<script>
    var myButton = document.getElementById("myButton");
    var test = "zipzambam";
    myButton.onclick = function(eventObject) {
        if (!eventObject) {
            eventObject = window.event;
        }
        if (!eventObject.target) {
            eventObject.target = eventObject.srcElement;
        }
        alert(eventObject.target);
        alert(test);
    };
    (function(myMessage) {
        alert(myMessage);
    })("Hello");
</script>

Run react-native application on iOS device directly from command line?

If you get this error [email protected] preinstall: ./src/scripts/check_reqs.js && xcodebuild ... using npm install -g ios-deploy

Try this. It works for me:

  1. sudo npm uninstall -g ios-deploy
  2. brew install ios-deploy

Could not find or load main class with a Jar File

This error comes even if you miss "-" by mistake before the word jar

Wrong command java jar test.jar

Correct command java -jar test.jar

How do I kill an Activity when the Back button is pressed?

Simple Override onBackPressed Method:

    @Override
    public void onBackPressed() {
            super.onBackPressed();
            this.finish();
    }

Where can I find the Java SDK in Linux after installing it?

on OpenSUSE 13.1/13.2 its: /usr/lib64/jvm/java-1.6.0-openjdk-(version-number)
version-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...

André

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

Convert Pixels to Points

Surely this whole question should be:

"How do I obtain the horizontal and vertical PPI (Pixels Per Inch) of the monitor?"

There are 72 points in an inch (by definition, a "point" is defined as 1/72nd of an inch, likewise a "pica" is defined as 1/72nd of a foot). With these two bits of information you can convert from px to pt and back very easily.

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

How do you Encrypt and Decrypt a PHP String?

If you don't want to use library (which you should) then use something like this (PHP 7):

function sign($message, $key) {
    return hash_hmac('sha256', $message, $key) . $message;
}

function verify($bundle, $key) {
    return hash_equals(
      hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
      mb_substr($bundle, 0, 64, '8bit')
    );
}

function getKey($password, $keysize = 16) {
    return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
}

function encrypt($message, $password) {
    $iv = random_bytes(16);
    $key = getKey($password);
    $result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
    return bin2hex($iv).bin2hex($result);
}

function decrypt($hash, $password) {
    $iv = hex2bin(substr($hash, 0, 32));
    $data = hex2bin(substr($hash, 32));
    $key = getKey($password);
    if (!verify($data, $key)) {
      return null;
    }
    return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
}

$string_to_encrypt='John Smith';
$password='password';
$encrypted_string=encrypt($string_to_encrypt, $password);
$decrypted_string=decrypt($encrypted_string, $password);

Prevent jQuery UI dialog from setting focus to first textbox

I got the same problem.

The workaround I did is add the dummy textbox at the top of the dialog container.

<input type="text" style="width: 1px; height: 1px; border: 0px;" />

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

How can I count the number of elements with same class?

Simplest example:

_x000D_
_x000D_
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
_x000D_
<html>_x000D_
    <body>_x000D_
    _x000D_
    <p id="demo"></p>_x000D_
    <ul>_x000D_
      <li class="test">Coffee</li>_x000D_
      <li class="test">Milk</li>_x000D_
      <li class="test">Soda</li>_x000D_
    </ul>_x000D_
_x000D_
 </body> _x000D_
 </html>
_x000D_
_x000D_
_x000D_

What does "make oldconfig" do exactly in the Linux kernel makefile?

Before you run make oldconfig, you need to copy a kernel configuration file from an older kernel into the root directory of the new kernel.

You can find a copy of the old kernel configuration file on a running system at /boot/config-3.11.0. Alternatively, kernel source code has configs in linux-3.11.0/arch/x86/configs/{i386_defconfig / x86_64_defconfig}

If your kernel source is located at /usr/src/linux:

cd /usr/src/linux
cp /boot/config-3.9.6-gentoo .config
make oldconfig

Recover from git reset --hard?

I just did git reset --hard and lost all my uncommitted changes. Luckily, I use an editor (IntelliJ) and I was able to recover the changes from the Local History. Eclipse should allow you to do the same.

Print a string as hex bytes?

Some complements to Fedor Gogolev answer:

First, if the string contains characters whose 'ASCII code' is below 10, they will not be displayed as required. In that case, the correct format should be {:02x}:

>>> s = "Hello unicode \u0005 !!"
>>> ":".join("{0:x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:5:20:21:21'
                                           ^

>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:05:20:21:21'
                                           ^^

Second, if your "string" is in reality a "byte string" -- and since the difference matters in Python 3 -- you might prefer the following:

>>> s = b"Hello bytes \x05 !!"
>>> ":".join("{:02x}".format(c) for c in s)
'48:65:6c:6c:6f:20:62:79:74:65:73:20:05:20:21:21'

Please note there is no need for conversion in the above code as a bytes objects is defined as "an immutable sequence of integers in the range 0 <= x < 256".

Copying formula to the next row when inserting a new row

If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.

How to expand a list to function arguments in Python

It exists, but it's hard to search for. I think most people call it the "splat" operator.

It's in the documentation as "Unpacking argument lists".

You'd use it like this: foo(*values). There's also one for dictionaries:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

AngularJS check if form is valid in controller

The BusinessCtrl is initialised before the createBusinessForm's FormController. Even if you have the ngController on the form won't work the way you wanted. You can't help this (you can create your ngControllerDirective, and try to trick the priority.) this is how angularjs works.

See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
}

So this will call your fragment's onActivityResult()

Edit: the solution is to replace getActivity().startActivityForResult(i, 1); with startActivityForResult(i, 1);

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

type checking in javascript

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

How to add text to JFrame?

To create a label for text:

JLabel label1 = new JLabel("Test");

To change the text in the label:

label1.setText("Label Text");

And finally to clear the label:

label1.setText("");

And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...

error, string or binary data would be truncated when trying to insert

From @gmmastros's answer

Whenever you see the message....

string or binary data would be truncated

Think to yourself... The field is NOT big enough to hold my data.

Check the table structure for the customers table. I think you'll find that the length of one or more fields is NOT big enough to hold the data you are trying to insert. For example, if the Phone field is a varchar(8) field, and you try to put 11 characters in to it, you will get this error.

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

Getting a slice of keys from a map

This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

keys := make([]int, len(mymap))

i := 0
for k := range mymap {
    keys[i] = k
    i++
}

In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

sort dict by value python

In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.

PEP 256 suggests this for sorting a dictionary by values.

import operator
sorted(d.iteritems(), key=operator.itemgetter(1))

If you want descending order, do this

sorted(d.iteritems(), key=itemgetter(1), reverse=True)

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:

spring.datasource.url=jdbc://localhost:3306/test

after:

spring.datasource.url=jdbc:mysql://localhost:3306/test

PHP get dropdown value and text

you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown

$("#dropdownid").val();   for value
$("#dropdownid").text(); for selected value

catch these into two variables and take it as inputs to ajax call for a php file

$.ajax 
   ({
     url:"callingphpfile.php",//url of fetching php  
     method:"POST", //type 
     data:"val1="+value+"&val2="+selectedtext,
     success:function(data) //return the data     
     {

}

and in php you can get it as

    if (isset($_POST["val1"])) {
    $val1= $_POST["val1"] ;
}

if (isset($_POST["val2"])) {
  $selectedtext= $_POST["val1"];
}

What is Shelving in TFS?

That's right. If you create a shelf, other people doing a get latest won't see your code.

It puts your code changes onto the server, which is probably better backed up than your work PC.

It enables you to pick up your changes on another machine, should you feel the urge to work from home.

Others can see your shelves (though I think this may be optional) so they can review your code prior to a check-in.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

inspired by @dilettante answer, here's my solution as an extension function in kotlin:

/* sets a valid id that isn't in use */
fun View.findAndSetFirstValidId() {
    var i: Int
    do {
        i = Random.nextInt()
    } while (findViewById<View>(i) != null)
    id = i
}

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

What is an .inc and why use it?

Generally means that its a file that needs to be included and does not make standalone script in itself.

This is a convention not a programming technique.

Although if your web server is not configured properly it could expose files with extensions like .inc.

how to properly display an iFrame in mobile safari

Purely using MSchimpf and Ahmad's code, I made adjustments so I could have the iframe within a div, therefore keeping a header and footer for back button and branding on my page. Updated code:

<script type="text/javascript">
    $("#webview").bind('pagebeforeshow', function(event){
        $("#iframe").attr('src',cwebview);
    });

    if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
    {
        $("#webview-content").css("width","100%");
        $("#webview-content").css("height","100%");
        $("#iframe").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
            iframeWidth = $("#iframe").contents().width();
            if (iframeWidth > 400)
               $("#webview-content").css("width",(iframeWidth + 182) + 'px');

            iframeHeight = $("#iframe").contents().height();
            if (iframeHeight>200)
                $("#webview-content").css("height",iframeHeight + 'px');
         });
    }       
</script>  

and the html

<div class="header" data-role="header" data-position="fixed">
</div>

<div id="webview-content" data-role="content" style="height:380px;">
    <iframe id="iframe"></iframe>   
</div><!-- /content -->

<div class="footer" data-role="footer" data-position="fixed">
</div><!-- /footer -->   

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

Network usage top/htop on Linux

NetHogs is probably what you're looking for:

a small 'net top' tool. Instead of breaking the traffic down per protocol or per subnet, like most tools do, it groups bandwidth by process.

NetHogs does not rely on a special kernel module to be loaded. If there's suddenly a lot of network traffic, you can fire up NetHogs and immediately see which PID is causing this. This makes it easy to identify programs that have gone wild and are suddenly taking up your bandwidth.

Since NetHogs heavily relies on /proc, most features are only available on Linux. NetHogs can be built on Mac OS X and FreeBSD, but it will only show connections, not processes...

Rotate axis text in python matplotlib

Appart from

plt.xticks(rotation=90)

this is also possible:

plt.xticks(rotation='vertical')

Android Studio: Can't start Git

Run sudo git --version from command line and agree to the license and this should fix the issue.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD

<input type="text"  placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control "  name="eventDate" id="" required autofocus autocomplete="nope">

I got this solution from http://html5pattern.com/Dates. Hope it may help someone.

Difference between agile and iterative and incremental development

Incremental development means that different parts of a software project are continuously integrated into the whole, instead of a monolithic approach where all the different parts are assembled in one or a few milestones of the project.

Iterative means that once a first version of a component is complete it is tested, reviewed and the results are almost immediately transformed into a new version (iteration) of this component.

So as a first result: iterative development doesn't need to be incremental and vice versa, but these methods are a good fit.

Agile development aims to reduce massive planing overhead in software projects to allow fast reactions to change e.g. in customer wishes. Incremental and iterative development are almost always part of an agile development strategy. There are several approaches to Agile development (e.g. scrum).

Spring MVC - Why not able to use @RequestBody and @RequestParam together

You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

@RequestParam(required = false)String name

How to view the dependency tree of a given npm module?

If you want to get the actually dependency path of specific package and want to know why you have it, you can simply ask yarn why <MODULE>. example:

    $> yarn why mime-db
    yarn why v1.5.1
    [1/4] Why do we have the module "mime-db"...?
    [2/4] Initialising dependency graph...
    [3/4] Finding dependency...
    [4/4] Calculating file sizes...
    => Found "[email protected]"
    info Reasons this module exists
       - "coveralls#request#mime-types" depends on it
       - Hoisted from "coveralls#request#mime-types#mime-db"
    info Disk size without dependencies: "196kB"
    info Disk size with unique dependencies: "196kB"
    info Disk size with transitive dependencies: "196kB"
    info Number of shared dependencies: 0
    Done in 0.65s.

jQuery hide and show toggle div with plus and minus icon

Toggle the text Show and Hide and move your backgroundPosition Y axis

LIVE DEMO

$(function(){ // DOM READY shorthand

    $(".slidingDiv").hide();

    $('.show_hide').click(function( e ){
        // e.preventDefault(); // If you use anchors
        var SH = this.SH^=1; // "Simple toggler"
        $(this).text(SH?'Hide':'Show')
               .css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
               .next(".slidingDiv").slideToggle();
    });

});

CSS:

.show_hide{
  background:url(plusminus.png) no-repeat;
  padding-left:20px;  
}

How do I copy directories recursively with gulp?

Turns out that to copy a complete directory structure gulp needs to be provided with a base for your gulp.src() method.

So gulp.src( [ files ], { "base" : "." }) can be used in the structure above to copy all the directories recursively.

If, like me, you may forget this then try:

gulp.copy=function(src,dest){
    return gulp.src(src, {base:"."})
        .pipe(gulp.dest(dest));
};

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

ASP.net vs PHP (What to choose)

You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.

If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.

Get value from a string after a special character

Here's a way:

<html>
    <head>
        <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var value = $('input[type="hidden"]')[0].value;
                alert(value.split(/\?/)[1]);
            });
        </script>
    </head>
    <body>
        <input type="hidden" value="/TEST/Name?3" />
    </body>
</html>

How to set margin of ImageView using code, not xml

Here is an example to add 8px Margin on left, top, right, bottom.


ImageView imageView = new ImageView(getApplicationContext());

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
    ViewGroup.MarginLayoutParams.MATCH_PARENT,
    ViewGroup.MarginLayoutParams.WRAP_CONTENT
);

marginLayoutParams.setMargins(8, 8, 8, 8);

imageView.setLayoutParams(marginLayoutParams);

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

Android Material Design Button Styles

With the stable release of Android Material Components in Nov 2018, Google has moved the material components from namespace android.support.design to com.google.android.material.
Material Component library is replacement for Android’s Design Support Library.

Add the dependency to your build.gradle:

dependencies { implementation ‘com.google.android.material:material:1.0.0’ }

Then add the MaterialButton to your layout:

<com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.OutlinedButton" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:strokeColor="@color/colorAccent"
        app:strokeWidth="6dp"
        app:layout_constraintStart_toStartOf="parent"
        app:shapeAppearance="@style/MyShapeAppearance"
   />

You can check the full documentation here and API here.

To change the background color you have 2 options.

  1. Using the backgroundTint attribute.

Something like:

<style name="MyButtonStyle"
 parent="Widget.MaterialComponents.Button">
    <item name="backgroundTint">@color/button_selector</item>
    //..
</style>
  1. It will be the best option in my opinion. If you want to override some theme attributes from a default style then you can use new materialThemeOverlay attribute.

Something like:

<style name="MyButtonStyle"
 parent="Widget.MaterialComponents.Button">
   <item name=“materialThemeOverlay”>@style/GreenButtonThemeOverlay</item>
</style>

<style name="GreenButtonThemeOverlay">
  <!-- For filled buttons, your theme's colorPrimary provides the default background color of the component --> 
  <item name="colorPrimary">@color/green</item>
</style>

The option#2 requires the 'com.google.android.material:material:1.1.0'.

enter image description hereenter image description here

OLD Support Library:

With the new Support Library 28.0.0, the Design Library now contains the MaterialButton.

You can add this button to our layout file with:

<android.support.design.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="YOUR TEXT"
    android:textSize="18sp"
    app:icon="@drawable/ic_android_white_24dp" />

By default this class will use the accent colour of your theme for the buttons filled background colour along with white for the buttons text colour.

You can customize the button with these attributes:

  • app:rippleColor: The colour to be used for the button ripple effect
  • app:backgroundTint: Used to apply a tint to the background of the button. If you wish to change the background color of the button, use this attribute instead of background.

  • app:strokeColor: The color to be used for the button stroke

  • app:strokeWidth: The width to be used for the button stroke
  • app:cornerRadius: Used to define the radius used for the corners of the button

Twitter bootstrap remote modal shows same content every time

I've added something like this, because the older content is shown until the new one appears, with .html('') inside the .modal-content will clear the HTML inside, hope it helps

$('#myModal').on('hidden.bs.modal', function () {
   $('#myModal').removeData('bs.modal');
   $('#myModal').find('.modal-content').html('');
});

How to execute .sql script file using JDBC

I use this bit of code to import sql statements created by mysqldump:

public static void importSQL(Connection conn, InputStream in) throws SQLException
{
    Scanner s = new Scanner(in);
    s.useDelimiter("(;(\r)?\n)|(--\n)");
    Statement st = null;
    try
    {
        st = conn.createStatement();
        while (s.hasNext())
        {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/"))
            {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0)
            {
                st.execute(line);
            }
        }
    }
    finally
    {
        if (st != null) st.close();
    }
}

How to check if a string starts with a specified string?

You can use a simple regex (updated version from user viriathus as eregi is deprecated)

if (preg_match('#^http#', $url) === 1) {
    // Starts with http (case sensitive).
}

or if you want a case insensitive search

if (preg_match('#^http#i', $url) === 1) {
    // Starts with http (case insensitive).
}

Regexes allow to perform more complex tasks

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).
}

Performance wise, you don't need to create a new string (unlike with substr) nor parse the whole string if it doesn't start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). http://www.php.net/manual/en/intro.pcre.php

How do I POST JSON data with cURL?

You could also put your JSON content in a file and pass it to curl using the --upload-file option via standard input, like this:

 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -

How can I get the name of an html page in Javascript?

Use window.location.pathname to get the path of the current page's URL.

Base64: java.lang.IllegalArgumentException: Illegal character

Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.

Use this code to convert the byte[] to a String before adding it to the URL:

String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
    + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • Model1.tt (This template generates very simple POCO classes for each entity in your model)
  • Model1.Context.tt (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

Bootstrap dropdown menu not working (not dropping down when clicked)

I had the same issue I remove the following script and it worked for me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

Why is the use of alloca() not considered good practice?

All of the other answers are correct. However, if the thing you want to alloc using alloca() is reasonably small, I think that it's a good technique that's faster and more convenient than using malloc() or otherwise.

In other words, alloca( 0x00ffffff ) is dangerous and likely to cause overflow, exactly as much as char hugeArray[ 0x00ffffff ]; is. Be cautious and reasonable and you'll be fine.

Best way to do nested case statement logic in SQL Server

I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.

SELECT
    col1,
    col2,
    col3,
    CASE WHEN condition THEN
      CASE WHEN condition1 THEN
        CASE WHEN condition2 THEN calculation1
        ELSE calculation2 END
      ELSE
        CASE WHEN condition2 THEN calculation3
        ELSE calculation4 END
      END
    ELSE CASE WHEN condition1 THEN 
      CASE WHEN condition2 THEN calculation5
      ELSE calculation6 END
    ELSE CASE WHEN condition2 THEN calculation7
         ELSE calculation8 END
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

Map HTML to JSON

I had a similar issue where I wanted to represent HTML as JSON in the following way:

  • For HTML text nodes, use a string
  • For HTML elements, use an array with:
    • The (tag) name of the element
    • An object, mapping attribute keys to attribute values
    • The (inlined) list of children nodes

Example:

<div>
  <span>text</span>Text2
</div>

becomes

[
   'div',
   {},
   ['span', {}, 'text'],
   'Text2'
]

I wrote a function which handles transforming a DOM Element into this kind of JS structure. You can find this function at the end of this answer. The function is written in Typescript. You can use the Typescript playground to convert it to clean JavaScript.


Furthermore, if you need to parse an html string into DOM, assign to .innerHtml:

let element = document.createElement('div')
element.innerHtml = htmlString

Also, this one is common knowledge but if you need a JSON string output, use JSON.stringify.


/**
 * A NodeDescriptor stands for either an (HTML) Element, or for a text node
 */
export type NodeDescriptor = ElementDescriptor | string

/**
 * Array representing an HTML Element. It consists of:
 *
 * - The (tag) name of the element
 * - An object, mapping attribute keys to attribute values
 * - The (inlined) list of children nodes
 */
export type ElementDescriptor = [
   string,
   Record<string, string>,
   ...NodeDescriptor[]
]

export let htmlToJs = (element: Element, trim = true): ElementDescriptor => {
   let convertElement = (element: Element): ElementDescriptor => {
      let attributeObject: Record<string, string> = {}
      for (let { name, value } of element.attributes) {
         attributeObject[name] = value
      }

      let childArray: NodeDescriptor[] = []
      for (let node of element.childNodes) {
         let converter = htmlToJsDispatch[node.nodeType]
         if (converter) {
            let descriptor = converter(node as any)
            let skip = false

            if (trim && typeof descriptor === 'string') {
               descriptor = descriptor.trim()
               if (descriptor === '') skip = true
            }

            if (!skip) childArray.push(descriptor)
         }
      }

      return [element.tagName.toLowerCase(), attributeObject, ...childArray]
   }

   let htmlToJsDispatch = {
      [element.ELEMENT_NODE]: convertElement,
      [element.TEXT_NODE]: (node: Text): string => node.data,
   }

   return convertElement(element)
}

Relative imports in Python 3

I had a similar problem and solved it by creating a symbolic link to the package in the working directory:

ln -s ../../../my_package my_package

and then import it as usual:

import my_package

I know this is more like a "Linux" solution rather than a "Python" solution. but it's a valid approach nonetheless.

Is there a "previous sibling" selector?

Depending on your exact objective, there is a way to achieve the usefulness of a parent selector without using one (even if one were to exist)...

Say we have:

<div>
  <ul>
    <li><a>Pants</a></li>
    <li><a>Socks</a></li>
    <ul>
      <li><a>White socks</a></li>
      <li><a>Blue socks</a></li>
    </ul>
  </ul>
</div>

What can we do to make the Socks block (including sock colours) stand out visually using spacing?

What would be nice but doesn't exist:

ul li ul:parent {
  margin-top: 15px;
  margin-bottom: 15px;
}

What does exist:

li > a {
  margin-top: 15px;
  display: block;
}
li > a:only-child {
  margin-top: 0px;
}

This sets all anchor links to have 15px margin on the top and resets it back to 0 for those with no UL elements (or other tags) inside LIs.

How do I suspend painting for a control and its children?

I know this is an old question, already answered, but here is my take on this; I refactored the suspension of updates into an IDisposable - that way I can enclose the statements I want to run in a using statement.

class SuspendDrawingUpdate : IDisposable
{
    private const int WM_SETREDRAW = 0x000B;
    private readonly Control _control;
    private readonly NativeWindow _window;

    public SuspendDrawingUpdate(Control control)
    {
        _control = control;

        var msgSuspendUpdate = Message.Create(_control.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);

        _window = NativeWindow.FromHandle(_control.Handle);
        _window.DefWndProc(ref msgSuspendUpdate);
    }

    public void Dispose()
    {
        var wparam = new IntPtr(1);  // Create a C "true" boolean as an IntPtr
        var msgResumeUpdate = Message.Create(_control.Handle, WM_SETREDRAW, wparam, IntPtr.Zero);

        _window.DefWndProc(ref msgResumeUpdate);

        _control.Invalidate();
    }
}

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

How to build minified and uncompressed bundle with webpack?

In my opinion it's a lot easier just to use the UglifyJS tool directly:

  1. npm install --save-dev uglify-js
  2. Use webpack as normal, e.g. building a ./dst/bundle.js file.
  3. Add a build command to your package.json:

    "scripts": {
        "build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
    }
    
  4. Whenever you want to build a your bundle as well as uglified code and sourcemaps, run the npm run build command.

No need to install uglify-js globally, just install it locally for the project.

How to fetch the row count for all tables in a SQL SERVER database

Here's a dynamic SQL approach that also gives you the schema as well:

DECLARE @sql nvarchar(MAX)

SELECT
    @sql = COALESCE(@sql + ' UNION ALL ', '') +
        'SELECT
            ''' + s.name + ''' AS ''Schema'',
            ''' + t.name + ''' AS ''Table'',
            COUNT(*) AS Count
            FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
    FROM sys.schemas s
    INNER JOIN sys.tables t ON t.schema_id = s.schema_id
    ORDER BY
        s.name,
        t.name

EXEC(@sql)

If needed, it would be trivial to extend this to run over all databases in the instance (join to sys.databases).

error : expected unqualified-id before return in c++

Suggestions:

  • use consistent 3-4 space indenting and you will find these problems much easier
  • use a brace style that lines up {} vertically and you will see these problems quickly
  • always indent control blocks another level
  • use a syntax highlighting editor, it helps, you'll thank me later

for example,

type
functionname( arguments )
{
    if (something)
    {
        do stuff
    }
    else
    {
        do other stuff
    }
    switch (value)
    {
        case 'a':
            astuff
            break;
        case 'b':
            bstuff
            //fallthrough //always comment fallthrough as intentional
        case 'c':
            break;
        default: //always consider default, and handle it explicitly
            break;
    }
    while ( the lights are on )
    {
        if ( something happened )
        {
            run around in circles
            if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
            {
                scream and shout
            }
        }
    }
    return typevalue; //always return something, you'll thank me later
}

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

Using Server.MapPath in external C# Classes in ASP.NET

The server.mappath("") will work on aspx page,if you want to get the absolute path from a class file you have to use this-

HttpContext.Current.Server.MapPath("~/EmailLogic/RegistrationTemplate.html")

What are all possible pos tags of NLTK?

To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn_tagset...

CC: conjunction, coordinating

& 'n and both but either et for less minus neither nor or plus so
therefore times v. versus vs. whether yet

CD: numeral, cardinal

mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
fifteen 271,124 dozen quintillion DM2,000 ...

DT: determiner

all an another any both del each either every half la many much nary
neither no some such that the them these this those

EX: existential there

there

IN: preposition or conjunction, subordinating

astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...

JJ: adjective or numeral, ordinal

third ill-mannered pre-war regrettable oiled calamitous first separable
ectoplasmic battery-powered participatory fourth still-to-be-named
multilingual multi-disciplinary ...

JJR: adjective, comparative

bleaker braver breezier briefer brighter brisker broader bumper busier
calmer cheaper choosier cleaner clearer closer colder commoner costlier
cozier creamier crunchier cuter ...

JJS: adjective, superlative

calmest cheapest choicest classiest cleanest clearest closest commonest
corniest costliest crassest creepiest crudest cutest darkest deadliest
dearest deepest densest dinkiest ...

LS: list item marker

A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
SP-44007 Second Third Three Two * a b c d first five four one six three
two

MD: modal auxiliary

can cannot could couldn't dare may might must need ought shall should
shouldn't will would

NN: noun, common, singular or mass

common-carrier cabbage knuckle-duster Casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...

NNP: noun, proper, singular

Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
Shannon A.K.C. Meltex Liverpool ...

NNS: noun, common, plural

undergraduates scotches bric-a-brac products bodyguards facets coasts
divestitures storehouses designs clubs fragrances averages
subjectivists apprehensions muses factory-jobs ...

PDT: pre-determiner

all both half many quite such sure this

POS: genitive marker

' 's

PRP: pronoun, personal

hers herself him himself hisself it itself me myself one oneself ours
ourselves ownself self she thee theirs them themselves they thou thy us

PRP$: pronoun, possessive

her his mine my our ours their thy your

RB: adverb

occasionally unabatingly maddeningly adventurously professedly
stirringly prominently technologically magisterially predominately
swiftly fiscally pitilessly ...

RBR: adverb, comparative

further gloomier grander graver greater grimmer harder harsher
healthier heavier higher however larger later leaner lengthier less-
perfectly lesser lonelier longer louder lower more ...

RBS: adverb, superlative

best biggest bluntest earliest farthest first furthest hardest
heartiest highest largest least less most nearest second tightest worst

RP: particle

aboard about across along apart around aside at away back before behind
by crop down ever fast for forth from go high i.e. in into just later
low more off on open out over per pie raising start teeth that through
under unto up up-pp upon whole with you

TO: "to" as preposition or infinitive marker

to

UH: interjection

Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
man baby diddle hush sonuvabitch ...

VB: verb, base form

ask assemble assess assign assume atone attention avoid bake balkanize
bank begin behold believe bend benefit bevel beware bless boil bomb
boost brace break bring broil brush build ...

VBD: verb, past tense

dipped pleaded swiped regummed soaked tidied convened halted registered
cushioned exacted snubbed strode aimed adopted belied figgered
speculated wore appreciated contemplated ...

VBG: verb, present participle or gerund

telegraphing stirring focusing angering judging stalling lactating
hankerin' alleging veering capping approaching traveling besieging
encrypting interrupting erasing wincing ...

VBN: verb, past participle

multihulled dilapidated aerosolized chaired languished panelized used
experimented flourished imitated reunifed factored condensed sheared
unsettled primed dubbed desired ...

VBP: verb, present tense, not 3rd person singular

predominate wrap resort sue twist spill cure lengthen brush terminate
appear tend stray glisten obtain comprise detest tease attract
emphasize mold postpone sever return wag ...

VBZ: verb, present tense, 3rd person singular

bases reconstructs marks mixes displeases seals carps weaves snatches
slumps stretches authorizes smolders pictures emerges stockpiles
seduces fizzes uses bolsters slaps speaks pleads ...

WDT: WH-determiner

that what whatever which whichever

WP: WH-pronoun

that what whatever whatsoever which who whom whosoever

WRB: Wh-adverb

how however whence whenever where whereby whereever wherein whereof why

"git pull" or "git merge" between master and development branches

This workflow works best for me:

git checkout -b develop

...make some changes...

...notice master has been updated...

...commit changes to develop...

git checkout master
git pull

...bring those changes back into develop...

git checkout develop
git rebase master

...make some more changes...

...commit them to develop...

...merge them into master...

git checkout master
git pull
git merge develop

Uncaught TypeError: Cannot read property 'value' of undefined

First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like

if (typeof document.getElementsByName("username")[0] != 'undefined')

Similarly for the other element password.

What’s the best way to check if a file exists in C++? (cross platform)

If your compiler supports C++17 you don't need boost, you can simply use std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>

if (!std::filesystem::exists("myfile.txt"))
{
    std::cout << "File not found!" << std::endl;
}

How to output MySQL query results in CSV format?

From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Using this command columns names will not be exported.

Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

Notice: Trying to get property of non-object error

This is because $pjs is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.

echo $pjs[0]->player_name;

Actually dump result that you pasted tells it very clearly.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.

Biggest advantage to using ASP.Net MVC vs web forms

  1. Proper AJAX, e.g. JSONResults no partial page postback nonsense.
  2. no viewstate +1
  3. No renaming of the HTML IDs.
  4. Clean HTML = no bloat and having a decent shot at rendering XHTML or standards compliant pages.
  5. No more generated AXD javascript.

Fade In Fade Out Android Animation in Java

You can also use animationListener, something like this:

fadeIn.setAnimationListener(new AnimationListener() {
    @Override
    public void onAnimationEnd(Animation animation) {
        this.startAnimation(fadeout);
    }
});

jQuery scroll() detect when user stops scrolling

Ok this is something that I've used before. Basically you look a hold a ref to the last scrollTop(). Once your timeout clears, you check the current scrollTop() and if they are the same, you are done scrolling.

$(window).scroll((e) ->
  clearTimeout(scrollTimer)
  $('header').addClass('hidden')

  scrollTimer = setTimeout((() ->
    if $(this).scrollTop() is currentScrollTop
      $('header').removeClass('hidden') 
  ), animationDuration)

  currentScrollTop = $(this).scrollTop()
)

Difference between hamiltonian path and euler path

An Euler path is a path that passes through every edge exactly once. If it ends at the initial vertex then it is an Euler cycle.

A Hamiltonian path is a path that passes through every vertex exactly once (NOT every edge). If it ends at the initial vertex then it is a Hamiltonian cycle.

In an Euler path you might pass through a vertex more than once.

In a Hamiltonian path you may not pass through all edges.

Best tool for inspecting PDF files?

I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:

// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;                                                                                                                                                                                                          
doc = PDDocument.load(filename);

// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
    //System.out.println(o.toString() + " " + dict.getString(o));
    System.out.println(o.toString());
}

// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);

List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());

How can I show/hide component with JSF?

You can actually accomplish this without JavaScript, using only JSF's rendered attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:

<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
    <f:selectItem itemValue="O" itemLabel="Originator" />
    <f:selectItem itemValue="R" itemLabel="Role" />
    <f:selectItem itemValue="E" itemLabel="Employee" />
    <f:ajax event="change" execute="@this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
    <h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'R'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.roles}" />
    </h:selectOneMenu>
    <h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'E'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.employees}" />
    </h:selectOneMenu>
</h:panelGroup>

How to launch an application from a browser?

We use a sonicwall vpn. It launches a java applet that launches mstc with all the credentials setup. You really can't do this without a java applet or activex plugin.

Microsoft uses this technique itself on their small business server for getting inside the network. I wouldn't say it is a terrible idea, as long as platform independence isn't important.

Calling jQuery method from onClick attribute in HTML

I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:

function showMessage(msg) {
   alert(msg);
};

<input type="button" value="ahaha" onclick="showMessage('msg');" />

UPDATE: With a small change to how your method is defined I can get it to work:

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script language="javascript">
    // define the function within the global scope
    $.fn.MessageBox = function(msg) {
        alert(msg);
    };

    // or, if you want to encapsulate variables within the plugin
    (function($) {
        $.fn.MessageBoxScoped = function(msg) {
            alert(msg);
        };
    })(jQuery); //<-- make sure you pass jQuery into the $ parameter
 </script>
</head>
<body>
 <div class="Title">Welcome!</div>
 <input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>

Access event to call preventdefault from custom function originating from onclick attribute of tag

Without any JS library or jQuery. To open a nice popup window if possible. Fails safely to normal link open.

<a href="https://acme.com/" onclick="onclick="openNewWindow(event, this.href);">...</a>

And the helper function:

function openNewWindow(event, location) {
  if (event.preventDefault && event.stopImmediatePropagation) { 
    event.preventDefault(); 
    event.stopImmediatePropagation(); 
  } else {
    event.returnValue = false; 
  }
  window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}

Set Radiobuttonlist Selected from Codebehind

The best option, in my opinion, is to use the Value property for the ListItem, which is available in the RadioButtonList.

I must remark that ListItem does NOT have an ID property.

So, in your case, to select the second element (option2) that would be:

// SelectedValue expects a string
radio1.SelectedValue = "1"; 

Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.

// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1; 

Right Align button in horizontal LinearLayout

Use layout width in the button like android:layout_width="75dp"

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to create a fix size list in python?

fix_array = numpy.empty(n, dtype = object)

where n is the size of your array

though it works, it may not be the best idea as you have to import a library for this purpose. Hope this helps!

Version vs build in Xcode

The marketing release number is for the customers, called version number. It starts with 1.0 and goes up for major updates to 2.0, 3.0, for minor updates to 1.1, 1.2 and for bug fixes to 1.0.1, 1.0.2 . This number is oriented about releases and new features.

The build number is mostly the internal number of builds that have been made until then. But some use other numbers like the branch number of the repository. This number should be unique to distinguish the different nearly the same builds.

As you can see, the build number is not necessary and it is up to you which build number you want to use. So if you update your Xcode to a major version, the build field is empty. The version field may not be empty!.


To get the build number as a NSString variable:

NSString * appBuildString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

To get the version number as a NSString variable:

NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

If you want both in one NSString:

NSString * versionBuildString = [NSString stringWithFormat:@"Version: %@ (%@)", appVersionString, appBuildString];

This is tested with Xcode Version 4.6.3 (4H1503). The build number is often written in parenthesis / braces. The build number is in hexadecimal or decimal.

buildandversion


In Xcode you can auto-increment the build number as a decimal number by placing the following in the Run script build phase in the project settings

#!/bin/bash    
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

For hexadecimal build number use this script

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$((0x$buildNumber)) 
buildNumber=$(($buildNumber + 1)) 
buildNumber=$(printf "%X" $buildNumber)
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

project_settings

Cannot overwrite model once compiled Mongoose

So Another Reason why You might get this Error is if you use the same model in different files but your require path has a different case. For example in my situation I had:

require('./models/User') in one file and then in another file where I needed access to the User model I had require('./models/user').

I guess the look up for modules & mongoose is treating it as a different file. Once I made sure the case matched in both it was no longer an issue.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Check if object is a jQuery object

You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/

var a = { what: "A regular JS object" },
b = $('body');

if ( a.jquery ) { // falsy, since it's undefined
    alert(' a is a jQuery object! ');    
}

if ( b.jquery ) { // truthy, since it's a string
    alert(' b is a jQuery object! ');
}

How to stick text to the bottom of the page?

Try this

 <head>
 <style type ="text/css" >
   .footer{ 
       position: fixed;     
       text-align: center;    
       bottom: 0px; 
       width: 100%;
   }  
</style>
</head>
<body>
    <div class="footer">All Rights Reserved</div>
</body>

How to plot a subset of a data frame in R?

Most straightforward option:

plot(var1[var3<155],var2[var3<155])

It does not look good because of code redundancy, but is ok for fastndirty hacking.

Check if a string is a valid date using DateTime.TryParse

If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

DateTime.TryParse

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output: 
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

background:none vs background:transparent what is the difference?

As aditional information on @Quentin answer, and as he rightly says, background CSS property itself, is a shorthand for:

background-color
background-image
background-repeat
background-attachment
background-position

That's mean, you can group all styles in one, like:

background: red url(../img.jpg) 0 0 no-repeat fixed;

This would be (in this example):

background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;

So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none; and all the others to the initial state (as they are not being declared).
So, background:none; is:

background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

Now, when you define only the color (in your case transparent) then you are basically saying:

background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

I repeat, as @Quentin rightly says the default transparent and none values in this case are the same, so in your example and for your original question, No, there's no difference between them.

But!.. if you say background:none Vs background:red then yes... there's a big diference, as I say, the first would set all properties to none/default and the second one, will only change the color and remains the rest in his default state.

So in brief:

Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.


Upd1: Initial value (aka default)

Initial value the concatenation of the initial values of its longhand properties:

background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent

See more background descriptions here


Upd2: Clarify better the background:none; specification.

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

Process to convert simple Python script into Windows executable

Using py2exe, include this in your setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1}},
    windows = [{'script': "YourScript.py"}],
    zipfile = None,
)

then you can run it through command prompt / Idle, both works for me. Hope it helps

Javascript require() function giving ReferenceError: require is not defined

For me the issue was I did not have my webpack build mode set to production for the package I was referencing in. Explicitly setting it to "build": "webpack --mode production" fixed the issue.

Connect to mysql in a docker container from the host

change "localhost" to your real con ip addr
because it's to mysql_connect()

SHA512 vs. Blowfish and Bcrypt

I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").

You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

How to get Real IP from Visitor?

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

Avoid line break between html elements

CSS for that td: white-space: nowrap; should solve it.

Add a linebreak in an HTML text area

I believe this will work:

TextArea.Text = "Line 1" & vbCrLf & "Line 2"

System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

cannot call member function without object

If you want to call them like that, you should declare them static.

How do I get the classes of all columns in a data frame?

I wanted a more compact output than the great answers above using lapply, so here's an alternative wrapped as a small function.

# Example data
df <-
    data.frame(
        w = seq.int(10),
        x = LETTERS[seq.int(10)],
        y = factor(letters[seq.int(10)]),
        z = seq(
            as.POSIXct('2020-01-01'),
            as.POSIXct('2020-10-01'),
            length.out = 10
        )
    )

# Function returning compact column classes
col_classes <- function(df) {
    t(as.data.frame(lapply(df, function(x) paste(class(x), collapse = ','))))
}

# Return example data's column classes
col_classes(df)
  [,1]            
w "integer"       
x "character"     
y "factor"        
z "POSIXct,POSIXt"

Capturing mobile phone traffic on Wireshark

Similarly to making your PC a wireless access point, but can be much easier, is using reverse tethering. If you happen to have an HTC phone they have a nice reverse-tethering option called "Internet pass-through", under the network/mobile network sharing settings. It routes all your traffic through your PC and you can just run Wireshark there.

Check if number is decimal

$lat = '-25.3654';

if(preg_match('/./',$lat)) {
    echo "\nYes its a decimal value\n";
}
else{
    echo 'No its not a decimal value';
}

Splitting String and put it on int array

For input 1,2,3,4,5 the input is of length 9. 9/2 = 4 in integer math, so you're only storing the first four variables, not all 5.

Even if you fixed that, it would break horribly if you passed in an input of 10,11,12,13

It would work (by chance) if you used 1,2,3,4,50 for an input, strangely enough :-)

You would be much better off doing something like this

String[] strArray = input.split(",");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);
}

For future reference, when you get an error, I highly recommend posting it with the code. You might not have someone with a jdk readily available to compile the code to debug it! :)

Left-pad printf with spaces

int space = 40;
printf("%*s", space, "Hello");

This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:

printf("%*d", space, 10);
printf("%*c", space, 'x');

This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:

printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");

Hope this helps someone like me in future.

How to make <label> and <input> appear on the same line on an HTML form?

aaa##HTML I would suggest you wrap them in a div, since you will likely end up floating them in certain contexts.

<div class="input-w">
    <label for="your-input">Your label</label>
    <input type="text" id="your-input" />
</div>

CSS

Then within that div, you can make each piece inline-block so that you can use vertical-align to center them - or set baseline etc. (your labels and input might change sizes in the future...

.input-w label, .input-w input {
    float: none; /* if you had floats before? otherwise inline-block will behave differently */
    display: inline-block;
    vertical-align: middle;    
}

jsFiddle

UPDATE: mid 2016 + with mobile-first media queries and flex-box

This is how I do things these days.

HTML

<label class='input-w' for='this-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-input-name' placeholder='hello'>
</label>

<label class='input-w' for='this-other-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-other-input-name' placeholder='again'>
</label>

SCSS

html { // https://www.paulirish.com/2012/box-sizing-border-box-ftw/
  box-sizing: border-box;
  *, *:before, *:after {
    box-sizing: inherit;
  }
} // if you don't already reset your box-model, read about it

.input-w {
  display: block;
  width: 100%; // should be contained by a form or something
  margin-bottom: 1rem;
  @media (min-width: 500px) {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .label, .input {
    display: block;
    width: 100%;
    border: 1px solid rgba(0,0,0,.1);
    @media (min-width: 500px) {
      width: auto;
      display: flex;
    }
  }
  .label {
    font-size: 13px;
    @media (min-width: 500px) {
      /* margin-right: 1rem; */
      min-width: 100px; // maybe to match many?
    }
  }
  .input {
    padding: .5rem;
    font-size: 16px;
    @media (min-width: 500px) {
      flex-grow: 1;
      max-width: 450px; // arbitrary
    }
  }
}

jsFiddle

In C - check if a char exists in a char array

use strchr function when dealing with C strings.

const char * strchr ( const char * str, int character );

Here is an example of what you want to do.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char invalids[] = ".@<>#";
  char * pch;
  pch=strchr(invalids,'s');//is s an invalid character?
  if (pch!=NULL)
  {
    printf ("Invalid character");
  }
  else 
  {
     printf("Valid character");
  } 
  return 0;
}

Use memchr when dealing with memory blocks (as not null terminated arrays)

const void * memchr ( const void * ptr, int value, size_t num );

/* memchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char * pch;
  char invalids[] = "@<>#";
  pch = (char*) memchr (invalids, 'p', strlen(invalids));
  if (pch!=NULL)
    printf (p is an invalid character);
  else
    printf ("p valid character.\n");
  return 0;
}

http://www.cplusplus.com/reference/clibrary/cstring/memchr/

http://www.cplusplus.com/reference/clibrary/cstring/strchr/

What's the better (cleaner) way to ignore output in PowerShell?

Personally, I use ... | Out-Null because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null and [void] .... $null = ... is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null and ... > $null come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null), compared to putting $null = or [void] before the expression to determine what happens after executing it.

Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help command or your favorite search engine to try to find out what Out-Null does. You get a useful result immediately, right? Now try to do the same with [void] and $null =. Not so easy, is it?

Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void], $null =, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*

* I am presuming that Out-Null is clear and well-known, which I don't know to be $true. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.

How to change options of <select> with jQuery?

Removing and adding DOM element is slower than modification of existing one.

If your option sets have same length, you may do something like this:

$('#my-select option')
.each(function(index) {
    $(this).text('someNewText').val('someNewValue');
});

In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.

Does C# support multiple inheritance?

C# does not support multiple inheritance of classes, but you are permitted to inherit/implement any number of interfaces.

This is illegal (B, C, D & E are all classes)

class A : B, C, D, E
{
}

This is legal (IB, IC, ID & IE are all interfaces)

class A : IB, IC, ID, IE
{
}

This is legal (B is a class, IC, ID & IE are interfaces)

class A : B, IC, ID, IE
{
}

Composition over inheritance is a design pattern that seems to be favorable even in languages that support multiple inheritance.

How do I get the first element from an IEnumerable<T> in .net?

If you can use LINQ you can use:

var e = enumerable.First();

This will throw an exception though if enumerable is empty: in which case you can use:

var e = enumerable.FirstOrDefault();

FirstOrDefault() will return default(T) if the enumerable is empty, which will be null for reference types or the default 'zero-value' for value types.

If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator and MoveNext methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>):

Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
    if (enumer.MoveNext()) e = enumer.Current;
}

Joel Coehoorn mentioned .Single() in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault() method that covers this scenario in a similar fashion to FirstOrDefault(). However, David B explains that SingleOrDefault() may still throw an exception in the case where the enumerable contains more than one item.

Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator object after using it - I've edited the non-LINQ example to display the using keyword to implement this pattern.

Submit form on pressing Enter with AngularJS

Use ng-submit and just wrap both inputs in separate form tags:

<div ng-controller="mycontroller">

  <form ng-submit="myFunc()">
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
  </form>

  <br />

  <form ng-submit="myFunc()">
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
  </form>

</div>

Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.

HTTP Content-Type Header and JSON

Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.

SonarQube not picking up Unit Test Coverage

The presence of argLine configurations in either of surefire and jacoco plugins stops the jacoco report generation. The argLine should be defined in properties

<properties>
  <argLine>your jvm options here</argLine>
</properties>

Material Design not styling alert dialogs

You can consider this project: https://github.com/fengdai/AlertDialogPro

It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

How to show PIL Image in ipython notebook

If you are using the pylab extension, you could convert the image to a numpy array and use matplotlib's imshow.

%pylab # only if not started with the --pylab option
imshow(array(pil_im))

EDIT: As mentioned in the comments, the pylab module is deprecated, so use the matplotlib magic instead and import the function explicitly:

%matplotlib
from matplotlib.pyplot import imshow 
imshow(array(pil_im))

Required attribute on multiple checkboxes with the same name?

To provide another approach similar to the answer by @IvanCollantes. It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var requiredCheckboxes = $(':checkbox[required]');_x000D_
  requiredCheckboxes.on('change', function(e) {_x000D_
    var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
    var isChecked = checkboxGroup.is(':checked');_x000D_
    checkboxGroup.prop('required', !isChecked);_x000D_
  });_x000D_
  requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
  <p>_x000D_
    At least one checkbox from each group is required..._x000D_
  </p>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <br>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test2</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <hr>_x000D_
  <button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

Database, Table and Column Naming Conventions?

  1. Definitely keep table names singular, person not people
    1. Same here
    2. No. I've seen some terrible prefixes, going so far as to state what were dealing with is a table (tbl_) or a user store procedure (usp_). This followed by the database name... Don't do it!
    3. Yes. I tend to PascalCase all my table names

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Shorter in Swift 4/5:

var string = "123456"
string = String(string.prefix(3)) //"123"
string = String(string.suffix(3)) //"456"

How to print the contents of RDD?

In java syntax:

rdd.collect().forEach(line -> System.out.println(line));

Swift Bridging Header import issue

Be careful to add the file to the folder that your error is complaining! I've made the same mistake, if you create the file from Xcode, it will go to the folder: Project->Project->Header.h

And Xcode is looking for Project->Header.h

That means you need to put the file inside your project folder (ProjectName->ProjectNameFolder)!

Hope that helps ;)

UPDATED: I'm not sure if I got what you mean, but try this to solve your problem:
1. Delete all your bridging files that you created until now.
2. Select the main folder of project and hit new file->iOS->Header file.
3. Write your imports in the header file created.
4. Select the project inside Xcode->Build Settings, type in search field: bridging and put in the key SWIFT_OBJC_BRIDGING_HEADER the name of your header file or the path to it!

If you follow this steps, your header file will be created at the correct location!

:D Hope that helps!

How to use GNU Make on Windows?

I'm using GNU Make from the GnuWin32 project, see http://gnuwin32.sourceforge.net/ but there haven't been any updates for a while now, so I'm not sure on this project's status.

concatenate variables

If you need to concatenate paths with quotes, you can use = to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.

@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"

rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%

rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

In my case the error was caused by the lack of space on my machine. Deleting old builds fixed the problem.

Android getResources().getDrawable() deprecated API 22

In Kotlin you can use extension

fun Context.getMyDrawable(id : Int) : Drawable?{

    return  ContextCompat.getDrawable(this, id)
}

then use like

context.getMyDrawable(R.drawable.my_icon)

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

How do I move an existing Git submodule within a Git repository?

Note: As mentioned in the comments this answer refers to the steps needed with older versions of git. Git now has native support for moving submodules:

Since git 1.8.5, git mv old/submod new/submod works as expected and does all the plumbing for you. You might want to use git 1.9.3 or newer, because it includes fixes for submodule moving.


The process is similar to how you'd remove a submodule (see How do I remove a submodule?):

  1. Edit .gitmodules and change the path of the submodule appropriately, and put it in the index with git add .gitmodules.
  2. If needed, create the parent directory of the new location of the submodule (mkdir -p new/parent).
  3. Move all content from the old to the new directory (mv -vi old/parent/submodule new/parent/submodule).
  4. Make sure Git tracks this directory (git add new/parent).
  5. Remove the old directory with git rm --cached old/parent/submodule.
  6. Move the directory .git/modules/old/parent/submodule with all its content to .git/modules/new/parent/submodule.
  7. Edit the .git/modules/new/parent/config file, make sure that worktree item points to the new locations, so in this example it should be worktree = ../../../../../new/parent/module. Typically there should be two more .. than directories in the direct path in that place.
  8. Edit the file new/parent/module/.git, make sure that the path in it points to the correct new location inside the main project .git folder, so in this example gitdir: ../../../.git/modules/new/parent/submodule.

    git status output looks like this for me afterwards:

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #       modified:   .gitmodules
    #       renamed:    old/parent/submodule -> new/parent/submodule
    #
    
  9. Finally, commit the changes.

Android Studio gradle takes too long to build

I had a similar issue on my computer. Windows Defender was blocking some part of Gradle Building. I've disabled it, worked fine after that.

java.lang.IllegalAccessError: tried to access method

This happened to me when I had a class in one jar trying to access a private method in a class from another jar. I simply changed the private method to public, recompiled and deployed, and it worked ok afterwards.

Ruby: Can I write multi-line string with no concatenation?

Sometimes is worth to remove new line characters \n like:

conn.exec <<-eos.squish
 select attr1, attr2, attr3, attr4, attr5, attr6, attr7
 from table1, table2, table3, etc, etc, etc, etc, etc,
 where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How can I strip first X characters from string using sed?

Here's a concise method to cut the first X characters using cut(1). This example removes the first 4 characters by cutting a substring starting with 5th character.

echo "$pid" | cut -c 5-

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

How to embed matplotlib in pyqt - for Dummies

Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

How do I use this JavaScript variable in HTML?

You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.

Android: how to convert whole ImageView to Bitmap?

You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.

just make sure it built.

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

there's your bitmap as the screen saw it.

Check if a key exists inside a json object

You can try if(typeof object !== 'undefined')

Short rot13 function - Python

def rot13(s):
    lower_chars = ''.join(chr(c) for c in range (97,123)) #ASCII a-z
    upper_chars = ''.join(chr(c) for c in range (65,91)) #ASCII A-Z
    lower_encode = lower_chars[13:] + lower_chars[:13] #shift 13 bytes
    upper_encode = upper_chars[13:] + upper_chars[:13] #shift 13 bytes
    output = "" #outputstring
    for c in s:
        if c in lower_chars:
                output = output + lower_encode[lower_chars.find(c)]
        elif c in upper_chars:
            output = output + upper_encode[upper_chars.find(c)]
        else:
            output = output + c
    return output

Another solution with shifting. Maybe this code helps other people to understand rot13 better. Haven't tested it completely.

Create or update mapping in elasticsearch

Generally speaking, you can update your index mapping using the put mapping api (reference here) :

curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
    "advert_type" : {
        "properties" : {

          //your new mapping properties

        }
    }
}
'

It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.

You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.

Finally, you will have to reindex your data for your new mapping to be taken into account.

The best solution would really be to create a new index.

If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.

Best way to replace multiple characters in a string?

Here is a python3 method using str.translate and str.maketrans:

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

The printed string is abc\&def\#ghi.

Secure FTP using Windows batch script

First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).

Neither is supported by Windows command-line ftp.exe. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.

Using WinSCP, your batch file would look like (for SFTP):

echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

And the batch file:

winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%

Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP% syntax), the batch file simplifies to:

winscp.com /log=ftpcmd.log /command ^
    "open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

For the purpose of -hostkey switch, see verifying the host key in script.

Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:

Generate batch file

All you need to tweak is the source file name (use the %TIMESTAMP% syntax as shown previously) and the path to the log file.


For FTPS, replace the sftp:// in the open command with ftpes:// (explicit TLS/SSL) or ftps:// (implicit TLS/SSL). Remove the -hostkey switch.

winscp.com /log=ftpcmd.log /command ^
    "open ftps://ftp_user:[email protected] -explicit" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

You may need to add the -certificate switch, if your server's certificate is not issued by a trusted authority.

Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.


See a complete conversion guide from ftp.exe to WinSCP.

You should also read the Guide to automating file transfers to FTP server or SFTP server.


Note to using %TIMESTAMP#yyyymmdd% instead of %date%: A format of %date% variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date% resolves to ct 06. 11. 2014, what might be problematic when used as a part of a file name.

For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd% resolves to 20170515 on any locale.

(I'm the author of WinSCP)

How can I execute a python script from an html button?

There are various ways to make it done, very simple technique with security peace in mind, here might help you


1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code. If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)

2.Create a new folder
- 1st file will be server.py

_x000D_
_x000D_
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
  return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
  print ('I got clicked!')_x000D_
_x000D_
  return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
  app.run(debug=True)
_x000D_
_x000D_
_x000D_

-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html

_x000D_
_x000D_
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
    <meta charset=utf-8> </head>_x000D_
    <body>_x000D_
        <h1>My Website</h1>_x000D_
        <form action="/my-link/">_x000D_
            <input type="submit" value="Click me" />_x000D_
        </form>_x000D_
        _x000D_
        <button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
    </body>
_x000D_
_x000D_
_x000D_

3.. To run, open command prompt to the New folder directory, type python server.py to run the script, then go to browser type localhost:5000, then you will see button. You can click and route to destination script file you created.

Hope this helpful. thank you.

How to fix C++ error: expected unqualified-id

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

Try with /debug.1,2 As in :

signtool sign /debug /f mypfxfile.pfx /p <password> (mydllexectuable).exe

It will help you find out what is going on. You should get output like this:

The following certificates were considered:
    Issued to: <issuer>
    Issued by: <certificate authority> Class 2 Primary Intermediate Server CA
    Expires:   Sun Mar 01 14:18:23 2015
    SHA1 hash: DD0000000000000000000000000000000000D93E

    Issued to: <certificate authority> Certification Authority
    Issued by: <certificate authority> Certification Authority
    Expires:   Wed Sep 17 12:46:36 2036
    SHA1 hash: 3E0000000000000000000000000000000000000F

After EKU filter, 2 certs were left.
After expiry filter, 2 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.

You can see what filter is causing your certificate to not work, or if no certificates were considered.

I changed the hashes and other info, but you should get the idea. Hope this helps.


1 Please note: signtool is particular about where the /debug option is placed. It needs to go after the sign statement.
2 Also note: the /debug option only works with some versions of signtool. The WDK version has the option, whereas the Windows SDK version does not.

get unique machine id

I'd stay well away from using MAC addresses. On some hardware, the MAC address can change when you reboot. We learned quite early during our research not to rely on it.

Take a look at the article Developing for Software Protection and Licensing which has some pointers on how to design & implement apps to reduce piracy.

Obligatory disclaimer & plug: the company I co-founded produces the OffByZero Cobalt licensing solution. So it probably won't surprise you to hear that I recommend outsourcing your licensing, & focusing on your core competencies.

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

PHP Checking if the current date is before or after a set date

Here's a list of all possible checks for …

"Did a date pass?"

Possible ways to obtain the value

$date = strtotime( $date );

$date > date( "U" )
$date > mktime( 0, 0, 0 )
$date > strtotime( 'now' )
$date > time()
$date > abs( intval( $_SERVER['REQUEST_TIME'] ) )

Performance Test Result (PHP 5.4.7)

I did some performance test on 1.000.000 iterations and calculated the average – Ordered fastest to slowest.

+---------------------+---------------+
|        method       |     time      |
+---------------------+---------------+
|        time()       | 0.0000006732  |
|       $_SERVER      | 0.0000009131  |
|      date("U")      | 0.0000028951  |
|     mktime(0,0,0)   | 0.000003906   |
|   strtotime("now")  | 0.0000045032  |
| new DateTime("now") | 0.0000053365  |
+---------------------+---------------+

ProTip: You can easily remember what's fastest by simply looking at the length of the function. The longer, the slower the function is.

Performance Test Setup

The following loop was run for each of the above mentioned possibilities. I converted the values to non-scientific notation for easier readability.

$loops = 1000000;
$start = microtime( true );
for ( $i = 0; $i < $loops; $i++ )
    date( "U" );
printf(
    '|    date("U")     | %s  |'."\n",
    rtrim( sprintf( '%.10F', ( microtime( true ) - $start ) / $loops ), '0' )
);

Conclusion

time() still seems to be the fastest.