Programs & Examples On #Srp protocol

How can I detect browser type using jQuery?

The best solution is probably: use Modernizr.

However, if you necessarily want to use $.browser property, you can do it using jQuery Migrate plugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:

if($.browser.chrome) {
   alert(1);
} else if ($.browser.mozilla) {
   alert(2);
} else if ($.browser.msie) {
   alert(3);
}

And if you need for some reason to use navigator.userAgent, then it would be:

$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase()); 
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase()); 

Best way to generate xml?

I've tried a some of the solutions in this thread, and unfortunately, I found some of them to be cumbersome (i.e. requiring excessive effort when doing something non-trivial) and inelegant. Consequently, I thought I'd throw my preferred solution, web2py HTML helper objects, into the mix.

First, install the the standalone web2py module:

pip install web2py

Unfortunately, the above installs an extremely antiquated version of web2py, but it'll be good enough for this example. The updated source is here.

Import web2py HTML helper objects documented here.

from gluon.html import *

Now, you can use web2py helpers to generate XML/HTML.

words = ['this', 'is', 'my', 'item', 'list']
# helper function
create_item = lambda idx, word: LI(word, _id = 'item_%s' % idx, _class = 'item')
# create the HTML
items = [create_item(idx, word) for idx,word in enumerate(words)]
ul = UL(items, _id = 'my_item_list', _class = 'item_list')
my_div = DIV(ul, _class = 'container')

>>> my_div

<gluon.html.DIV object at 0x00000000039DEAC8>

>>> my_div.xml()
# I added the line breaks for clarity
<div class="container">
   <ul class="item_list" id="my_item_list">
      <li class="item" id="item_0">this</li>
      <li class="item" id="item_1">is</li>
      <li class="item" id="item_2">my</li>
      <li class="item" id="item_3">item</li>
      <li class="item" id="item_4">list</li>
   </ul>
</div>

Jackson overcoming underscores in favor of camel-case

You can configure the ObjectMapper to convert camel case to names with an underscore:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

Or annotate a specific model class with this annotation:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Before Jackson 2.7, the constant was named:

PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

How can I quickly sum all numbers in a file?

Here's another:

open(FIL, "a.txt");

my $sum = 0;
foreach( <FIL> ) {chomp; $sum += $_;}

close(FIL);

print "Sum = $sum\n";

Getting the number of filled cells in a column (VBA)

One way is to: (Assumes index column begins at A1)

MsgBox Range("A1").End(xlDown).Row

Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.

You can select the next empty cell with:

Range("A1").End(xlDown).Offset(1, 0).Select

If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row

Parse a URI String into Name-Value Collection

Answering here because this is a popular thread. This is a clean solution in Kotlin that uses the recommended UrlQuerySanitizer api. See the official documentation. I have added a string builder to concatenate and display the params.

    var myURL: String? = null

    if (intent.hasExtra("my_value")) {
        myURL = intent.extras.getString("my_value")
    } else {
        myURL = intent.dataString
    }

    val sanitizer = UrlQuerySanitizer(myURL)
    // We don't want to manually define every expected query *key*, so we set this to true
    sanitizer.allowUnregisteredParamaters = true
    val parameterNamesToValues: List<UrlQuerySanitizer.ParameterValuePair> = sanitizer.parameterList
    val parameterIterator: Iterator<UrlQuerySanitizer.ParameterValuePair> = parameterNamesToValues.iterator()

    // Helper simply so we can display all values on screen
    val stringBuilder = StringBuilder()

    while (parameterIterator.hasNext()) {
        val parameterValuePair: UrlQuerySanitizer.ParameterValuePair = parameterIterator.next()
        val parameterName: String = parameterValuePair.mParameter
        val parameterValue: String = parameterValuePair.mValue

        // Append string to display all key value pairs
        stringBuilder.append("Key: $parameterName\nValue: $parameterValue\n\n")
    }

    // Set a textView's text to display the string
    val paramListString = stringBuilder.toString()
    val textView: TextView = findViewById(R.id.activity_title) as TextView
    textView.text = "Paramlist is \n\n$paramListString"

    // to check if the url has specific keys
    if (sanitizer.hasParameter("type")) {
        val type = sanitizer.getValue("type")
        println("sanitizer has type param $type")
    }

Custom header to HttpClient request

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

HTTP Request in Kotlin

import java.io.IOException
import java.net.URL

fun main(vararg args: String) {
    val response = try {
        URL("http://seznam.cz")
                .openStream()
                .bufferedReader()
                .use { it.readText() }
    } catch (e: IOException) {
        "Error with ${e.message}."
    }
    println(response)
}

How to get the body's content of an iframe in Javascript?

use content in iframe with JS:

document.getElementById('id_iframe').contentWindow.document.write('content');

Enable vertical scrolling on textarea

Simply, change

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>

to

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>

ie, add:

data-role="none"

How to uninstall Eclipse?

Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..

Get the current fragment object

you can check which fragment is currently loaded by this

        supportFragmentManager.addOnBackStackChangedListener {
        val myFragment = supportFragmentManager.fragments.last()

        if (null != myFragment && myFragment is HomeFragment) {
            //HomeFragment is visible or currently loaded
        } else {
            //your code
        }
    }

What does <> mean?

Yes, it's "not equal".

Reading numbers from a text file into an array in C

There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
        i++;
    }
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    }
    return 0;
}

Update Angular model after setting input value with jQuery

The accepted answer which was triggering input event with jQuery didn't work for me. Creating an event and dispatching with native JavaScript did the trick.

$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));

How to modify a text file?

Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:
     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

Can't load IA 32-bit .dll on a AMD 64-bit platform

Short answer to first question: yes.

Longer answer: maybe; it depends on whether the build process for SVMLight behaves itself on 64-bit windows.

Final note: that call to System.loadLibrary is silly. Either call System.load with a full pathname or let it search java.library.path.

Maven: mvn command not found

I think the problem is with the spaces. I had my variable at the System variables but it didn't work. When I changed variable Progra~1 = 'Program Files' everything works fine.

M2_HOME C:\Progra~1\Maven\apache-maven-3.1.1

I also moved my M2_HOME at the end of the PATH(%M2_HOME%\bin) I'm not sure if this has any difference.

ReactJS: Maximum update depth exceeded error

I know this has plenty of answers but since most of them are old (well, older), none is mentioning approach I grow very fond of really quick. In short:

Use functional components and hooks.

In longer:

Try to use as much functional components instead class ones especially for rendering, AND try to keep them as pure as possible (yes, data is dirty by default I know).

Two bluntly obvious benefits of functional components (there are more):

  • Pureness or near pureness makes debugging so much easier
  • Functional components remove the need for constructor boiler code

Quick proof for 2nd point - Isn't this absolutely disgusting?

constructor(props) {
        super(props);     
        this.toggle= this.toggle.bind(this);
        this.state = {
            details: false
        } 
    }  

If you are using functional components for more then rendering you are gonna need the second part of great duo - hooks. Why are they better then lifecycle methods, what else can they do and much more would take me a lot of space to cover so I recommend you to listen to the man himself: Dan preaching the hooks

In this case you need only two hooks:

A callback hook conveniently named useCallback. This way you are preventing the binding the function over and over when you re-render.

A state hook, called useState, for keeping the state despite entire component being function and executing in its entirety (yes, this is possible due to magic of hooks). Within that hook you will store the value of toggle.

If you read to this part you probably wanna see all I have talked about in action and applied to original problem. Here you go: Demo

For those of you that want only to glance the component and WTF is this about, here you are:

const Item = () => {

    // HOOKZ
  const [isVisible, setIsVisible] = React.useState('hidden');

  const toggle = React.useCallback(() => {
    setIsVisible(isVisible === 'visible' ? 'hidden': 'visible');
  }, [isVisible, setIsVisible]);

    // RENDER
  return (
  <React.Fragment>
    <div style={{visibility: isVisible}}>
        PLACEHOLDER MORE INFO
    </div>
    <button onClick={toggle}>Details</button>
  </React.Fragment>
  )
};

PS: I wrote this in case many people land here with similar problem. Hopefully, they will like what I have shown here, at least well enough to google it a bit more. This is NOT me saying other answers are wrong, this is me saying that since the time they have been written, there is another way (IMHO, a better one) of dealing with this.

How do I tar a directory of files and folders without including the directory itself?

This Answer should work in most situations. Notice however how the filenames are stored in the tar file as, for example, ./file1 rather than just file1. I found that this caused problems when using this method to manipulate tarballs used as package files in BuildRoot.

One solution is to use some Bash globs to list all files except for .. like this:

tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *

This is a trick I learnt from this answer.

Now tar will return an error if there are no files matching ..?* or .[^.]* , but it will still work. If the error is a problem (you are checking for success in a script), this works:

shopt -s nullglob
tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
shopt -u nullglob

Though now we are messing with shell options, we might decide that it is neater to have * match hidden files:

shopt -s dotglob
tar -C my_dir -zcvf my_dir.tar.gz *
shopt -u dotglob

This might not work where your shell globs * in the current directory, so alternatively, use:

shopt -s dotglob
cd my_dir
tar -zcvf ../my_dir.tar.gz *
cd ..
shopt -u dotglob

enabling cross-origin resource sharing on IIS7

One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
  </customHeaders>
</httpProtocol>

Convert regular Python string to raw string

Since strings in Python are immutable, you cannot "make it" anything different. You can however, create a new raw string from s, like this:

raw_s = r'{}'.format(s)

WordPress - Check if user is logged in

Example: Display different output depending on whether the user is logged in or not.

<?php

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';
}

?>

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

How do I pipe or redirect the output of curl -v?

add the -s (silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body

curl -vs google.com 2>&1 | less

Pandas Merge - How to avoid duplicating columns

This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:

def merge_fix_cols(df_company,df_product,uniqueID):
    
    df_merged = pd.merge(df_company,
                         df_product,
                         how='left',left_on=uniqueID,right_on=uniqueID)    
    for col in df_merged:
        if col.endswith('_x'):
            df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
        elif col.endswith('_y'):
            to_drop = [col for col in df_merged if col.endswith('_y')]
            df_merged.drop(to_drop,axis=1,inplace=True)
        else:
            pass
    return df_merged

Seems to work well with my merges!

How to set the text color of TextView in code?

In Adapter you can set the text color by using this code:

holder.my_text_view = (TextView) convertView.findViewById(R.id.my_text_view);
holder.my_text_view.setTextColor(Color.parseColor("#FFFFFF"));

How do I add files and folders into GitHub repos?

You can add files using git add, example git add README, git add <folder>/*, or even git add *

Then use git commit -m "<Message>" to commit files

Finally git push -u origin master to push files.

When you make modifications run git status which gives you the list of files modified, add them using git add * for everything or you can specify each file individually, then git commit -m <message> and finally, git push -u origin master

Example - say you created a file README, running git status gives you

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   README

Run git add README, the files are staged for committing. Then run git status again, it should give you - the files have been added and ready for committing.

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   README
#

nothing added to commit but untracked files present (use "git add" to track)

Then run git commit -m 'Added README'

$ git commit -m 'Added README'
[master 6402a2e] Added README
  0 files changed, 0 insertions(+), 0 deletions(-)
  create mode 100644 README

Finally, git push -u origin master to push the remote branch master for the repository origin.

$ git push -u origin master
Counting objects: 4, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 267 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To [email protected]:xxx/xxx.git
   292c57a..6402a2e  master -> master
Branch master set up to track remote branch master from origin.

The files have been pushed successfully to the remote repository.

Running a git pull origin master to ensure you have absorbed any upstream changes

$ git pull origin master
remote: Counting objects: 12, done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 8 (delta 4), reused 7 (delta 3)
Unpacking objects: 100% (8/8), done.
From xxx.com:xxx/xxx
 * branch            master     -> FETCH_HEAD
Updating e0ef362..6402a2e
Fast-forward
 public/javascript/xxx.js |    5 ++---
 1 files changed, 2 insertions(+), 3 deletions(-)
 create mode 100644 README

If you do not want to merge the upstream changes with your local repository, run git fetch to fetch the changes and then git merge to merge the changes. git pull is just a combination of fetch and merge.

I have personally used gitimmersion - http://gitimmersion.com/ to get upto curve on git, its a step-by-step guide, if you need some documentation and help

How to have EditText with border in Android Lollipop

You can use a drawable. Create a drawable layout file in your drawable folder. Paste this code. You can as well modify it - border.xml.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
    android:width="1dp"
    android:color="@color/divider" />
<solid
    android:color="#00FFFFFF"
    android:paddingLeft="10dp"
    android:paddingTop="10dp"/>
<padding
    android:left="10dp"
    android:top="10dp"
    android:right="10dp"
    android:bottom="10dp" />
</shape>

in your EditText view, add

android:background="@drawable/border"

`export const` vs. `export default` in ES6

When you put default, its called default export. You can only have one default export per file and you can import it in another file with any name you want. When you don't put default, its called named export, you have to import it in another file using the same name with curly braces inside it.

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

How to start and stop/pause setInterval?

add is a local variable not a global variable try this

_x000D_
_x000D_
var add;_x000D_
var input = document.getElementById("input");_x000D_
_x000D_
function start() {_x000D_
  add = setInterval("input.value++", 1000);_x000D_
}_x000D_
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input type="button" onclick="clearInterval(add)" value="stop" />_x000D_
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

Match multiline text using regular expression

First, you're using the modifiers under an incorrect assumption.

Pattern.MULTILINE or (?m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).

Pattern.DOTALL or (?s) tells Java to allow the dot to match newline characters, too.

Second, in your case, the regex fails because you're using the matches() method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)* have matched.

So if you're simply looking for a string that starts with User Comments:, use the regex

^\s*User Comments:\s*(.*)

with the Pattern.DOTALL option:

Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
} 

ResultString will then contain the text after User Comments:

What does the 'L' in front a string mean in C++?

'L' means wchar_t, which, as opposed to a normal character, requires 16-bits of storage rather than 8-bits. Here's an example:

"A"    = 41
"ABC"  = 41 42 43
L"A"   = 00 41
L"ABC" = 00 41 00 42 00 43

A wchar_t is twice big as a simple char. In daily use you don't need to use wchar_t, but if you are using windows.h you are going to need it.

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

Check/Uncheck all the checkboxes in a table

$(document).ready(function () {

            var someObj = {};

            $("#checkAll").click(function () {
                $('.chk').prop('checked', this.checked);
            });

            $(".chk").click(function () {

                $("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
            });

            $("input:checkbox").change(function () {
                debugger;

                someObj.elementChecked = [];

                $("input:checkbox").each(function () {
                    if ($(this).is(":checked")) {
                        someObj.elementChecked.push($(this).attr("id"));

                    }

                });             
            });

            $("#button").click(function () {
                debugger;

                alert(someObj.elementChecked);

            });

        });
    </script>
</head>

<body>

    <ul class="chkAry">
        <li><input type="checkbox" id="checkAll" />Select All</li>

        <li><input class="chk" type="checkbox" id="Delhi">Delhi</li>

        <li><input class="chk" type="checkbox" id="Pune">Pune</li>

        <li><input class="chk" type="checkbox" id="Goa">Goa</li>

        <li><input class="chk" type="checkbox" id="Haryana">Haryana</li>

        <li><input class="chk" type="checkbox" id="Mohali">Mohali</li>

    </ul>
    <input type="button" id="button" value="Get" />

</body>

How to include *.so library in Android Studio?

To use native-library (so files) You need to add some codes in the "build.gradle" file.

This code is for cleaing "armeabi" directory and copying 'so' files into "armeabi" while 'clean project'.

task copyJniLibs(type: Copy) {
    from 'libs/armeabi'
    into 'src/main/jniLibs/armeabi'
}
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(copyJniLibs)
}
clean.dependsOn 'cleanCopyJniLibs'

I've been referred from the below. https://gist.github.com/pocmo/6461138

View HTTP headers in Google Chrome?

I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.

Press F12 on windows or ??I on a mac to bring up the Chrome developer tools.

Chrome developer tools headers tab

Explicitly select items from a list or tuple

It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like:

class MyList(list):

    def __getitem__(self, index):
        if isinstance(index, tuple):
            return [self[i] for i in index]
        return super(MyList, self).__getitem__(index)


seq = MyList("foo bar baaz quux mumble".split())
print seq[0]
print seq[2,4]
print seq[1::2]

printing

foo
['baaz', 'mumble']
['bar', 'quux']

How to send email attachments?

With my code you can send email attachments using gmail you will need to:

set your gmail address at "YOUR SMTP EMAIL HERE"

set your gmail account password at "YOUR SMTP PASSWORD HERE_"

In the ___EMAIL TO RECEIVE THE MESSAGE_ part you need to set the destination email address.

Alarm notification is the subject,

Someone has entered the room, picture attached is the body

["/home/pi/webcam.jpg"] is an image attachment.

#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

USERNAME = "___YOUR SMTP EMAIL HERE___"
PASSWORD = "__YOUR SMTP PASSWORD HERE___"

def sendMail(to, subject, text, files=[]):
    assert type(to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = USERNAME
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo_or_helo_if_needed()
    server.starttls()
    server.ehlo_or_helo_if_needed()
    server.login(USERNAME,PASSWORD)
    server.sendmail(USERNAME, to, msg.as_string())
    server.quit()

sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
        "Alarm notification",
        "Someone has entered the room, picture attached",
        ["/home/pi/webcam.jpg"] )

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

How to negate specific word in regex?

I had a list of file names, and I wanted to exclude certain ones, with this sort of behavior (Ruby):

files = [
  'mydir/states.rb',      # don't match these
  'countries.rb',
  'mydir/states_bkp.rb',  # match these
  'mydir/city_states.rb' 
]
excluded = ['states', 'countries']

# set my_rgx here

result = WankyAPI.filter(files, my_rgx)  # I didn't write WankyAPI...
assert result == ['mydir/city_states.rb', 'mydir/states_bkp.rb']

Here's my solution:

excluded_rgx = excluded.map{|e| e+'\.'}.join('|')
my_rgx = /(^|\/)((?!#{excluded_rgx})[^\.\/]*)\.rb$/

My assumptions for this application:

  • The string to be excluded is at the beginning of the input, or immediately following a slash.
  • The permitted strings end with .rb.
  • Permitted filenames don't have a . character before the .rb.

List of tables, db schema, dump etc using the Python sqlite3 API

I'm not familiar with the Python API but you can always use

SELECT * FROM sqlite_master;

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Java - Getting Data from MySQL database

This should work, I think...

ResultSet results = st.executeQuery(sql);

if(results.next()) { //there is a row
 int id = results.getInt(1); //ID if its 1st column
 String str1 = results.getString(2);
 ...
}

How to send HTML email using linux command line

Command Line

Create a file named tmp.html with the following contents:

<b>my bold message</b>

Next, paste the following into the command line (parentheses and all):

(
  echo To: [email protected]
  echo From: [email protected]
  echo "Content-Type: text/html; "
  echo Subject: a logfile
  echo
  cat tmp.html
) | sendmail -t

The mail will be dispatched including a bold message due to the <b> element.

Shell Script

As a script, save the following as email.sh:

ARG_EMAIL_TO="[email protected]"
ARG_EMAIL_FROM="Your Name <[email protected]>"
ARG_EMAIL_SUBJECT="Subject Line"

(
  echo "To: ${ARG_EMAIL_TO}"
  echo "From: ${ARG_EMAIL_FROM}"
  echo "Subject: ${ARG_EMAIL_SUBJECT}"
  echo "Mime-Version: 1.0"
  echo "Content-Type: text/html; charset='utf-8'"
  echo
  cat contents.html
) | sendmail -t

Create a file named contents.html in the same directory as the email.sh script that resembles:

<html><head><title>Subject Line</title></head>
<body>
  <p style='color:red'>HTML Content</p>
</body>
</html>

Run email.sh. When the email arrives, the HTML Content text will appear red.

Related

scp (secure copy) to ec2 instance without password

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

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

Serializing class instance to JSON

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using __dict__

Remove last character from string. Swift language

Use the function removeAtIndex(i: String.Index) -> Character:

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

Check that a input to UITextField is numeric only

Late to the game but here a handy little category I use that accounts for decimal places and the local symbol used for it. link to its gist here

@interface NSString (Extension)

- (BOOL) isAnEmail;
- (BOOL) isNumeric;

@end

@implementation NSString (Extension)

/**
 *  Determines if the current string is a valid email address.
 *
 *  @return BOOL - True if the string is a valid email address.
 */

- (BOOL) isAnEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:self];
}

/**
 *  Determines if the current NSString is numeric or not. It also accounts for the localised (Germany for example use "," instead of ".") decimal point and includes these as a valid number.
 *
 *  @return BOOL - True if the string is numeric.
 */

- (BOOL) isNumeric
{
    NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
    NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
    [decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];

    NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];

    if (r.location == NSNotFound)
    {
        // check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
        int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
        return (numberOfOccurances > 1) ? NO : YES;
    }
    else return NO;
}

@end

How to attach a file using mail command on Linux?

There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"

First, Ubuntu 14.0.4 mail from mailutils supports this:

mail -A filename -s "subject" [email protected]

Second, I found that by using the "man mail" command and searching for "attach"

WSDL/SOAP Test With soapui

I faced the same exception while trying to test my web-services deployed to WSO2 ESB.

WSO2 generated both wsdl and wsdl2. I tried to pass a wsdl2 URL and got the above exception. Quick googling showed me, that one of differences between wsdl1.1 and wsdl2.0 is replacing 'definitions' element with 'description'. Also, I found out, that SoapUI does not support wsdl2.

Therefore, for me the solution was to use wsdl1 url instead of wsdl2.

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

How to silence output in a Bash script?

If you want STDOUT and STDERR both [everything], then the simplest way is:

#!/bin/bash
myprogram >& sample.s

then run it like ./script, and you will get no output to your terminal. :)

the ">&" means STDERR and STDOUT. the & also works the same way with a pipe: ./script |& sed that will send everything to sed

Python decorators in classes

Decorators seem better suited to modify the functionality of an entire object (including function objects) versus the functionality of an object method which in general will depend on instance attributes. For example:

def mod_bar(cls):
    # returns modified class

    def decorate(fcn):
        # returns decorated function

        def new_fcn(self):
            print self.start_str
            print fcn(self)
            print self.end_str

        return new_fcn

    cls.bar = decorate(cls.bar)
    return cls

@mod_bar
class Test(object):
    def __init__(self):
        self.start_str = "starting dec"
        self.end_str = "ending dec" 

    def bar(self):
        return "bar"

The output is:

>>> import Test
>>> a = Test()
>>> a.bar()
starting dec
bar
ending dec

How to set a default row for a query that returns no rows?

This would be eliminate the select query from running twice and be better for performance:

Declare @rate int

select 
    @rate = rate 
from 
    d_payment_index
where 
    fy = 2007
    and payment_year = 2008
    and program_id = 18

IF @@rowcount = 0
    Set @rate = 0

Select @rate 'rate'

Remove 'b' character do in front of a string literal in Python 3

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding

Angular2 @Input to a property with get/set

Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts

directives are no more in Component decorator options. So I have provided sub directive to app module.

thank you @thierry-templier!

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

BEGIN - END block atomic transactions in PL/SQL

You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.

If an error occurs the transaction implicitly does a ROLLBACK.

This is the default behaviour for PL/SQL.

What is .htaccess file?

It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.

Read a file in Node.js

With Node 0.12, it's possible to do this synchronously now:

  var fs = require('fs');
  var path = require('path');

  // Buffer mydata
  var BUFFER = bufferFile('../public/mydata.png');

  function bufferFile(relPath) {
    return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
  }

fs is the file system. readFileSync() returns a Buffer, or string if you ask.

fs correctly assumes relative paths are a security issue. path is a work-around.

To load as a string, specify the encoding:

return fs.readFileSync(path,{ encoding: 'utf8' });

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

configuring project ':app' failed to find Build Tools revision

For me, dataBinding { enabled true } was enabled in gradle, removing this helped me

Why is there no tuple comprehension in Python?

We can generate tuples from a list comprehension. The following one adds two numbers sequentially into a tuple and gives a list from numbers 0-9.

>>> print k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> r= [tuple(k[i:i+2]) for i in xrange(10) if not i%2]
>>> print r
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them).

Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity.

The following code runs as expected, even in a console application:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

How to commit my current changes to a different branch in Git

You can just create a new branch and switch onto it. Commit your changes then:

git branch dirty
git checkout dirty
// And your commit follows ...

Alternatively, you can also checkout an existing branch (just git checkout <name>). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.

Is there any way to start with a POST request using Selenium?

Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.

Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.

Basically, using the driver.execute_script() you can send any javascript, including Ajax queries.

#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/

import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType

jquery = open("jquery.min.js", "r").read()
#print jquery

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"

capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)

driver = webdriver.PhantomJS(desired_capabilities=capabilities)

driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery

ajax_query = '''
            $.post( "post", {
                "a" : "%s",
                "b" : "%s"
            });
            ''' % (1,2)

ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query

result = driver.execute_script("return " + ajax_query)
#print result

#print driver.page_source

driver.close()

# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org


None
a=1&b=2  <<---- that is OK, is the data contained into the POST
None
'''

Create a git patch from the uncommitted changes in the current working directory

If you want to do binary, give a --binary option when you run git diff.

How to get HTTP Response Code using Selenium WebDriver

Not sure this is what you're looking for, but I had a bit different goal is to check if remote image exists and I will not have 403 error, so you could use something like below:

public static boolean linkExists(String URLName){
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

How to redirect the output of a PowerShell to a file during its execution

Maybe Start-Transcript would work for you. First stop it if it's already running, then start it, and stop it when done.

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\output.txt -append
# Do some stuff
Stop-Transcript

You can also have this running while working on stuff and have it saving your command line sessions for later reference.

If you want to completely suppress the error when attempting to stop a transcript that is not transcribing, you could do this:

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

T-sql - determine if value is integer

declare @i numeric(28,5) = 12.0001


if (@i/cast(@i as int) > 1)
begin
    select 'this is not int'
end
else
begin
    select 'this is int'
end

PHP Regex to check date is in YYYY-MM-DD format

You can make it this way:

if (preg_match("/\d{4}\-\d{2}-\d{2}/", $date)) {
    echo 'true';
} else {
    echo 'false';
}

but you'd better use this one:

$date = DateTime::createFromFormat('Y-m-d', $date);
if ($date) {
    echo $date -> format('Y-m-d');
}

in this case you'll get an object which is muck easier to use than just strings.

How do I pass an object from one activity to another on Android?

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    }
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);
}


public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;
        }
    }

    @Override
    public String toString() {
        return " (" + x + " " + y + ") ";
    }
}

Why does the Google Play store say my Android app is incompatible with my own device?

The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.

I changed nothing in this app except for adding more content into the res/drawable directory. When the .apk size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.

I will attempt to contact Google developer support and ask for clarification on the reason for this limit.

UPDATE: Here is Google developer support response to this:

Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.

However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.

I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.

I also removed all the <uses-feature> stuff, and now have just this:

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

Difference between "enqueue" and "dequeue"

A queue is a certain 2-sided data structure. You can add new elements on one side, and remove elements from the other side (as opposed to a stack that has only one side). Enqueue means to add an element, dequeue to remove an element. Please have a look here.

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

SQL using sp_HelpText to view a stored procedure on a linked server

It's the correct way to access linked DB:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

But make sure to mention dbo as it owns the sp_helptext.

Difference between signed / unsigned char

Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.

Use of alloc init instead of new

One Short Answere is:

  1. Both are same. But
  2. 'new' only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).

How to lay out Views in RelativeLayout programmatically?

Android 22 minimal runnable example

enter image description here

Source:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final RelativeLayout relativeLayout = new RelativeLayout(this);

        final TextView tv1;
        tv1 = new TextView(this);
        tv1.setText("tv1");
        // Setting an ID is mandatory.
        tv1.setId(View.generateViewId());
        relativeLayout.addView(tv1);

        // tv2.
        final TextView tv2;
        tv2 = new TextView(this);
        tv2.setText("tv2");
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.BELOW, tv1.getId());
        relativeLayout.addView(tv2, lp);

        // tv3.
        final TextView tv3;
        tv3 = new TextView(this);
        tv3.setText("tv3");
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        );
        lp2.addRule(RelativeLayout.BELOW, tv2.getId());
        relativeLayout.addView(tv3, lp2);

        this.setContentView(relativeLayout);
    }
}

Works with the default project generated by android create project .... GitHub repository with minimal build code.

CSS background-image - What is the correct usage?

  1. No you don’t need quotes.

  2. Yes you can. But note that relative URLs are resolved from the URL of your stylesheet.

  3. Better don’t use quotes. I think there are clients that don’t understand them.

Apply style ONLY on IE

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   #myElement {
        /* Enter your style code */
   }
}

Explanation: It is a Microsoft-specific media query. Using -ms-high-contrast property specific to Microsoft IE, it will only be parsed in Internet Explorer 10 or greater. I have used both the valid values of the media query, so it will be parsed by IE only, whether the user has high contrast enabled or not.

How to perform grep operation on all files in a directory?

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Efficiently replace all accented characters in a string?

For the lads using TypeScript and those who don't want to deal with string prototypes, here is a typescript version of Ed.'s answer:

    // Usage example:
    "Some string".replace(/[^a-zA-Z0-9-_]/g, char => ToLatinMap.get(char) || '')

    // Map:
    export let ToLatinMap: Map<string, string> = new Map<string, string>([
        ["Á", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["Â", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ä", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["À", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["A", "A"],
        ["Å", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ã", "A"],
        ["?", "AA"],
        ["Æ", "AE"],
        ["?", "AE"],
        ["?", "AE"],
        ["?", "AO"],
        ["?", "AU"],
        ["?", "AV"],
        ["?", "AV"],
        ["?", "AY"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["C", "C"],
        ["C", "C"],
        ["Ç", "C"],
        ["?", "C"],
        ["C", "C"],
        ["C", "C"],
        ["?", "C"],
        ["?", "C"],
        ["D", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["Ð", "D"],
        ["?", "D"],
        ["?", "DZ"],
        ["?", "DZ"],
        ["É", "E"],
        ["E", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ê", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ë", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["È", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "ET"],
        ["?", "F"],
        ["ƒ", "F"],
        ["?", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["?", "G"],
        ["?", "G"],
        ["G", "G"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["Í", "I"],
        ["I", "I"],
        ["I", "I"],
        ["Î", "I"],
        ["Ï", "I"],
        ["?", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "I"],
        ["Ì", "I"],
        ["?", "I"],
        ["?", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "D"],
        ["?", "F"],
        ["?", "G"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "IS"],
        ["J", "J"],
        ["?", "J"],
        ["?", "K"],
        ["K", "K"],
        ["K", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["L", "L"],
        ["?", "L"],
        ["L", "L"],
        ["L", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["L", "L"],
        ["?", "LJ"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["N", "N"],
        ["N", "N"],
        ["N", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["Ñ", "N"],
        ["?", "NJ"],
        ["Ó", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ô", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["Ö", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["Ò", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ø", "O"],
        ["?", "O"],
        ["Õ", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "OI"],
        ["?", "OO"],
        ["?", "E"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "Q"],
        ["?", "Q"],
        ["R", "R"],
        ["R", "R"],
        ["R", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "C"],
        ["?", "E"],
        ["S", "S"],
        ["?", "S"],
        ["Š", "S"],
        ["?", "S"],
        ["S", "S"],
        ["S", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["T", "T"],
        ["T", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["T", "T"],
        ["T", "T"],
        ["?", "A"],
        ["?", "L"],
        ["?", "M"],
        ["?", "V"],
        ["?", "TZ"],
        ["Ú", "U"],
        ["U", "U"],
        ["U", "U"],
        ["Û", "U"],
        ["?", "U"],
        ["Ü", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["Ù", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "VY"],
        ["?", "W"],
        ["W", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "X"],
        ["?", "X"],
        ["Ý", "Y"],
        ["Y", "Y"],
        ["Ÿ", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["Z", "Z"],
        ["Ž", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["Z", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "IJ"],
        ["Œ", "OE"],
        ["?", "A"],
        ["?", "AE"],
        ["?", "B"],
        ["?", "B"],
        ["?", "C"],
        ["?", "D"],
        ["?", "E"],
        ["?", "F"],
        ["?", "G"],
        ["?", "G"],
        ["?", "H"],
        ["?", "I"],
        ["?", "R"],
        ["?", "J"],
        ["?", "K"],
        ["?", "L"],
        ["?", "L"],
        ["?", "M"],
        ["?", "N"],
        ["?", "O"],
        ["?", "OE"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "R"],
        ["?", "N"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "E"],
        ["?", "R"],
        ["?", "U"],
        ["?", "V"],
        ["?", "W"],
        ["?", "Y"],
        ["?", "Z"],
        ["á", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["â", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ä", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["à", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["å", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ã", "a"],
        ["?", "aa"],
        ["æ", "ae"],
        ["?", "ae"],
        ["?", "ae"],
        ["?", "ao"],
        ["?", "au"],
        ["?", "av"],
        ["?", "av"],
        ["?", "ay"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["b", "b"],
        ["?", "b"],
        ["?", "o"],
        ["c", "c"],
        ["c", "c"],
        ["ç", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["?", "c"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["i", "i"],
        ["?", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "dz"],
        ["?", "dz"],
        ["é", "e"],
        ["e", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ê", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ë", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["è", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "et"],
        ["?", "f"],
        ["ƒ", "f"],
        ["?", "f"],
        ["?", "f"],
        ["?", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["?", "g"],
        ["?", "g"],
        ["?", "g"],
        ["g", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "hv"],
        ["í", "i"],
        ["i", "i"],
        ["i", "i"],
        ["î", "i"],
        ["ï", "i"],
        ["?", "i"],
        ["?", "i"],
        ["?", "i"],
        ["ì", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "d"],
        ["?", "f"],
        ["?", "g"],
        ["?", "r"],
        ["?", "s"],
        ["?", "t"],
        ["?", "is"],
        ["j", "j"],
        ["j", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "k"],
        ["k", "k"],
        ["k", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["l", "l"],
        ["?", "lj"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["n", "n"],
        ["n", "n"],
        ["n", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["ñ", "n"],
        ["?", "nj"],
        ["ó", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ô", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["ö", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["ò", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ø", "o"],
        ["?", "o"],
        ["õ", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "oi"],
        ["?", "oo"],
        ["?", "e"],
        ["?", "e"],
        ["?", "o"],
        ["?", "o"],
        ["?", "ou"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["r", "r"],
        ["r", "r"],
        ["r", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "c"],
        ["?", "c"],
        ["?", "e"],
        ["?", "r"],
        ["s", "s"],
        ["?", "s"],
        ["š", "s"],
        ["?", "s"],
        ["s", "s"],
        ["s", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["g", "g"],
        ["?", "o"],
        ["?", "o"],
        ["?", "u"],
        ["t", "t"],
        ["t", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "th"],
        ["?", "a"],
        ["?", "ae"],
        ["?", "e"],
        ["?", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "i"],
        ["?", "k"],
        ["?", "l"],
        ["?", "m"],
        ["?", "m"],
        ["?", "oe"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "t"],
        ["?", "v"],
        ["?", "w"],
        ["?", "y"],
        ["?", "tz"],
        ["ú", "u"],
        ["u", "u"],
        ["u", "u"],
        ["û", "u"],
        ["?", "u"],
        ["ü", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["ù", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "ue"],
        ["?", "um"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "vy"],
        ["?", "w"],
        ["w", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "x"],
        ["?", "x"],
        ["?", "x"],
        ["ý", "y"],
        ["y", "y"],
        ["ÿ", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["z", "z"],
        ["ž", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "ff"],
        ["?", "ffi"],
        ["?", "ffl"],
        ["?", "fi"],
        ["?", "fl"],
        ["?", "ij"],
        ["œ", "oe"],
        ["?", "st"],
        ["?", "a"],
        ["?", "e"],
        ["?", "i"],
        ["?", "j"],
        ["?", "o"],
        ["?", "r"],
        ["?", "u"],
        ["?", "v"],
        ["?", "x"],
    ]);

Transferring files over SSH

If copying to/from your desktop machine, use WinSCP, or if on Linux, Nautilus supports SCP via the Connect To Server option.

scp can only copy files to a machine running sshd, hence you need to run the client software on the remote machine from the one you are running scp on.

If copying on the command line, use:

# copy from local machine to remote machine
scp localfile user@host:/path/to/whereyouwant/thefile

or

# copy from remote machine to local machine
scp user@host:/path/to/remotefile localfile

Unmount the directory which is mounted by sshfs in Mac

The following worked for me:

hdiutil detach <path to sshfs mount>

Example:

hdiutil detach /Users/user1/sshfs

One can also locate the volume created by sshfs in Finder, right-click, and select Eject. Which is, to the best of my knowledge, the GUI version of the above command.

How to stop the task scheduled in java.util.Timer class

Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.

Escaping double quotes in JavaScript onClick event handler

It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

Set TextView text from html-formatted string resource in XML

I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server.

Here is what I get from a server:

<p>The quick brown&nbsp;<br />
fox jumps&nbsp;<br />
 over the lazy dog<br />
</p>

It seems to be more complicated but the solution is much simpler.

private TextView textView;

protected void onCreate(Bundle savedInstanceState) { 
.....
textView = (TextView) findViewById(R.id.text); //need to define in your layout
String htmlFromServer = getHTMLContentFromAServer(); 
textView.setText(Html.fromHtml(htmlFromServer).toString());

}

Hope it helps!
Linh

CSS no text wrap

Additionally to overflow:hidden, use

white-space:nowrap;

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

How to write a Python module/package?

I created a project to easily initiate a project skeleton from scratch. https://github.com/MacHu-GWU/pygitrepo-project.

And you can create a test project, let's say, learn_creating_py_package.

You can learn what component you should have for different purpose like:

  • create virtualenv
  • install itself
  • run unittest
  • run code coverage
  • build document
  • deploy document
  • run unittest in different python version
  • deploy to PYPI

The advantage of using pygitrepo is that those tedious are automatically created itself and adapt your package_name, project_name, github_account, document host service, windows or macos or linux.

It is a good place to learn develop a python project like a pro.

Hope this could help.

Thank you.

How do I unload (reload) a Python module?

if 'myModule' in sys.modules:  
    del sys.modules["myModule"]

Change text color with Javascript?

innerHTML is a string representing the contents of the element.

You want to modify the element itself. Drop the .innerHTML part.

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Setting Custom ActionBar Title from Fragment

A simple Kotlin example

Assuming these gradle deps match or are higher version in your project:

kotlin_version = '1.3.41'
nav_version_ktx = '2.0.0'

Adapt this to your fragment classes:

    /**
     * A simple [Fragment] subclass.
     *
     * Updates the action bar title when onResume() is called on the fragment,
     * which is called every time you navigate to the fragment
     *
     */

    class MyFragment : Fragment() {
    private lateinit var mainActivity: MainActivity

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

       //[...]

        mainActivity = this.activity as MainActivity

       //[...]
    }

    override fun onResume() {
        super.onResume()
        mainActivity.supportActionBar?.title = "My Fragment!"
    }


    }

Playing a video in VideoView in Android

Add android.permission.READ_EXTERNAL_STORAGE in manifest, worked for me

Remove end of line characters from Java string

You can use unescapeJava from org.apache.commons.text.StringEscapeUtils like below

str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);

Timestamp to human readable format

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

For example, using it for the current time:

_x000D_
_x000D_
document.write( new Date().toUTCString() );
_x000D_
_x000D_
_x000D_

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Loop through files in a folder using VBA?

Dir seems to be very fast.

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
   file = Dir("c:\testfolder\")
   While (file <> "")
      If InStr(file, "test") > 0 Then
         MsgBox "found " & file
         Exit Sub
      End If
     file = Dir
  Wend
End Sub

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

How to dynamically allocate memory space for a string and get that string from user?

This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c != '\n')
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory\n");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] = '\0';
    return str;
}

In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

if you create an MVC Web project You should select Authentication when creating the project . by defaults is not selected. enter image description here

Characters allowed in GET parameter

The question asks which characters are allowed in GET parameters without encoding or escaping them.

According to RFC3986 (general URL syntax) and RFC7230, section 2.7.1 (HTTP/S URL syntax) the only characters you need to percent-encode are those outside of the query set, see the definition below.

However, there are additional specifications like HTML5, Web forms, and the obsolete Indexed search, W3C recommendation. Those documents add a special meaning to some characters notably, to symbols like = & + ;.

Other answers here suggest that most of the reserved characters should be encoded, including "/" "?". That's not correct. In fact, RFC3986, section 3.4 advises against percent-encoding "/" "?" characters.

it is sometimes better for usability to avoid percent- encoding those characters.

RFC3986 defines query component as:

query       = *( pchar / "/" / "?" )
pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~" 

A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component.

The conclusion is that XYZ part should encode:

special: # % = & ;
Space
sub-delims
out of query set: [ ]
non ASCII encodable characters

Unless special symbols = & ; are key=value separators.

Encoding other characters is allowed but not necessary.

Convert from enum ordinal to enum type

You could use a static lookup table:

public enum Suit {
  spades, hearts, diamonds, clubs;

  private static final Map<Integer, Suit> lookup = new HashMap<Integer, Suit>();

  static{
    int ordinal = 0;
    for (Suit suit : EnumSet.allOf(Suit.class)) {
      lookup.put(ordinal, suit);
      ordinal+= 1;
    }
  }

  public Suit fromOrdinal(int ordinal) {
    return lookup.get(ordinal);
  }
}

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

How to add to an NSDictionary

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];

Flask at first run: Do not use the development server in a production environment

The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

Or you can use waitress.serve() in the code instead of using the CLI command.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

How to count the number of files in a directory using Python

Luke's code reformat.

import os

print len(os.walk('/usr/lib').next()[2])

How to access ssis package variables inside script component

I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

So to access the variable, I type

string fp = Variables.FilePath;

In the PreExecute() method of the Script Component.

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

How to concat a string to xsl:value-of select="...?

The easiest way to concat a static text string to a selected value is to use element.

<a>
  <xsl:attribute name="href"> 
    <xsl:value-of select="/*/properties/property[@name='report']/@value" />
    <xsl:text>staticIconExample.png</xsl:text>
  </xsl:attribute>
</a>

Delete a row from a table by id

And what about trying not to delete but hide that row?

Why does jQuery or a DOM method such as getElementById not find the element?

As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).

However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.

Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.

Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).

Given a filesystem path, is there a shorter way to extract the filename without its extension?

You can use Path API as follow:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

More info: Path.GetFileNameWithoutExtension

Multiple inputs with same name through POST in php

Change the names of your inputs:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

Then:

$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

show dbs gives "Not Authorized to execute command" error

You should have started the mongod instance with access control, i.e., the --auth command line option, such as:

$ mongod --auth

Let's start the mongo shell, and create an administrator in the admin database:

$ mongo
> use admin
> db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

Now if you run command "db.stats()", or "show users", you will get error "not authorized on admin to execute command..."

> db.stats()
{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { dbstats: 1.0, scale: undefined }",
        "code" : 13,
        "codeName" : "Unauthorized"
}

The reason is that you still have not granted role "read" or "readWrite" to user myUserAdmin. You can do it as below:

> db.auth("myUserAdmin", "abc123")
> db.grantRolesToUser("myUserAdmin", [ { role: "read", db: "admin" } ])

Now You can verify it (Command "show users" now works):

> show users
{
        "_id" : "admin.myUserAdmin",
        "user" : "myUserAdmin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "read",
                        "db" : "admin"
                },
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}

Now if you run "db.stats()", you'll also be OK:

> db.stats()
{
        "db" : "admin",
        "collections" : 2,
        "views" : 0,
        "objects" : 3,
        "avgObjSize" : 151,
        "dataSize" : 453,
        "storageSize" : 65536,
        "numExtents" : 0,
        "indexes" : 3,
        "indexSize" : 81920,
        "ok" : 1
}

This user and role mechanism can be applied to any other databases in MongoDB as well, in addition to the admin database.

(MongoDB version 3.4.3)

How to check if curl is enabled or disabled

Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -

function isExtensionLoaded($extension_name){
    return extension_loaded($extension_name);
}

Usage

echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');

Reading a huge .csv file

I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.

I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Best C/C++ Network Library

Aggregated List of Libraries

MySQL 'Order By' - sorting alphanumeric correctly

People use different tricks to do this. I Googled and find out some results each follow different tricks. Have a look at them:

Edit:

I have just added the code of each link for future visitors.

Alpha Numeric Sorting in MySQL

Given input

1A 1a 10A 9B 21C 1C 1D

Expected output

1A 1C 1D 1a 9B 10A 21C

Query

Bin Way
===================================
SELECT 
tbl_column, 
BIN(tbl_column) AS binray_not_needed_column
FROM db_table
ORDER BY binray_not_needed_column ASC , tbl_column ASC

-----------------------

Cast Way
===================================
SELECT 
tbl_column, 
CAST(tbl_column as SIGNED) AS casted_column
FROM db_table
ORDER BY casted_column ASC , tbl_column ASC

Natural Sorting in MySQL

Given input

Table: sorting_test
 -------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
 -------------------------- -------------
| test1                    | 1           |
| test12                   | 2           |
| test13                   | 3           |
| test2                    | 4           |
| test3                    | 5           |
 -------------------------- -------------

Expected Output

 -------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
 -------------------------- -------------
| test1                    | 1           |
| test2                    | 4           |
| test3                    | 5           |
| test12                   | 2           |
| test13                   | 3           |
 -------------------------- -------------

Query

SELECT alphanumeric, integer
       FROM sorting_test
       ORDER BY LENGTH(alphanumeric), alphanumeric  

Sorting of numeric values mixed with alphanumeric values

Given input

2a, 12, 5b, 5a, 10, 11, 1, 4b

Expected Output

1, 2a, 4b, 5a, 5b, 10, 11, 12

Query

SELECT version
FROM version_sorting
ORDER BY CAST(version AS UNSIGNED), version;

Hope this helps

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

Comma separated results in SQL

For Sql Server 2017 and later you can use the new STRING_AGG function

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.

SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv 
FROM Person.Person;

Here is the result set.

John,N/A,Mike,Peter,N/A,N/A,Alice,Bob

Perhaps a more common use case is to group together and then aggregate, just like you would with SUM, COUNT or AVG.

SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags 
FROM dbo.Article AS a       
LEFT JOIN dbo.ArticleTag AS t 
    ON a.ArticleId = t.ArticleId 
GROUP BY a.articleId, title;

How to get subarray from array?

The question is actually asking for a New array, so I believe a better solution would be to combine Abdennour TOUMI's answer with a clone function:

_x000D_
_x000D_
function clone(obj) {_x000D_
  if (null == obj || "object" != typeof obj) return obj;_x000D_
  const copy = obj.constructor();_x000D_
  for (const attr in obj) {_x000D_
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];_x000D_
  }_x000D_
  return copy;_x000D_
}_x000D_
_x000D_
// With the `clone()` function, you can now do the following:_x000D_
_x000D_
Array.prototype.subarray = function(start, end) {_x000D_
  if (!end) {_x000D_
    end = this.length;_x000D_
  } _x000D_
  const newArray = clone(this);_x000D_
  return newArray.slice(start, end);_x000D_
};_x000D_
_x000D_
// Without a copy you will lose your original array._x000D_
_x000D_
// **Example:**_x000D_
_x000D_
const array = [1, 2, 3, 4, 5];_x000D_
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]_x000D_
_x000D_
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
_x000D_
_x000D_
_x000D_

[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Passing arguments to "make run"

I don't know a way to do what you want exactly, but a workaround might be:

run: ./prog
    ./prog $(ARGS)

Then:

make ARGS="asdf" run
# or
make run ARGS="asdf"

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,

ggplot(data_country)+
  geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")

Image style height and width not taken in outlook mails

This worked for me:

src="{0}"  width=30 height=30 style="border:0;"

Nothing else has worked so far.

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

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

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

Check OS version in Swift?

let Device = UIDevice.currentDevice()
let iosVersion = NSString(string: Device.systemVersion).doubleValue

let iOS8 = iosVersion >= 8
let iOS7 = iosVersion >= 7 && iosVersion < 8

and check as

if(iOS8)
{

}
else 
{
}  

parseInt with jQuery

Two issues:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseInt will call toString on it and get back "[object Object]". You need to use val or text or something (depending on what the element is) to get the string you want.

  2. You're not telling parseInt what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt guesses which radix to use.

Fix if the element is a form field:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

Create component to specific module with Angular-CLI

I ran into this issue today while scaffolding an Angular 9 application. I got the "module does not exist error" whenever I added the .module.ts or .module to the module name. The cli only needs the name of the module with no extension. Assuming I had a module name: brands.module.ts, the command I used was

ng g c path/to/my/components/brands-component -m brands --dry-run

remove the --dry-run once you've confirmed the file structure is correct.

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
    _x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
_x000D_
_x000D_

As others have suggested, you could also use slice(1);

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
  _x000D_
alert(myarray.slice(1));
_x000D_
_x000D_
_x000D_

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I just deal with it like this. Go to the properties of your reference and do this:

Set "Copy local = false"
Save
Set "Copy local = true"
Save

and that's it.

Visual Studio 2010 doesn't initially put: <private>True</private> in the reference tag and setting "copy local" to false causes it to create the tag. Afterwards it will set it to true and false accordingly.

Dynamically add script tag with src that may include document.write

Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.

Inserting Dynamic Javascript the right way

Merge DLL into EXE?

2019 Update (just for reference):

Starting with .NET Core 3.0, this feature is supported out of the box. To take advantage of the single-file executable publishing, just add the following line to the project configuration file:

<PropertyGroup>
  <PublishSingleFile>true</PublishSingleFile>
</PropertyGroup>

Now, dotnet publish should produce a single .exe file without using any external tool.

More documentation for this feature is available at https://github.com/dotnet/designs/blob/master/accepted/single-file/design.md.

How to get a microtime in Node.js?

there are npm packages that bind to the system gettimeofday() function, which returns a microsecond precision timestamp on Linux. Search for npm gettimeofday. Calling C is faster than process.hrtime()

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Support for "border-radius" in IE

A workaround and a handy tool:

CSS3Pie uses .htc files and the behavior property to implement CSS3 into IE 6 - 8.

Modernizr is a bit of javascript that will put classes on your html element, allowing you to serve different style definitions to different browsers based on their capabilities.

Obviously, these both add more overhead, but with IE9 due to only run on Vista/7 we might be stuck for quite awhile. As of August 2010 Windows XP still accounts for 48% of web client OSes.

How to select the first element of a set with JSTL?

Since i have have just one element in my Set the order is not important So I can access to the first element like this :

${ attachments.iterator().next().id }

How do I get the first n characters of a string without checking the size or going out of bounds?

Use the substring method, as follows:

int n = 8;
String s = "Hello, World!";
System.out.println(s.substring(0,n);

If n is greater than the length of the string, this will throw an exception, as one commenter has pointed out. one simple solution is to wrap all this in the condition if(s.length()<n) in your else clause, you can choose whether you just want to print/return the whole String or handle it another way.

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

set STATICBUILD=true && pip install lxml

run this command instead, must have VS C++ compiler installed first

https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/

It works for me with Python 3.5.2 and Windows 7

How to compile LEX/YACC files on Windows?

Go for the full installation of Git for windows (with Unix tool), and bison and flex would come with it in the bin folder.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Just iterate and add:

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

Edit to add:

If you can make changes to a, you can also do:

a.putAll(b)

and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

Set the default value in dropdownlist using jQuery

One line of jQuery does it all!

$("#myCombobox option[text='it\'s me']").attr("selected","selected"); 

Case-insensitive string comparison in C++

Just a note on whatever method you finally choose, if that method happens to include the use of strcmp that some answers suggest:

strcmp doesn't work with Unicode data in general. In general, it doesn't even work with byte-based Unicode encodings, such as utf-8, since strcmp only makes byte-per-byte comparisons and Unicode code points encoded in utf-8 can take more than 1 byte. The only specific Unicode case strcmp properly handle is when a string encoded with a byte-based encoding contains only code points below U+00FF - then the byte-per-byte comparison is enough.

Function not defined javascript

important: in this kind of error you should look for simple mistakes in most cases

besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

set column width of a gridview in asp.net

I know this is an old Question, but it popped up when I was looking for a solution to the same issue, so I thought that I would post what worked for me.

<asp:BoundField DataField="Description" HeaderText="Bond Event" ItemStyle-Width="300px" />

I used the ItemStyle-Width attribute on my BoundField and it worked very nicely I haven't had any issues yet.

I didn't need to add anything else to the rest of the code to make this work either.

Raw SQL Query without DbSet - Entity Framework Core

Building on the other answers I've written this helper that accomplishes the task, including example usage:

public static class Helper
{
    public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map)
    {
        using (var context = new DbContext())
        {
            using (var command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;

                context.Database.OpenConnection();

                using (var result = command.ExecuteReader())
                {
                    var entities = new List<T>();

                    while (result.Read())
                    {
                        entities.Add(map(result));
                    }

                    return entities;
                }
            }
        }
    }

Usage:

public class TopUser
{
    public string Name { get; set; }

    public int Count { get; set; }
}

var result = Helper.RawSqlQuery(
    "SELECT TOP 10 Name, COUNT(*) FROM Users U"
    + " INNER JOIN Signups S ON U.UserId = S.UserId"
    + " GROUP BY U.Name ORDER BY COUNT(*) DESC",
    x => new TopUser { Name = (string)x[0], Count = (int)x[1] });

result.ForEach(x => Console.WriteLine($"{x.Name,-25}{x.Count}"));

I plan to get rid of it as soon as built-in support is added. According to a statement by Arthur Vickers from the EF Core team it is a high priority for post 2.0. The issue is being tracked here.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Created a directive (ng-repeat with lazy loading) 

which loads data when it reaches to bottom of the page and remove half of the previously loaded data and when it reaches to top of the div again previous data(depending upon on page number) will be loaded removing half of the current data So on DOM at a time only limited data is present which may leads to better performance instead of rendering whole data on load.

HTML CODE:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="ListController">
  <div class="row customScroll" id="customTable" datafilter pagenumber="pageNumber" data="rowData" searchdata="searchdata" itemsPerPage="{{itemsPerPage}}"  totaldata="totalData"   selectedrow="onRowSelected(row,row.index)"  style="height:300px;overflow-y: auto;padding-top: 5px">

    <!--<div class="col-md-12 col-xs-12 col-sm-12 assign-list" ng-repeat="row in CRGC.rowData track by $index | orderBy:sortField:sortReverse | filter:searchFish">-->
    <div class="col-md-12 col-xs-12 col-sm-12 pdl0 assign-list" style="padding:10px" ng-repeat="row in rowData" ng-hide="row[CRGC.columns[0].id]=='' && row[CRGC.columns[1].id]==''">
        <!--col1-->

        <div ng-click ="onRowSelected(row,row.index)"> <span>{{row["sno"]}}</span> <span>{{row["id"]}}</span> <span>{{row["name"]}}</span></div>
      <!--   <div class="border_opacity"></div> -->
    </div>

</div>

  </body>

</html>

Angular CODE:

var app = angular.module('plunker', []);
var x;
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];

function ListController($scope, $timeout, $q, $templateCache) {
  $scope.itemsPerPage = 40;
  $scope.lastPage = 0;
  $scope.maxPage = 100;
  $scope.data = [];
  $scope.pageNumber = 0;


  $scope.makeid = function() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }


  $scope.DataFormFunction = function() {
      var arrayObj = [];
      for (var i = 0; i < $scope.itemsPerPage*$scope.maxPage; i++) {
          arrayObj.push({
              sno: i + 1,
              id: Math.random() * 100,
              name: $scope.makeid()
          });
      }
      $scope.totalData = arrayObj;
      $scope.totalData = $scope.totalData.filter(function(a,i){ a.index = i; return true; })
      $scope.rowData = $scope.totalData.slice(0, $scope.itemsperpage);
    }
  $scope.DataFormFunction();

  $scope.onRowSelected = function(row,index){
    console.log(row,index);
  }

}

angular.module('plunker').controller('ListController', ListController).directive('datafilter', function($compile) {
  return {
    restrict: 'EAC',
    scope: {
      data: '=',
      totalData: '=totaldata',
      pageNumber: '=pagenumber',
      searchdata: '=',
      defaultinput: '=',
      selectedrow: '&',
      filterflag: '=',
      totalFilterData: '='
    },
    link: function(scope, elem, attr) {
      //scope.pageNumber = 0;
      var tempData = angular.copy(scope.totalData);
      scope.totalPageLength = Math.ceil(scope.totalData.length / +attr.itemsperpage);
      console.log(scope.totalData);
      scope.data = scope.totalData.slice(0, attr.itemsperpage);
      elem.on('scroll', function(event) {
        event.preventDefault();
      //  var scrollHeight = angular.element('#customTable').scrollTop();
      var scrollHeight = document.getElementById("customTable").scrollTop
        /*if(scope.filterflag && scope.pageNumber != 0){
        scope.data = scope.totalFilterData;
        scope.pageNumber = 0;
        angular.element('#customTable').scrollTop(0);
        }*/
        if (scrollHeight < 100) {
          if (!scope.filterflag) {
            scope.scrollUp();
          }
        }
        if (angular.element(this).scrollTop() + angular.element(this).innerHeight() >= angular.element(this)[0].scrollHeight) {
          console.log("scroll bottom reached");
          if (!scope.filterflag) {
            scope.scrollDown();
          }
        }
        scope.$apply(scope.data);

      });

      /*
       * Scroll down data append function
       */
      scope.scrollDown = function() {
          if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
            scope.totalDataCompare = scope.totalData;
          } else {
            scope.totalDataCompare = scope.totalFilterData;
          }
          scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
          if (scope.pageNumber < scope.totalPageLength - 1) {
            scope.pageNumber++;
            scope.lastaddedData = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage, (+attr.itemsperpage) + (+scope.pageNumber * attr.itemsperpage));
            scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
            scope.data = scope.data.concat(scope.lastaddedData);
            scope.$apply(scope.data);
            if (scope.pageNumber < scope.totalPageLength) {
              var divHeight = $('.assign-list').outerHeight();
              if (!scope.moveToPositionFlag) {
                angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
              } else {
                scope.moveToPositionFlag = false;
              }
            }


          }
        }
        /*
         * Scroll up data append function
         */
      scope.scrollUp = function() {
          if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
            scope.totalDataCompare = scope.totalData;
          } else {
            scope.totalDataCompare = scope.totalFilterData;
          }
          scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
          if (scope.pageNumber > 0) {
            this.positionData = scope.data[0];
            scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
            var position = +attr.itemsperpage * scope.pageNumber - 1.5 * (+attr.itemsperpage);
            if (position < 0) {
              position = 0;
            }
            scope.TopAddData = scope.totalDataCompare.slice(position, (+attr.itemsperpage) + position);
            scope.pageNumber--;
            var divHeight = $('.assign-list').outerHeight();
            if (position != 0) {
              scope.data = scope.TopAddData.concat(scope.data);
              scope.$apply(scope.data);
              angular.element('#customTable').scrollTop(divHeight * 1 * (+attr.itemsperpage));
            } else {
              scope.data = scope.TopAddData;
              scope.$apply(scope.data);
              angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
            }
          }
        }
    }
  };
});

Demo with directive

Another Solution: If you using UI-grid in the project then  same implementation is there in UI grid with infinite-scroll.

Depending upon height of the division it loads the data and upon scroll new data will be append and previous data will be removed.

HTML Code:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://cdn.rawgit.com/angular-ui/bower-ui-grid/master/ui-grid.min.css" type="text/css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="ListController">
     <div class="input-group" style="margin-bottom: 15px">
      <div class="input-group-btn">
        <button class='btn btn-primary' ng-click="resetList()">RESET</button>
      </div>
      <input class="form-control" ng-model="search" ng-change="abc()">
    </div>

    <div data-ui-grid="gridOptions" class="grid" ui-grid-selection  data-ui-grid-infinite-scroll style="height :400px"></div>

    <button ng-click="getProductList()">Submit</button>
  </body>

</html>

Angular Code:

var app = angular.module('plunker', ['ui.grid', 'ui.grid.infiniteScroll', 'ui.grid.selection']);
var x;
angular.module('plunker').controller('ListController', ListController);
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];

function ListController($scope, $timeout, $q, $templateCache) {
    $scope.itemsPerPage = 200;
    $scope.lastPage = 0;
    $scope.maxPage = 5;
    $scope.data = [];

    var request = {
        "startAt": "1",
        "noOfRecords": $scope.itemsPerPage
    };
    $templateCache.put('ui-grid/selectionRowHeaderButtons',
        "<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"row.isSelected\" ng-click=\"row.isSelected=!row.isSelected;selectButtonClick(row, $event)\">&nbsp;</div>"
    );


    $templateCache.put('ui-grid/selectionSelectAllButtons',
        "<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-if=\"grid.options.enableSelectAll\"><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"grid.selection.selectAll\" ng-click=\"grid.selection.selectAll=!grid.selection.selectAll;headerButtonClick($event)\"></div>"
    );

    $scope.gridOptions = {
        infiniteScrollDown: true,
        enableSorting: false,
        enableRowSelection: true,
        enableSelectAll: true,
        //enableFullRowSelection: true,
        columnDefs: [{
            field: 'sno',
            name: 'sno'
        }, {
            field: 'id',
            name: 'ID'
        }, {
            field: 'name',
            name: 'My Name'
        }],
        data: 'data',
        onRegisterApi: function(gridApi) {
            gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.loadMoreData);
            $scope.gridApi = gridApi;
        }
    };
    $scope.gridOptions.multiSelect = true;
    $scope.makeid = function() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for (var i = 0; i < 5; i++)
            text += possible.charAt(Math.floor(Math.random() * possible.length));

        return text;
    }
    $scope.abc = function() {
        var a = $scope.search;
        x = $scope.searchData;
        $scope.data = x.filter(function(arr, y) {
            return arr.name.indexOf(a) > -1
        })
        console.log($scope.data);
        if ($scope.gridApi.grid.selection.selectAll)
            $timeout(function() {
                $scope.gridApi.selection.selectAllRows();
            }, 100);
    }


    $scope.loadMoreData = function() {
        var promise = $q.defer();
        if ($scope.lastPage < $scope.maxPage) {
            $timeout(function() {
                var arrayObj = [];
                for (var i = 0; i < $scope.itemsPerPage; i++) {
                    arrayObj.push({
                        sno: i + 1,
                        id: Math.random() * 100,
                        name: $scope.makeid()
                    });
                }

                if (!$scope.search) {
                    $scope.lastPage++;
                    $scope.data = $scope.data.concat(arrayObj);
                    $scope.gridApi.infiniteScroll.dataLoaded();
                    console.log($scope.data);
                    $scope.searchData = $scope.data;
                    // $scope.data = $scope.searchData;
                    promise.resolve();
                    if ($scope.gridApi.grid.selection.selectAll)
                        $timeout(function() {
                            $scope.gridApi.selection.selectAllRows();
                        }, 100);
                }


            }, Math.random() * 1000);
        } else {
            $scope.gridApi.infiniteScroll.dataLoaded();
            promise.resolve();
        }
        return promise.promise;
    };

    $scope.loadMoreData();

    $scope.getProductList = function() {

        if ($scope.gridApi.selection.getSelectedRows().length > 0) {
            $scope.gridOptions.data = $scope.resultSimulatedData;
            $scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows(); //<--Property undefined error here
            console.log($scope.mySelectedRows);
            //alert('Selected Row: ' + $scope.mySelectedRows[0].id + ', ' + $scope.mySelectedRows[0].name + '.');
        } else {
            alert('Select a row first');
        }
    }
    $scope.getSelectedRows = function() {
        $scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
    }
    $scope.headerButtonClick = function() {

        $scope.selectAll = $scope.grid.selection.selectAll;

    }
}

Demo with UI grid with infinite-scroll Demo

Jquery: Find Text and replace

Change by id or class for each tag

$("#id <tag>:contains('Text want to replaced')").html("Text Want to replaced with");


$(".className <tag>:contains('Text want to replaced')").html("Text Want to replaced with");

MySQL root password change

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

You can find Resetting the Root Password in the MySQL documentation.

Basic text editor in command prompt?

notepad filename.extension will open notepad editor

Number of occurrences of a character in a string

Because LINQ can do everything...:

string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();

Or if you like, you can use the Count overload that takes a predicate :

var count = test.Count(x => x == '&');

Android findViewById() in Custom View

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ImageHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ImageHolder();
        editText = (EditText) row.findViewById(R.id.id_number_custom);
        loadButton = (ImageButton) row.findViewById(R.id.load_data_button);
        row.setTag(holder);
    } else {
        holder = (ImageHolder) row.getTag();
    }


    holder.editText.setText("Your Value");
    holder.loadButton.setImageBitmap("Your Bitmap Value");
    return row;
}

Check if character is number?

isNumber = function(obj, strict) {
    var strict = strict === true ? true : false;
    if (strict) {
        return !isNaN(obj) && obj instanceof Number ? true : false;
    } else {
        return !isNaN(obj - parseFloat(obj));
    }
}

output without strict mode:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);

true
true
false
false

output with strict mode:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);

true
false
false
false

Auto increment primary key in SQL Server Management Studio 2012

Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .

Examle: before restart ID=11 after restart , you insert new row in the table, then the id will be 1012.

Mod in Java produces negative numbers

If the modulus is a power of 2 then you can use a bitmask:

int i = -1 & ~-2; // -1 MOD 2 is 1

By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y is x - (x DIV y) * y where x DIV y is TRUNC(x / y)) and MOD requires a positive denominator and returns a positive result.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

How to convert float to varchar in SQL Server

Try this one, should work:

cast((convert(bigint,b.tax_id)) as varchar(20))

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How can you tell if a value is not numeric in Oracle?

There is no built-in function. You could write one

CREATE FUNCTION is_numeric( p_str IN VARCHAR2 )
  RETURN NUMBER
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN 1;
EXCEPTION
  WHEN value_error
  THEN
    RETURN 0;
END;

and/or

CREATE FUNCTION my_to_number( p_str IN VARCHAR2 )
  RETURN NUMBER
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN l_num;
EXCEPTION
  WHEN value_error
  THEN
    RETURN NULL;
END;

You can then do

IF( is_numeric( str ) = 1 AND 
    my_to_number( str ) >= 1000 AND
    my_to_number( str ) <= 7000 )

If you happen to be using Oracle 12.2 or later, there are enhancements to the to_number function that you could leverage

IF( to_number( str default null on conversion error ) >= 1000 AND
    to_number( str default null on conversion error ) <= 7000 )

One line ftp server in python

Why don't you instead use a one-line HTTP server?

python -m SimpleHTTPServer 8000

will serve the contents of the current working directory over HTTP on port 8000.

If you use Python 3, you should instead write

python3 -m http.server 8000

See the SimpleHTTPServer module docs for 2.x and the http.server docs for 3.x.

By the way, in both cases the port parameter is optional.

Convert nested Python dict to object?

This little class never gives me any problem, just extend it and use the copy() method:

  import simplejson as json

  class BlindCopy(object):

    def copy(self, json_str):
        dic = json.loads(json_str)
        for k, v in dic.iteritems():
            if hasattr(self, k):
                setattr(self, k, v);

Can a java file have more than one class?

In a .java file,there can be only one public top-level class whose name is the same as the file, but there might be several public inner classes which can be exported to everyone and access the outer class's fields/methods,for example:AlertDialog.Builder(modified by 'public static') in AlertDialog(modified by 'public')

Random date in C#

I have taken @Joel Coehoorn answer and made the changes he adviced - put the variable out of the method and put all in class. Plus now the time is random too. Here is the result.

class RandomDateTime
{
    DateTime start;
    Random gen;
    int range;

    public RandomDateTime()
    {
        start = new DateTime(1995, 1, 1);
        gen = new Random();
        range = (DateTime.Today - start).Days;
    }

    public DateTime Next()
    {
        return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));
    }
}

And example how to use to write 100 random DateTimes to console:

RandomDateTime date = new RandomDateTime();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(date.Next());
}

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

How do I convert an array object to a string in PowerShell?

From a pipe

# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}

# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}

Write-Host

# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'

# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'

Example

Should we pass a shared_ptr by reference or by value?

Pass by const reference, it's faster. If you need to store it, say in some container, the ref. count will be auto-magically incremented by the copy operation.

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

Avoid browser popup blockers

My use case: In my react app, Upon user click there is an API call performed to the backend. Based on the response, new tab is opened with the api response added as params to the new tab URL (in same domain).

The only caveat in my use case is that it takes more for 1 second for the API response to be received. Hence pop-up blocker shows up (if it is active) when opening up URL in a new tab.

To circumvent the above described issue, here is the sample code,

var new_tab=window.open()
axios.get('http://backend-api').then(response=>{
    const url="http://someurl"+"?response"
    new_tab.location.href=url;
}).catch(error=>{
    //catch error
})

Summary: Create an empty tab (as above line 1) and when the API call is completed, you can fill up the tab with the url and skip the popup blocker.

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

Retrieve Button value with jQuery

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

Service vs IntentService in the Android platform

The Major Difference between a Service and an IntentService is described as follows:

Service :

1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.

2.Allows Multiple requests at a time.(Multi Threading)

IntentService :

1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.

2.But it allows only one request at a time.

Scroll to a div using jquery

you can try :

$("#MediaPlayer").ready(function(){
    $("html, body").delay(2000).animate({
        scrollTop: $('#MediaPlayer').offset().top 
    }, 2000);
});

How do you count the elements of an array in java

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

Android Studio not showing modules in project structure

Make sure the directory name is lower case.

How to find the foreach index?

I normally do this when working with associative arrays:

foreach ($assoc_array as $key => $value) {
 //do something
}

This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:

foreach ($array as $indx => $value) {
  //do something
}

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

I know it's mighty late to post this but here's a tiny hack to achieve your outcome ;)

Simply add a dummy view below your viewpager:

<android.support.v4.view.ViewPager
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

<RelativeLayout
     android:id="@+id/dummyView"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</RelativeLayout>

Then add a OnClickListener to your RelativeLayout.

dummyView = (RelativeLayout) findViewById(R.id.dummyView);

dummyView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         //Just leave this empty
    }
});

Get a bit creative with layouts, their placements and their behaviour and you'll learn to find a way to do absolutely anything that you imagine :)

Good luck!