Programs & Examples On #In operator

How to make GREP select only numeric values?

Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk

PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"

df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'

in your case, use:

df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'

output: 81

If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back

df . |awk '$NF=="/" {print $(NF-1)}'

output: 81%

Skip certain tables with mysqldump

I like Rubo77's solution, I hadn't seen it before I modified Paul's. This one will backup a single database, excluding any tables you don't want. It will then gzip it, and delete any files over 8 days old. I will probably use 2 versions of this that do a full (minus logs table) once a day, and another that just backs up the most important tables that change the most every hour using a couple cron jobs.

#!/bin/sh
PASSWORD=XXXX
HOST=127.0.0.1
USER=root
DATABASE=MyFavoriteDB

now="$(date +'%d_%m_%Y_%H_%M')"
filename="${DATABASE}_db_backup_$now"
backupfolder="/opt/backups/mysql"
DB_FILE="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt

EXCLUDED_TABLES=(
logs
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE}  > ${DB_FILE} 
echo "Dump structure finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
gzip ${DB_FILE}

find "$backupfolder" -name ${DATABASE}_db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

What are the differences between git remote prune, git prune, git fetch --prune, etc

I don't blame you for getting frustrated about this. The best way to look at is this. There are potentially three versions of every remote branch:

  1. The actual branch on the remote repository
    (e.g., remote repo at https://example.com/repo.git, refs/heads/master)
  2. Your snapshot of that branch locally (stored under refs/remotes/...)
    (e.g., local repo, refs/remotes/origin/master)
  3. And a local branch that might be tracking the remote branch
    (e.g., local repo, refs/heads/master)

Let's start with git prune. This removes objects that are no longer being referenced, it does not remove references. In your case, you have a local branch. That means there's a ref named random_branch_I_want_deleted that refers to some objects that represent the history of that branch. So, by definition, git prune will not remove random_branch_I_want_deleted. Really, git prune is a way to delete data that has accumulated in Git but is not being referenced by anything. In general, it doesn't affect your view of any branches.

git remote prune origin and git fetch --prune both operate on references under refs/remotes/... (I'll refer to these as remote references). It doesn't affect local branches. The git remote version is useful if you only want to remove remote references under a particular remote. Otherwise, the two do exactly the same thing. So, in short, git remote prune and git fetch --prune operate on number 2 above. For example, if you deleted a branch using the git web GUI and don't want it to show up in your local branch list anymore (git branch -r), then this is the command you should use.

To remove a local branch, you should use git branch -d (or -D if it's not merged anywhere). FWIW, there is no git command to automatically remove the local tracking branches if a remote branch disappears.

Using Mockito with multiple calls to the same method with the same arguments

You can even chain doReturn() method invocations like this

doReturn(null).doReturn(anotherInstance).when(mock).method();

cute isn't it :)

Difference between Java SE/EE/ME?

If I were you I would install the Java SE SDK. Once it is installed make sure you have the JAVA_HOME environment variable set and add the %JAVA_HOME%\bin dir to your path.

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part

What does it mean if a Python object is "subscriptable" or not?

As a corollary to the earlier answers here, very often this is a sign that you think you have a list (or dict, or other subscriptable object) when you do not.

For example, let's say you have a function which should return a list;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

Now when you call that function, and something_happens() for some reason does not return a True value, what happens? The if fails, and so you fall through; gimme_things doesn't explicitly return anything -- so then in fact, it will implicitly return None. Then this code:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

will fail with "NoneType object is not subscriptable" because, well, things is None and so you are trying to do None[0] which doesn't make sense because ... what the error message says.

There are two ways to fix this bug in your code -- the first is to avoid the error by checking that things is in fact valid before attempting to use it;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

or equivalently trap the TypeError exception;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

Another is to redesign gimme_things so that you make sure it always returns a list. In this case, that's probably the simpler design because it means if there are many places where you have a similar bug, they can be kept simple and idiomatic.

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

Of course, what you put in the else: branch depends on your use case. Perhaps you should raise an exception when something_happens() fails, to make it more obvious and explicit where something actually went wrong? Adding exceptions to your own code is an important way to let yourself know exactly what's up when something fails!

(Notice also how this latter fix still doesn't completely fix the bug -- it prevents you from attempting to subscript None but things[0] is still an IndexError when things is an empty list. If you have a try you can do except (TypeError, IndexError) to trap it, too.)

What's better at freeing memory with PHP: unset() or $var = null

I still doubt about this, but I've tried it at my script and I'm using xdebug to know how it will affect my app memory usage. The script is set on my function like this :

function gen_table_data($serv, $coorp, $type, $showSql = FALSE, $table = 'ireg_idnts') {
    $sql = "SELECT COUNT(`operator`) `operator` FROM $table WHERE $serv = '$coorp'";
    if($showSql === FALSE) {
        $sql = mysql_query($sql) or die(mysql_error());
        $data = mysql_fetch_array($sql);
        return $data[0];
    } else echo $sql;
}

And I add unset just before the return code and it give me : 160200 then I try to change it with $sql = NULL and it give me : 160224 :)

But there is something unique on this comparative when I am not using unset() or NULL, xdebug give me 160144 as memory usage

So, I think giving line to use unset() or NULL will add process to your application and it will be better to stay origin with your code and decrease the variable that you are using as effective as you can .

Correct me if I'm wrong, thanks

imagecreatefromjpeg and similar functions are not working in PHP

After installing php5-gd apache restart is needed.

Regular expression to find URLs within a string

I liked Stefan Henze 's solution but it would pick up 34.56. Its too general and I have unparsed html. There are 4 anchors for a url;

www ,

http:\ (and co) ,

. followed by letters and then / ,

or letters . and one of these: https://ftp.isc.org/www/survey/reports/current/bynum.txt .

I used lots of info from this thread. Thank you all.

"(((((http|ftp|https|gopher|telnet|file|localhost):\\/\\/)|(www\\.)|(xn--)){1}([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)|(([\\w_-]{2,200}(?:(?:\\.[\\w_-]+)*))((\\.[\\w_-]+\\/([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)|(\\.((org|com|net|edu|gov|mil|int|arpa|biz|info|unknown|one|ninja|network|host|coop|tech)|(jp|br|it|cn|mx|ar|nl|pl|ru|tr|tw|za|be|uk|eg|es|fi|pt|th|nz|cz|hu|gr|dk|il|sg|uy|lt|ua|ie|ir|ve|kz|ec|rs|sk|py|bg|hk|eu|ee|md|is|my|lv|gt|pk|ni|by|ae|kr|su|vn|cy|am|ke))))))(?!(((ttp|tp|ttps):\\/\\/)|(ww\\.)|(n--)))"

Above solves just about everything except a string like "eurls:www.google.com,facebook.com,http://test.com/", which it returns as a single string. Tbh idk why I added gopher etc. Proof R code

if(T){
  wierdurl<-vector()
  wierdurl[1]<-"https://JP??.?.jp/dir1/?? "
  wierdurl[2]<-"xn--jp-cd2fp15c.xn--fsq.jp "
  wierdurl[3]<-"http://52.221.161.242/2018/11/23/biofourmis-collab"
  wierdurl[4]<-"https://12000.org/ "
  wierdurl[5]<-"  https://vg-1.com/?page_id=1002 "
  wierdurl[6]<-"https://3dnews.ru/822878"
  wierdurl[7]<-"The link of this question: https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
  Also there are some urls: www.google.com, facebook.com, http://test.com/method?param=wasd
  The code below catches all urls in text and returns urls in list. "
  wierdurl[8]<-"Thelinkofthisquestion:https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
  Alsotherearesomeurls:www.google.com,facebook.com,http://test.com/method?param=wasd
  Thecodebelowcatchesallurlsintextandreturnsurlsinlist. "
  wierdurl[9]<-"Thelinkofthisquestion:https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-stringAlsotherearesomeurlsZwww.google.com,facebook.com,http://test.com/method?param=wasdThecodebelowcatchesallurlsintextandreturnsurlsinlist."
  wierdurl[10]<-"1facebook.com/1res"
  wierdurl[11]<-"1facebook.com/1res/wat.txt"
  wierdurl[12]<-"www.e "
  wierdurl[13]<-"is this the file.txt i need"
  wierdurl[14]<-"xn--jp-cd2fp15c.xn--fsq.jpinspiredby "
  wierdurl[15]<-"[xn--jp-cd2fp15c.xn--fsq.jp/inspiredby "
  wierdurl[16]<-"xnto--jpto-cd2fp15c.xnto--fsq.jpinspiredby "
  wierdurl[17]<-"fsety--fwdvg-gertu56.ffuoiw--ffwsx.3dinspiredby "
  wierdurl[18]<-"://3dnews.ru/822878 "
  wierdurl[19]<-" http://mywebsite.com/msn.co.uk "
  wierdurl[20]<-" 2.0http://www.abe.hip "
  wierdurl[21]<-"www.abe.hip"
  wierdurl[22]<-"hardware/software/data"
  regexstring<-vector()
  regexstring[2]<-"(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?"
  regexstring[3]<-"/(?:(?:https?|ftp|file):\\/\\/|www\\.|ftp\\.)(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[-A-Z0-9+&@#\\/%=~_|$?!:,.])*(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[A-Z0-9+&@#\\/%=~_|$])/igm"
  regexstring[4]<-"[a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]?"
  regexstring[5]<-"((http|ftp|https)\\:\\/\\/)?([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?"
  regexstring[6]<-"((http|ftp|https):\\/\\/)?([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?"
  regexstring[7]<-"(http|ftp|https)(:\\/\\/)([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?"
  regexstring[8]<-"(?:(?:https?|ftp|file):\\/\\/|www\\.|ftp\\.)(?:\\([-A-Z0-9+&@#/%=~_|$?!:,.]*\\)|[-A-Z0-9+&@#/%=~_|$?!:,.])*(?:\\([-A-Z0-9+&@#/%=~_|$?!:,.]*\\)|[A-Z0-9+&@#/%=~_|$])"
  regexstring[10]<-"((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?"
  regexstring[12]<-"http[s:/]+[[:alnum:]./]+"
  regexstring[9]<-"http[s:/]+[[:alnum:]./]+" #in DLpages 230
  regexstring[1]<-"[[:alnum:]-]+?[.][:alnum:]+?(?=[/ :])" #in link_graphs 50
  regexstring[13]<-"^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$"
  regexstring[14]<-"(((((http|ftp|https):\\/\\/)|(www\\.)|(xn--)){1}([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)|(([\\w_-]+(?:(?:\\.[\\w_-]+)*))((\\.((org|com|net|edu|gov|mil|int)|(([:alpha:]{2})(?=[, ]))))|([\\/]([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?))))(?!(((ttp|tp|ttps):\\/\\/)|(ww\\.)|(n--)))"
  regexstring[15]<-"(((((http|ftp|https|gopher|telnet|file|localhost):\\/\\/)|(www\\.)|(xn--)){1}([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)|(([\\w_-]{2,200}(?:(?:\\.[\\w_-]+)*))((\\.[\\w_-]+\\/([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)|(\\.((org|com|net|edu|gov|mil|int|arpa|biz|info|unknown|one|ninja|network|host|coop|tech)|(jp|br|it|cn|mx|ar|nl|pl|ru|tr|tw|za|be|uk|eg|es|fi|pt|th|nz|cz|hu|gr|dk|il|sg|uy|lt|ua|ie|ir|ve|kz|ec|rs|sk|py|bg|hk|eu|ee|md|is|my|lv|gt|pk|ni|by|ae|kr|su|vn|cy|am|ke))))))(?!(((ttp|tp|ttps):\\/\\/)|(ww\\.)|(n--)))"
    }

for(i in wierdurl){#c(7,22)
  for(c in regexstring[c(15)]) {
    print(paste(i,which(regexstring==c)))
    print(str_extract_all(i,c))
  }
}

How do I pass a class as a parameter in Java?

This kind of thing is not easy. Here is a method that calls a static method:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

Kotlin Android start new Activity

To start a new Activity ,

startActivity(Intent(this@CurrentClassName,RequiredClassName::class.java)

So change your code to :

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun buTestUpdateText2 (view: View) {
        startActivity(Intent(this@MainActivity,ClassName::class.java))

        // Also like this 

        val intent = Intent(this@MainActivity,ClassName::class.java)
        startActivity(intent)
    }

How to convert CSV to JSON in Node.js

I started with node-csvtojson, but it brought too many dependencies for my linking.

Building on your question and the answer by brnd, I used node-csv and underscore.js.

var attribs;
var json:
csv()
    .from.string(csvString)
    .transform(function(row) {
        if (!attribs) {
            attribs = row;
            return null;
        }
        return row;
     })
    .to.array(function(rows) {
        json = _.map(rows, function(row) {
            return _.object(attribs, row);
        });
     });

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

How to set editable true/false EditText in Android programmatically?

An easy and safe method:

editText.clearFocus();
editText.setFocusable(false);

How do I fix "The expression of type List needs unchecked conversion...'?

Since getEntries returns a raw List, it could hold anything.

The warning-free approach is to create a new List<SyndEntry>, then cast each element of the sf.getEntries() result to SyndEntry before adding it to your new list. Collections.checkedList does not do this checking for you—although it would have been possible to implement it to do so.

By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a ClassCastException is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Is it possible to get the current spark context settings in PySpark?

Unfortunately, no, the Spark platform as of version 2.3.1 does not provide any way to programmatically access the value of every property at run time. It provides several methods to access the values of properties that were explicitly set through a configuration file (like spark-defaults.conf), set through the SparkConf object when you created the session, or set through the command line when you submitted the job, but none of these methods will show the default value for a property that was not explicitly set. For completeness, the best options are:

  • The Spark application’s web UI, usually at http://<driver>:4040, has an “Environment” tab with a property value table.
  • The SparkContext keeps a hidden reference to its configuration in PySpark, and the configuration provides a getAll method: spark.sparkContext._conf.getAll().
  • Spark SQL provides the SET command that will return a table of property values: spark.sql("SET").toPandas(). You can also use SET -v to include a column with the property’s description.

(These three methods all return the same data on my cluster.)

What is phtml, and when should I use a .phtml extension rather than .php?

.phtml was the standard file extension for PHP 2 programs. .php3 took over for PHP 3. When PHP 4 came out they switched to a straight .php.

The older file extensions are still sometimes used, but aren't so common.

How to print a string at a fixed width?

I find using str.format much more elegant:

>>> '{0: <5}'.format('s')
's    '
>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

If you want to align the string to the right use > instead of <:

>>> '{0: >5}'.format('ss')
'   ss'

Edit 1: As mentioned in the comments: the 0 in '{0: <5}' indicates the argument’s index passed to str.format().


Edit 2: In python3 one could use also f-strings:

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

or:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

of note, in some places above, ' ' (single quotation marks) were added to emphasize the width of the printed strings.

How are POST and GET variables handled in Python?

They are stored in the CGI fieldstorage object.

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")

How to print a list in Python "nicely"

from pprint import pprint
pprint(the_list)

how to fire event on file select

This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses jquery:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});

How to add extension methods to Enums

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions 
{
  public static DateTime From(this Duration duration, DateTime dateTime) 
  {
    switch (duration) 
    {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration");
    }
  }
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

how to bind datatable to datagridview in c#

Try this:

    ServersTable.Columns.Clear();
    ServersTable.DataSource = SBind;

If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:

for (int i = 0; i < ServersTable.ColumnCount; ++i) {
  DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
  ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

Search for value in DataGridView in a column

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

Laravel Controller Subfolder routing

1.create your subfolder just like followings:

app
----controllers
--------admin
--------home

2.configure your code in app/routes.php

<?php
// index
Route::get('/', 'Home\HomeController@index');

// admin/test
Route::group(
    array('prefix' => 'admin'), 
    function() {
        Route::get('test', 'Admin\IndexController@index');
    }
);
?>

3.write sth in app/controllers/admin/IndexController.php, eg:

<?php
namespace Admin;

class IndexController extends \BaseController {

    public function index()
    {
        return "admin.home";
    }
}
?>

4.access your site,eg:localhost/admin/test you'll see "admin.home" on the page

ps: Please ignore my poor English

What is the best way to conditionally apply attributes in AngularJS?

For input field validation you can do:

<input ng-model="discount" type="number" ng-attr-max="{{discountType == '%' ? 100 : undefined}}">

This will apply the attribute max to 100 only if discountType is defined as %

Installing jQuery?

There are two ways to load jQuery in your application:

1) Add jQuery from your own site.

For this, you need to add jQuery reference in <Head> section of your page with correct src path:

<script src="script/jquery.js" type="text/javascript"></script>

But this create an additional load to your server for download a file to client

2) ther other way to load jQuery from any other server like Google, Microsoft or jQuery itself.

As stated here:

it provides several advantages.

  1. You always use the latest jQuery framework.
  2. It reduces the load from your server.
  3. It saves bandwidth. jQuery framework will load faster from these CDN.
  4. The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN.

Here is the link by which you can load jQuery from Microsoft. Follow this url, it may be helpful.

http://www.asp.net/ajaxlibrary/cdn.ashx

How to convert a String to Bytearray

In C# running this

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes("Hello");

Will create an array with

72,0,101,0,108,0,108,0,111,0

byte array

For a character which the code is greater than 255 it will look like this

byte array

If you want a very similar behavior in JavaScript you can do this (v2 is a bit more robust solution, while the original version will only work for 0x00 ~ 0xff)

_x000D_
_x000D_
var str = "Hello?";_x000D_
var bytes = []; // char codes_x000D_
var bytesv2 = []; // char codes_x000D_
_x000D_
for (var i = 0; i < str.length; ++i) {_x000D_
  var code = str.charCodeAt(i);_x000D_
  _x000D_
  bytes = bytes.concat([code]);_x000D_
  _x000D_
  bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);_x000D_
}_x000D_
_x000D_
// 72, 101, 108, 108, 111, 31452_x000D_
console.log('bytes', bytes.join(', '));_x000D_
_x000D_
// 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 220, 122_x000D_
console.log('bytesv2', bytesv2.join(', '));
_x000D_
_x000D_
_x000D_

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

Android Device Chooser -- device not showing up

After following some of the steps in other answers here, as well as what is found here: ADB Driver for HTC Incredible, I had to issue two commands before my phone would show up.

adb kill-server
adb start-server

Finally, after those two commands would my device show up when I ran

adb devices

From time to time, the ADB process may get stuck (technical term there). When that happens, the above commands will not work. I have found that killing the ADB process (look in for adb.exe in the Processes tab in Task Manager on Windows, or kill the PID for adb under linux), and then use

adb start-server

generally fixes that problem.

Execute function after Ajax call is complete

try

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({  

 url: 'api.php',                        
 data: 'id1='+q+'',                                                         
 dataType: 'json',
 success: function(data)          
  {

    id = data[0];              
   vname = data[1];
   printWithAjax();
}
      });



}//end of the for statement
  }//end of ajax call function

Form Submit jQuery does not work

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form.

If you plan to call .submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.


Several other things:

As mentioned, you need to submit the form using a simpler event than the jQuery one

BUT you also need to cancel the clicks on the links

Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.

<form action="deletprofil.php" id="form_id" method="post">
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });

    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});    

Judging from your comments, I think you really want to do this:

<form action="deletprofil.php" id="form_id" method="post">
  <input type="hidden" id="whichdelete" name="whichdelete" value="" />
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          // trigger the submit event, not the event handler
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });
    $(".delete").on("click", function(e) {
        $("#whichdelete").val(this.value);
    });
    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});  

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

Open internet explorer as administrator.

Open the reports url http://machinename/reportservername

then in 'folder settings' give permission to required user-groups.

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

A quick solution to get me going was to uncheck the "Sign the ClickOnce manifests" in: Project -> (project name)Properties -> Signing Tab

ANTLR: Is there a simple example?

version 4.7.1 was slightly different : for import:

import org.antlr.v4.runtime.*;

for the main segment - note the CharStreams:

CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1
Host: www.example.com

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

Sort array of objects by string property value

Given the original example:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

Sort by multiple fields:

objs.sort(function(left, right) {
    var last_nom_order = left.last_nom.localeCompare(right.last_nom);
    var first_nom_order = left.first_nom.localeCompare(right.first_nom);
    return last_nom_order || first_nom_order;
});

Notes

  • a.localeCompare(b) is universally supported and returns -1,0,1 if a<b,a==b,a>b respectively.
  • || in the last line gives last_nom priority over first_nom.
  • Subtraction works on numeric fields: var age_order = left.age - right.age;
  • Negate to reverse order, return -last_nom_order || -first_nom_order || -age_order;

How do I convert a number to a letter in Java?

if you define a/A as 0

char res;
if (i>25 || i<0){
    res = null;
}
    res = (i) + 65
}
return res;

65 for captitals; 97 for non captitals

MySQL error 2006: mysql server has gone away

Just in case this helps anyone:

I got this error when I opened and closed connections in a function which would be called from several parts of the application. We got too many connections so we thought it might be a good idea to reuse the existing connection or throw it away and make a new one like so:

  public static function getConnection($database, $host, $user, $password)
 {
 if (!self::$instance) {
  return self::newConnection($database, $host, $user, $password);
 } elseif ($database . $host . $user != self::$connectionDetails) {

self::$instance->query('KILL CONNECTION_ID()'); self::$instance = null; return self::newConnection($database, $host, $user, $password); } return self::$instance; } Well turns out we've been a little too thorough with the killing and so the processes doing important things on the old connection could never finish their business. So we dropped these lines

  self::$instance->query('KILL CONNECTION_ID()');
  self::$instance = null;

and as the hardware and setup of the machine allows it we increased the number of allowed connections on the server by adding

max_connections = 500

to our configuration file. This fixed our problem for now and we learned something about killing mysql connections.

Why do I get access denied to data folder when using adb?

$ adb shell

$ cd /data

$ ls

opendir failed, Permission denied


You should do this:

$ adb shell

$ cd /data

shell@android:/data $ run-as com.your.package 

shell@android:/data/data/com.your.package $ ls

OK!

Exiting out of a FOR loop in a batch file?

Did a little research on this, it appears that you are looping from 1 to 2147483647, in increments of 1.

(1, 1, 2147483647): The firs number is the starting number, the next number is the step, and the last number is the end number.

Edited To Add

It appears that the loop runs to completion regardless of any test conditions. I tested

FOR /L %%F IN (1, 1, 5) DO SET %%F=6

And it ran very quickly.

Second Edit

Since this is the only line in the batch file, you might try the EXIT command:

FOR /L %%F IN (1, 1, 2147483647) DO @IF NOT EXIST %%F EXIT

However, this will also close the DOS prompt window.

How to "add existing frameworks" in Xcode 4?

In Project

  1. Select the project navigator
  2. Click on Build Phases
  3. Click on link binary with libraries
  4. Click on + Button and add your Frameworks

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Java replace all square brackets in a string

String str, str1;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String : ");
str = sc.nextLine();


str1 = str.replaceAll("[aeiouAEIOU]", "");



System.out.print(str1);

How can I get city name from a latitude and longitude point?

There are many tools available

  1. google maps API as like all had written
  2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

other free and paid tools are available also

MySQL - ignore insert error: duplicate entry

$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
    while($value=mysql_fetch_array($duplicate_query)
    {
        if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
        {
            echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
            $res=mysql_query($query);
            if($query)
            {
                echo "Success";
            }
            else
            {
                echo "Error";
            }
            else
            {
                echo "Duplicate Entry";
            }
        }
    }
}
else
{
    echo "Records Already Exixts";
}

validate a dropdownlist in asp.net mvc

For ListBox / DropDown in MVC5 - i've found this to work for me sofar:

in Model:

[Required(ErrorMessage = "- Select item -")]
 public List<string> SelectedItem { get; set; }
 public List<SelectListItem> AvailableItemsList { get; set; }

in View:

@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

Submit a form using jQuery

this will send a form with preloader :

var a=$('#yourform').serialize();
$.ajax({
    type:'post',
    url:'receiver url',
    data:a,
    beforeSend:function(){
        launchpreloader();
    },
    complete:function(){
        stopPreloader();
    },
    success:function(result){
         alert(result);
    }
});

i'have some trick to make a form data post reformed with random method http://www.jackart4.com/article.html

Python class inherits object

Yes, it's historical. Without it, it creates an old-style class.

If you use type() on an old-style object, you just get "instance". On a new-style object you get its class.

Why doesn't TFS get latest get the latest?

WHen I run into this problem with it not getting latest and version mismatches I first do a "Get Specific Version" set it to changeset and put in 1. This will then remove all the files from your local workspace (for that project, folder, file, etc) and it will also have TFS update so that it knows you now have NO VERSION DOWNLOADED. You can then do a "Get Latest" and viola, you will actually have the latest

Download an SVN repository?

One the upper left in Google Code it has a link "Checkout"

Click that and you will get a command line suggestion:

Command-line access

Use this command to anonymously check out the latest project source code:

 Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://yourfolder.googlecode.com/svn/trunk/ yourfolder-read-only

If you want a subfolder only then add it after trunk

If you are on linux & have SVN installed just CD to the folder where you want it installed first then run the above command - it will download fast

I tried all the other suggestions & this is the only thing that worked, couldnt do it with bazaar or svnDownloader app.

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

Base64 String throwing invalid character error

string stringToDecrypt = HttpContext.Current.Request.QueryString.ToString()

//change to string stringToDecrypt = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString())

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

'str' object does not support item assignment in Python

In Python, strings are immutable, so you can't change their characters in-place.

You can, however, do the following:

for i in str:
    srr += i

The reasons this works is that it's a shortcut for:

for i in str:
    srr = srr + i

The above creates a new string with each iteration, and stores the reference to that new string in srr.

About .bash_profile, .bashrc, and where should alias be written in?

From the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc or .bash_profile, and then have the other file source the first one.

How to set the opacity/alpha of a UIImage?

Hey hey thanks from Xamarin user! :) Here it goes translated to c#

//***************************************************************************
public static class ImageExtensions
//***************************************************************************
{
    //-------------------------------------------------------------
    public static UIImage WithAlpha(this UIImage image, float alpha)  
    //-------------------------------------------------------------
        {
        UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale);
        image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha);
        var newImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return newImage;
        }

}

Usage example:

var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

Get GMT Time in Java

To get the time in millis at GMT all you need is

long millis = System.currentTimeMillis();

You can also do

long millis = new Date().getTime();

and

long millis = 
    Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis();

but these are inefficient ways of making the same call.

Cocoa: What's the difference between the frame and the bounds?

Frame its relative to its SuperView whereas Bounds relative to its NSView.

Example:X=40,Y=60.Also contains 3 Views.This Diagram shows you clear idea.

FRAME

BOUNDS

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

SQL Server Text type vs. varchar data type

There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx

Bytes per

  1. varchar(max), varbinary(max), xml, text, or image column 2^31-1 2^31-1
  2. nvarchar(max) column 2^30-1 2^30-1

Create line after text with css

There's no need for extra wrappers or span elements anymore. Flexbox and Grid can handle this easily.

_x000D_
_x000D_
h2 {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h2::after {_x000D_
  content: '';_x000D_
  flex: 1;_x000D_
  margin-left: 1rem;_x000D_
  height: 1px;_x000D_
  background-color: #000;_x000D_
}
_x000D_
<h2>Heading</h2>
_x000D_
_x000D_
_x000D_

How do I import a sql data file into SQL Server?

  1. Start SQL Server Management Studio
  2. Connect to your database
  3. File > Open > File and pick your file
  4. Execute it

Losing Session State

You could add some logging to the Global.asax in Session_Start and Application_Start to track what's going on with the user's Session and the Application as a whole.

Also, watch out of you're running in Web Farm mode (multiple IIS threads defined in the application pool) or load balancing because the user can end up hitting a different server that does not have the same memory. If this is the case, you can switch the Session mode to SQL Server.

php variable in html no other way than: <?php echo $var; ?>

I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.

Personally I don't mind mixing HTML and PHP like so

<a href="<?php echo $link;?>">link description</a>

As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.

echo '<a href="'.$link.'">link description</a>';

The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.

How to check if mysql database exists

CREATE SCHEMA IF NOT EXISTS `demodb` DEFAULT CHARACTER SET utf8 ;

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

Spring Boot access static resources missing scr/main/resources

Just use Spring type ClassPathResource.

File file = new ClassPathResource("countries.xml").getFile();

As long as this file is somewhere on classpath Spring will find it. This can be src/main/resources during development and testing. In production, it can be current running directory.

EDIT: This approach doesn't work if file is in fat JAR. In such case you need to use:

InputStream is = new ClassPathResource("countries.xml").getInputStream();

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

How to hide form code from view code/inspect element browser?

There is a smart way to disable inspect element in your website. Just add the following snippet inside script tag :

$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});

Please check out this blog

The function key F12 which directly take inspect element from browser, we can also disable it, by using the following code:

$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

Make UINavigationBar transparent

In iOS5 you can do this to make the navigation bar transparent:

nav.navigationBar.translucent = YES; // Setting this slides the view up, underneath the nav bar (otherwise it'll appear black)
const float colorMask[6] = {222, 255, 222, 255, 222, 255};
UIImage *img = [[UIImage alloc] init];
UIImage *maskedImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)];

[nav.navigationBar setBackgroundImage:maskedImage forBarMetrics:UIBarMetricsDefault]; 
[img release];

HTML code for INR

Here is one more example based on Intl.NumberFormat native api.

_x000D_
_x000D_
var number = 123456.789;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
  style: 'currency',_x000D_
  currency: 'INR',_x000D_
  // limit to six significant digits (Possible values are from 1 to 21)._x000D_
  maximumSignificantDigits: 6_x000D_
}).format(number));
_x000D_
_x000D_
_x000D_

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

MySQL OPTIMIZE all tables?

The MySQL Administrator (part of the MySQL GUI Tools) can do that for you on a database level.

Just select your schema and press the Maintenance button in the bottom right corner.

Since the GUI Tools have reached End-of-life status they are hard to find on the mysql page. Found them via Google: http://dev.mysql.com/downloads/gui-tools/5.0.html

I don't know if the new MySQL Workbench can do that, too.

And you can use the mysqlcheck command line tool which should be able to do that, too.

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

There are a few ways to do it, for example:

  • Check window.orientation value
  • Compare innerHeight vs. innerWidth

You can adapt one of the methods below.


Check if device is in portrait mode

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}

Check if device is in landscape mode

function isLandscape() {
    return (window.orientation === 90 || window.orientation === -90);
}

Example usage

if (isPortrait()) {
    alert("This page is best viewed in landscape mode");
}

How do I detect the orientation change?

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});

Kubernetes pod gets recreated when deleted

The root cause for the question asked was the deployment/job/replicasets spec attribute strategy->type which defines what should happen when the pod will be destroyed (either implicitly or explicitly). In my case, it was Recreate.

As per @nomad's answer, deleting the deployment/job/replicasets is the simple fix to avoid experimenting with deadly combos before messing up the cluster as a novice user.

Try the following commands to understand the behind the scene actions before jumping into debugging :

kubectl get all -A -o name
kubectl get events -A | grep <pod-name>

How to determine equality for two JavaScript objects?

This is a simple Javascript function to compare two objects having simple key-value pairs. The function will return an array of strings, where each string is a path to an inequality between the two objects.

function compare(a,b) {
    var paths = [];
    [...new Set(Object.keys(a).concat(Object.keys(b)))].forEach(key=>{
        if(typeof a[key] === 'object' && typeof b[key] === 'object') {
            var results = compare(a[key], b[key]);
            if(JSON.stringify(results)!=='[]') {
                paths.push(...results.map(result=>key.concat("=>"+result)));
            }
        }
        else if (a[key]!==b[key]) {
            paths.push(key);
        }
    })
    return paths;
}

If you only want to compare two objects without knowing the paths to inequalities, you can do it as follows:

if(JSON.stringify(compare(object1, object2))==='[]') {
   // the two objects are equal
} else {
   // the two objects are not equal
}

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

My trial version of DevExpress had expired. Try renewing it again.

Performing a Stress Test on Web Application?

You asked this question almost a year ago and I don't know if you still are looking for another way of benchmarking your website. However since this question is still not marked as solved I would like to suggest the free webservice LoadImpact (btw. not affiliated). Just got this link via twitter and would like to share this find. They create a reasonable good overview and for a few bucks more you get the "full impact mode". This probably sounds strange, but good luck pushing and braking your service :)

Check for special characters in string

Your regexp use ^ and $ so it tries to match the entire string. And if you want only a boolean as the result, use test instead of match.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

if(format.test(string)){
  return true;
} else {
  return false;
}

Git command to checkout any branch and overwrite local changes

The new git-switch command (starting in GIT 2.23) also has a flag --discard-changes which should help you. git pull might be necessary afterwards.

Warning: it's still considered to be experimental.

How to return a string from a C++ function?

Assign something to your strings. This will definitely help.

int to hex string

Use ToString("X4").

The 4 means that the string will be 4 digits long.

Reference: The Hexadecimal ("X") Format Specifier on MSDN.

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

How to clone ArrayList and also clone its contents?

A nasty way is to do it with reflection. Something like this worked for me.

public static <T extends Cloneable> List<T> deepCloneList(List<T> original) {
    if (original == null || original.size() < 1) {
        return new ArrayList<>();
    }

    try {
        int originalSize = original.size();
        Method cloneMethod = original.get(0).getClass().getDeclaredMethod("clone");
        List<T> clonedList = new ArrayList<>();

        // noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < originalSize; i++) {
            // noinspection unchecked
            clonedList.add((T) cloneMethod.invoke(original.get(i)));
        }
        return clonedList;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        System.err.println("Couldn't clone list due to " + e.getMessage());
        return new ArrayList<>();
    }
}

Converting a date string to a DateTime object using Joda Time library

An simple method :

public static DateTime transfStringToDateTime(String dateParam, Session session) throws NotesException {
    DateTime dateRetour;
    dateRetour = session.createDateTime(dateParam);                 

    return dateRetour;
}

How to make a owl carousel with arrows instead of next previous

A note for others who may be using Owl Carousel v 1.3.2:

You can replace the navigation text in the settings where you're enabling the navigation.

navigation:true,
navigationText: [
   "<i class='fa fa-chevron-left'></i>",
   "<i class='fa fa-chevron-right'></i>"
]

Freeze the top row for an html table only (Fixed Table Header Scrolling)

The Chromatable jquery plugin allows a fixed header (or top row) with widths that allow percentages--granted, only a percentage of 100%.

http://www.chromaloop.com/posts/chromatable-jquery-plugin

I can't think of how you could do this without javascript.

update: new link -> http://www.jquery-plugins.info/chromatable-00012248.htm

Export HTML table to pdf using jspdf

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data);
doc.save("table.pdf");

How do I redirect a user when a button is clicked?

It depends on what you mean by button. If it is a link:

<%= Html.ActionLink("some text", "actionName", "controllerName") %>

For posting you could use a form:

<% using(Html.BeginForm("actionName", "controllerName")) { %>
    <input type="submit" value="Some text" />
<% } %>

And finally if you have a button:

<input type="button" value="Some text" onclick="window.location.href='<%= Url.Action("actionName", "controllerName") %>';" />

How to ignore the first line of data when processing CSV data?

I would convert csvreader to list, then pop the first element

import csv        

with open(fileName, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        data = list(csvreader)               # Convert to list
        data.pop(0)                          # Removes the first row

        for row in data:
            print(row)

Making HTML page zoom by default

Solved it as follows,

in CSS

#my{
zoom: 100%;
}

Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.

Though this is not the best way to do it, there is another effective solution

Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.

Uncaught TypeError: Cannot read property 'appendChild' of null

Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script> but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.

  1. Use
window.onload = () => {
    //write your code here
}
  1. Add the <script src="script.js"></script> to the bottom of the html file so that it loads last.

What MIME type should I use for CSV?

For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)

_x000D_
_x000D_
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"

There is also another list

_x000D_
_x000D_
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/mime-types

But the first one was more helpful for my use case..

Happy coding ;)

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

I want to calculate the distance between two points in Java

Based on the @trashgod's comment, this is the simpliest way to calculate distance:

double distance = Math.hypot(x1-x2, y1-y2);

From documentation of Math.hypot:

Returns: sqrt(x²+ y²) without intermediate overflow or underflow.

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

Flushing footer to bottom of the page, twitter bootstrap

to handle width constraint layouts use the following so that you do not get rounded corners, and so that your nav bar will be flush to the sides of the application

<div class="navbar navbar-fixed-bottom">
    <div class="navbar-inner">
        <div class="width-constraint clearfix">
            <p class="pull-left muted credit">YourApp v1.0.0</p>

            <p class="pull-right muted credit">©2013 • CONFIDENTIAL ALL RIGHTS RESERVED</p>
        </div>
    </div>
</div>

then you can use css to override the bootstrap classes to adjust height, font, and color

    .navbar-fixed-bottom {
      font-size: 12px;
      line-height: 18px;
    }
    .navbar-fixed-bottom .navbar-inner {
        min-height: 22px;
    }
    .navbar-fixed-bottom .p {
        margin: 2px 0 2px;
    }

Remove white space above and below large text in an inline-block element

span::before,
span::after {
    content: '';
    display: block;
    height: 0;
    width: 0;
}

span::before{
    margin-top:-6px;
}

span::after{
    margin-bottom:-8px;
}

Find out the margin-top and margin-bottom negative margins with this tool: http://text-crop.eightshapes.com/

The tool also gives you SCSS, LESS and Stylus examples. You can read more about it here: https://medium.com/eightshapes-llc/cropping-away-negative-impacts-of-line-height-84d744e016ce

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

How to compare type of an object in Python?

You can always use the type(x) == type(y) trick, where y is something with known type.

# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)

Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.

In this case, the better ways would be:

# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None

Note the last case: there is only one instance of NoneType in python, and that is None. You'll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable -- happens to me all the time..) but you'll hardly ever need to refer to it in code.

Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.

Running Selenium WebDriver python bindings in chrome

For windows

Download ChromeDriver from this direct link OR get the latest version from this page.

Paste the chromedriver.exe file in your C:\Python27\Scripts folder.

This should work now:

from selenium import webdriver
driver = webdriver.Chrome()

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

HTML meta tag for content language

another language meta tag is og:locale and you can define og:locale meta tag for social media

<meta property="og:locale" content="en" />

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python foo.py | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported.

How to check queue length in Python

it is simple just use .qsize() example:

a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue

The above snippet applies for Queue() class of python. Thanks @rayryeng for the update.

for deque from collections we can use len() as stated here by K Z.

Windows command to get service status?

Maybe this could be the best way to start a service and check the result

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@ECHO OFF

REM Put whatever your Batch may do before trying to start the service

net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error

REM Put Whatever you want in case Service was not running and start correctly

GOTO ContinueWithBatch

:AlreadyRunning
REM Put Whatever you want in case Service was already running
GOTO ContinueWithBatch

:Error
REM Put Whatever you want in case Service fail to start
GOTO ContinueWithBatch

:ContinueWithBatch

REM Put whatever else your Batch may do

Another thing is to check for its state without changing it, for that there is a much more simple way to do it, just run:

net start

As that, without parameters it will show a list with all services that are started...

So a simple grep or find after it on a pipe would fit...

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@ECHO OFF

REM Put here any code to be run before check for Service

SET TemporalFile=TemporalFile.TXT
NET START | FIND /N "NameOfSercive" > %TemporalFile%
SET CountLines=0
FOR /F %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
IF 0==%CountLines% GOTO ServiceIsNotRunning

REM Put here any code to be run if Service Is Running

GOTO ContinueWithBatch

:ServiceIsNotRunning

REM Put here any code to be run if Service Is Not Running

GOTO ContinueWithBatch
:ContinueWithBatch
DEL -P %TemporalFile% 2>nul
SET TemporalFile=

REM Put here any code to be run after check for Service

Hope this can help!! It is what i normally use.

add title attribute from css

While currently not possible with CSS, there is a proposal to enable this functionality called Cascading Attribute Sheets.

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Clicking HTML 5 Video element to play, pause video, breaks play button

Not to bring up an old post but I landed on this question in my search for the same solution. I ended up coming up with something of my own. Figured I'd contribute.

HTML:

<video class="video"><source src=""></video>

JAVASCRIPT: "JQUERY"

$('.video').click(function(){this.paused?this.play():this.pause();});

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Difference between static, auto, global and local variable in the context of c and c++

When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -

#include<iostream.h>
#include<conio.h>
class test
{
    void fun()
    {
        static int a=0;
        a++;
        cout<<"Value of a = "<<a<<"\n";
    }
};
void main()
{
    clrscr();
    test obj1;
    test obj2;
    test obj3;
    obj1.fun();
    obj2.fun();
    obj3.fun();
    getch();
}

This program will generate the following output: -

Value of a = 1
Value of a = 2
Value of a = 3

The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()

Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -

Value of a = 1
Value of a = 1
Value of a = 1

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

What are you expecting? The default Tomcat homepage? If so, you'll need to configure Eclipse to take control over from Tomcat.

Doubleclick the Tomcat server entry in the Servers tab, you'll get the server configuration. At the left column, under Server Locations, select Use Tomcat installation (note, when it is grayed out, read the section leading text! ;) ). This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse. I only don't see how that's useful while developing using Eclipse.

enter image description here

The port number is not the problem. You would otherwise have gotten an exception in Tomcat's startup log, and the browser would show a browser-specific "Connection timed out" error page and thus not a Tomcat-specific error page which could impossibly be served when Tomcat was not up and running.

jQuery Mobile - back button

You can use nonHistorySelectors option from jquery mobile where you do not want to track history. You can find the detailed documentation here http://jquerymobile.com/demos/1.0a4.1/#docs/api/globalconfig.html

What version of MongoDB is installed on Ubuntu

When you entered in mongo shell using "mongo" command , that time only you will notice

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2

also you can try command,in mongo shell , db.version()

jQuery UI dialog box not positioned center screen

I was having the same problem. It ended up being the jquery.dimensions.js plugin. If I removed it, everything worked fine. I included it because of another plugin that required it, however I found out from the link here that dimensions was included in the jQuery core quite a while ago (http://api.jquery.com/category/dimensions). You should be ok simply getting rid of the dimensions plugin.

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

Add column in dataframe from list

First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.

df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})

And the mapping that you desire:

mapping = dict(enumerate([2,5,6,8,12,16,26,32]))

df['D'] = df['A'].map(mapping)

Done!

print df

Output:

   A   D
0  0   2
1  4  12
2  5  16
3  6  26
4  7  32
5  7  32
6  6  26
7  5  16

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Partition Function COUNT() OVER possible using DISTINCT

There is a very simple solution using dense_rank()

dense_rank() over (partition by [Mth] order by [UserAccountKey]) 
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc) 
- 1

This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

How to support placeholder attribute in IE8 and 9

    <script>
        if ($.browser.msie) {
            $('input[placeholder]').each(function() {

                var input = $(this);

                $(input).val(input.attr('placeholder'));

                $(input).focus(function() {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });

                $(input).blur(function() {
                    if (input.val() == '' || input.val() == input.attr('placeholder')) {
                        input.val(input.attr('placeholder'));
                    }
                });
            });
        }
        ;
    </script>

Recursively counting files in a Linux directory

With bash:

Create an array of entries with ( ) and get the count with #.

FILES=(./*); echo ${#FILES[@]}

Ok that doesn't recursively count files but I wanted to show the simple option first. A common use case might be for creating rollover backups of a file. This will create logfile.1, logfile.2, logfile.3 etc.

CNT=(./logfile*); mv logfile logfile.${#CNT[@]}

Recursive count with bash 4+ globstar enabled (as mentioned by @tripleee)

FILES=(**/*); echo ${#FILES[@]}

To get the count of files recursively we can still use find in the same way.

FILES=(`find . -type f`); echo ${#FILES[@]}

How can I have same rule for two locations in NGINX config?

Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:

error_page 418 = @common_location;
location /first/location/ {
    return 418;
}
location /second/location/ {
    return 418;
}
location @common_location {
    # The common configuration...
}

There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.

The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.

Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:

location /specialpages/ {
    # some config
    location /specialpages/static/ {
        try_files $uri $uri/ =404;
    }
    location /specialpages/dynamic/ {
        proxy_pass http://127.0.0.1;
    }
}

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

in my case I was missing to write in web.xml:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext.xml</param-value>
   </context-param>

and in the application context file:

<context:component-scan base-package=[your package name] />

after add this tags and run maven to rebuild project the autowired error in intellj desapears and the bean icon appears in the left margin: enter image description here

What is the maximum number of edges in a directed graph with n nodes?

If you have N nodes, there are N - 1 directed edges than can lead from it (going to every other node). Therefore, the maximum number of edges is N * (N - 1).

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Did you use the webpack... if yes please install

angular2-template-loader

and put it

test: /\.ts$/,
   loaders: ['awesome-typescript-loader', 'angular2-template-loader']

Adding ASP.NET MVC5 Identity Authentication to an existing project

This is what I did to integrate Identity with an existing database.

  1. Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.

  2. Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam

  3. Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.

  4. This is the SQL script I ran on my existing database to create necessary tables:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  5. Check and solve any remaining errors and you are done. Identity will handle the rest :)

Where is jarsigner?

This error comes when you only have JRE installed instead of JDK in your JAVA_HOME variable. Unfortunately, you cannot have both of them installed in the same variable so you just need to overwrite the variable with new JDK installation path.

The process should be the same as the way you had JRE installed

How to normalize a histogram in MATLAB?

Since 2014b, Matlab has these normalization routines embedded natively in the histogram function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).

data = 2*randn(5000,1) + 5;             % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf')   % PDF normalization

The corresponding PDF is

Nbins = h.NumBins;
edges = h.BinEdges; 
x = zeros(1,Nbins);
for counter=1:Nbins
    midPointShift = abs(edges(counter)-edges(counter+1))/2;
    x(counter) = edges(counter)+midPointShift;
end

mu = mean(data);
sigma = std(data);

f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));

The two together gives

hold on;
plot(x,f,'LineWidth',1.5)

enter image description here

An improvement that might very well be due to the success of the actual question and accepted answer!


EDIT - The use of hist and histc is not recommended now, and histogram should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist and histc produce. There is a Matlab script to update former code to fit the way histogram is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf normalization methods of @abcd (trapz and sum) and Matlab (pdf).

The 3 pdf normalization method give nearly identical results (within the range of eps).

TEST:

A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));

figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');

subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');

subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');


subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');

dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);

max(normalization_difference_trapz)
max(normalization_difference_sum)

enter image description here

The maximum difference between the new PDF normalization and the former one is 5.5511e-17.

Loop through checkboxes and count each one checked or unchecked

I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.

Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.

Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.

So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.

What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.

The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

The difference is not just for Chrome but for most of the web browsers.

enter image description here

F5 refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.

Shift + F5 forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.

Shift + F5 guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5.

You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

What's wrong with overridable method calls in constructors?

If you call methods in your constructor that subclasses override, it means you are less likely to be referencing variables that don’t exist yet if you divide your initialization logically between the constructor and the method.

Have a look on this sample link http://www.javapractices.com/topic/TopicAction.do?Id=215

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Get the latest record from mongodb collection

This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })

you can add or remove from the group

help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

https://docs.mongodb.com/manual/reference/operator/aggregation/last/

What is the difference between x86 and x64

Oddly enough it was an Intel thing not a Microsoft thing. X86 referred to the Intel CPU series from the 8086 to the 80486. The Pentium series still use the same addressing system. The x64 refers to the I64 addressing system that Intel came out with later for the 64-bit CPUs. So Windows was just following Intel's architecture naming.

Disable activity slide-in animation when launching new activity?

I had a similar problem of getting a black screen appear on sliding transition from one activity to another using overridependingtransition. and I followed the way below and it worked

1) created a noanim.xml in anim folder

<?xml version="1.0" encoding="utf-8"?>
<translate 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromYDelta="0%p"
    android:toYDelta="0%p" />

and used

overridePendingTransition(R.drawable.lefttorightanim, R.anim.noanim);

The first parameter as my original animation and second parameter which is the exit animation as my dummy animation

Use jQuery to scroll to the bottom of a div with lots of text

//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
    $("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}

scrollDown = function() {
    var scroller = $('#scroller');
    var height = scroller[0].scrollHeight - $(scroller).height();

    $(scroller).stop().animate({ scrollTop: height }, "slow");
}

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

The model backing the 'ApplicationDbContext' context has changed since the database was created

simply the error means that your models has changes and is not in Sync with DB ,so go to package manager console , add-migration foo2 this will give a hint of what is causing the issue , may be you removed something or in my case I remove a data annotation . from there you can get the change and hopefully reverse it in your model.

after that delete foo2 .

Returning an empty array

Definitely the second one. In the first one, you use a constant empty List<?> and then convert it to a File[], which requires to create an empty File[0] array. And that is what you do in the second one in one single step.

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

Laravel Redirect Back with() Message

In Laravel 5.4 the following worked for me:

return back()->withErrors(['field_name' => ['Your custom message here.']]);

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I should understand the problem by just seeing

dex errors

But it took a half day to fix the issue.
I fix this by following android developers page's instruction: https://developer.android.com/studio/build/multidex.html

First add this to gradle.build file :

defaultConfig {
    ...
    minSdkVersion 14
    targetSdkVersion 21
    ...

    // Enabling multidex support.
    multiDexEnabled true
}

 dependencies {
     compile 'com.android.support:multidex:1.0.0'
 }

Then extend Application class with the MultiDexApplication class as instructed on the above link (or declare the application class in AndroidManifest.xml or override attachBaseContext() function if not possible to extend the application class).

That's all and it solved the problem.

How to change UIPickerView height

I use a mask layer to change it's display size

// swift 3.x
let layer = CALayer()
layer.frame = CGRect(x: 0,y:0, width: displayWidth, height: displayHeight)
layer.backgroundColor = UIColor.red.cgColor
pickerView.layer.mask = layer

How should I log while using multiprocessing in Python?

QueueHandler is native in Python 3.2+, and does exactly this. It is easily replicated in previous versions.

Python docs have two complete examples: Logging to a single file from multiple processes

For those using Python < 3.2, just copy QueueHandler into your own code from: https://gist.github.com/vsajip/591589 or alternatively import logutils.

Each process (including the parent process) puts its logging on the Queue, and then a listener thread or process (one example is provided for each) picks those up and writes them all to a file - no risk of corruption or garbling.

Count number of rows within each group

The simple option to use with aggregate is the length function which will give you the length of the vector in the subset. Sometimes a little more robust is to use function(x) sum( !is.na(x) ).

Select query to remove non-numeric characters

In your case It seems like the # will always be after teh # symbol so using CHARINDEX() with LTRIM() and RTRIM() would probably perform the best. But here is an interesting method of getting rid of ANY non digit. It utilizes a tally table and table of digits to limit which characters are accepted then XML technique to concatenate back to a single string without the non-numeric characters. The neat thing about this technique is it could be expanded to included ANY Allowed characters and strip out anything that is not allowed.

DECLARE @ExampleData AS TABLE (Col VARCHAR(100))
INSERT INTO @ExampleData (Col) VALUES ('AB ABCDE # 123'),('ABCDE# 123'),('AB: ABC# 123')

DECLARE @Digits AS TABLE (D CHAR(1))
INSERT INTO @Digits (D) VALUES ('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')

;WITH cteTally AS (
SELECT
    I = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM
    @Digits d10
    CROSS APPLY @Digits d100
    --add more cross applies to cover longer fields this handles 100
)

SELECT *
FROM
    @ExampleData e
    OUTER APPLY (
    SELECT CleansedPhone = CAST((
    SELECT TOP 100
       SUBSTRING(e.Col,t.I,1)
    FROM
       cteTally t
       INNER JOIN @Digits d
       ON SUBSTRING(e.Col,t.I,1) = d.D
    WHERE
       I <= LEN(e.Col)
    ORDER BY
       t.I
    FOR XML PATH('')) AS VARCHAR(100))) o

Adding IN clause List to a JPA Query

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

How to easily resize/optimize an image size with iOS?

you can use this code to scale image in required size.

+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
    CGSize actSize = image.size;
    float scale = actSize.width/actSize.height;

    if (scale < 1) {
        newSize.height = newSize.width/scale;
    } 
    else {
        newSize.width = newSize.height*scale;
    }

    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

angularjs to output plain text instead of html

Use ng-bind-html this is only proper and simplest way

filedialog, tkinter and opening files

I had to specify individual commands first and then use the * to bring all in command.

from tkinter import filedialog
from tkinter import *

Multi-statement Table Valued Function vs Inline Table Valued Function

I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.

How to create a new schema/new user in Oracle Database 11g?

From oracle Sql developer, execute the below in sql worksheet:

create user lctest identified by lctest;
grant dba to lctest;

then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.

Reload the page after ajax success

You use the ajaxStop to execute code when the ajax are completed:

$(document).ajaxStop(function(){
  setTimeout("window.location = 'otherpage.html'",100);
});

How to create windows service from java jar?

[2020 Update]

Actually, after spending some times trying the different option provided here which are quite old, I found that the easiest way to do it was to use a small paid tool built for that purpose : FireDaemon Pro. I was trying to run Selenium standalone server as a service and none of the free option worked instantly.

The tool is quite cheap (50 USD one-time-licence, 30 days trial) and it took me 5 minutes to set up the server service instead of a half a day of reading/troubleshooting. So far, it works like a charm.

I have absolutely no link with FusionPro, this is a pure disinterested advice, but feel free to delete if it violates forum rules.

Android failed to load JS bundle

An easy solution that works for me with Ubuntu 14.04.

react-native run-android

The emulator (already launched) will return: Unable to download JS Bundle; start again the JS server:

react-native start

Hit Reload JS on the emulator. It worked for me. Hope it will help

Get unique values from a list in python

What type is your output variable?

Python sets are what you need. Declare output like this:

output = set()  # initialize an empty set

and you're ready to go adding elements with output.add(elem) and be sure they're unique.

Warning: sets DO NOT preserve the original order of the list.

How to output in CLI during execution of PHP Unit tests?

For some cases one could use something like that to output something to the console

class yourTests extends PHPUnit_Framework_TestCase
{
    /* Add Warnings */
    protected function addWarning($msg, Exception $previous = null)
    {
        $add_warning = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
        $add_warning->addWarning($this, $msg, time());
        $this->setTestResultObject($add_warning);
    }

    /* Add errors */
    protected function addError($msg, Exception $previous = null)
    {
        $add_error = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_error->addError($this, $msg, time());
        $this->setTestResultObject($add_error);
    }

    /* Add failures */
    protected function addFailure($msg, Exception $previous = null)
    {
        $add_failure = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_failure->addFailure($this, $msg, time());
        $this->setTestResultObject($add_failure);
    }

    public function test_messages()
    {
        $this->addWarning("Your warning message!");
        $this->addError("Your error message!");
        $this->addFailure("Your Failure message");
    }

    /* Or just mark test states! */
    public function test_testMarking()
    {
        $this->markTestIncomplete();
        $this->markTestSkipped();
    }
}

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

Add centered text to the middle of a <hr/>-like line

please try this with bootstrap:

<div class="text-center d-flex">
  <hr className="flex-grow-1" />
  <span className="px-2 font-weight-lighter small align-self-center">
    Hello
  </span>
  <hr className="flex-grow-1" />
</div>

here is result

How to select date from datetime column?

Using WHERE DATE(datetime) = '2009-10-20' has performance issues. As stated here:

  • it will calculate DATE() for all rows, including those that don't match.
  • it will make it impossible to use an index for the query.

Use BETWEEN or >, <, = operators which allow to use an index:

SELECT * FROM data 
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'

Update: the impact on using LIKE instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:

  • using datetime LIKE '2009-10-20%' => 2931ms
  • using datetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59' => 168ms

When doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.

Does Django scale?

The developer advocate for YouTube gave a talk about scaling Python at PyCon 2012, which is also relevant to scaling Django.

YouTube has more than a billion users, and YouTube is built on Python.

SQL query to select distinct row with minimum value

Try:

select id, game, min(point) from t
group by id 

How to restart Jenkins manually?

If it is deployed as a war file then restart the application server, for example, Tomcat.

Which keycode for escape key with jQuery

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.

$(document).ready(function(){

    // Set focus
    setTimeout('window.focus()',1000);

});

$(document).keypress(function(e) {

    // Enable esc
    if (e.keyCode == 27) {
      parent.document.getElementById('iframediv').style.display='none';
      parent.document.getElementById('iframe').src='/views/view.empty.black.html';
    }

});

Embed website into my site

Put content from other site in iframe

<iframe src="/othersiteurl" width="100%" height="300">
  <p>Your browser does not support iframes.</p>
</iframe>

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

Remove the last chars of the Java String variable

I am surprised to see that all the other answers (as of Sep 8, 2013) either involve counting the number of characters in the substring ".null" or throw a StringIndexOutOfBoundsException if the substring is not found. Or both :(

I suggest the following:

public class Main {

    public static void main(String[] args) {

        String path = "file.txt";
        String extension = ".doc";

        int position = path.lastIndexOf(extension);

        if (position!=-1)
            path = path.substring(0, position);
        else
            System.out.println("Extension: "+extension+" not found");

        System.out.println("Result: "+path);
    }

}

If the substring is not found, nothing happens, as there is nothing to cut off. You won't get the StringIndexOutOfBoundsException. Also, you don't have to count the characters yourself in the substring.

dropdownlist set selected value in MVC3 Razor

Replace below line with new updated working code:

@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)

Now Implement new updated working code:

@Html.DropDownListFor(model => model.NewsCategoriesID, ViewBag.NewsCategoriesID as List<SelectListItem>, new {name = "NewsCategoriesID", id = "NewsCategoriesID" })

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

How to autosize a textarea using Prototype?

Here's a Prototype version of resizing a text area that is not dependent on the number of columns in the textarea. This is a superior technique because it allows you to control the text area via CSS as well as have variable width textarea. Additionally, this version displays the number of characters remaining. While not requested, it's a pretty useful feature and is easily removed if unwanted.

//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {}; 

Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 30,
      'max_length' : 400
    }).update(options);

    this.textarea.observe('keyup', this.refresh.bind(this));

    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });

    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});  
    this.refresh();  
  },

  refresh: function()
  { 
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    var remaining = this.options.get('max_length') - $F(this.textarea).length;
    this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
  }
});

Create the widget by calling new Widget.Textarea('element_id'). The default options can be overridden by passing them as an object, e.g. new Widget.Textarea('element_id', { max_length: 600, min_height: 50}). If you want to create it for all textareas on the page, do something like:

Event.observe(window, 'load', function() {
  $$('textarea').each(function(textarea) {
    new Widget.Textarea(textarea);
  });   
});

How to select a radio button by default?

They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:

<input type="radio" checked="checked">

...and you got it.

Cheers!

Clearing the terminal screen?

ESC is the character _2_7, not _1_7. You can also try decimal 12 (aka. FF, form feed).

Note that all these special characters are not handled by the Arduino but by the program on the receiving side. So a standard Unix terminal (xterm, gnome-terminal, kterm, ...) handles a different set of control sequences then say a Windows terminal program like HTerm.

Therefore you should specify what program you are using exactly for display. After that it is possible to tell you what control characters and control sequences are usable.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

WCF error: The caller was not authenticated by the service

Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.