Programs & Examples On #Literals

a notation for representing fixed values in source code

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "measure_weight_speed.py", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

Why does instanceof return false for some literals?

The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, num­bers, or Booleans are read.For example :

var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);

This is what happens behind the scenes:

// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);

Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work.The String object exists only for one statement before it’s destroyed check this

The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the ­values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually

escaping question mark in regex javascript

You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:

var gent = /I like your Apartment. Could we schedule a viewing\?/g;

How do you express binary literals in Python?

Another good method to get an integer representation from binary is to use eval()

Like so:

def getInt(binNum = 0):
    return eval(eval('0b' + str(n)))

I guess this is a way to do it too. I hope this is a satisfactory answer :D

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

SQL Server - boolean literal?

I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!

What does the M stand for in C# Decimal literal notation?

Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.

Can I escape a double quote in a verbatim string literal?

This should help clear up any questions you may have: C# literals

Here is a table from the linked content:

Regular literal Verbatim literal Resulting string
"Hello" @"Hello" Hello
"Backslash: \\" @"Backslash: \" Backslash: \
"Quote: \"" @"Quote: """ Quote: "
"CRLF:\r\nPost CRLF" @"CRLF:
Post CRLF"
CRLF:
Post CRLF

Java: how do I get a class literal from a generic type?

The Java Generics FAQ and therefore also cletus' answer sound like there is no point in having Class<List<T>>, however the real problem is that this is extremely dangerous:

@SuppressWarnings("unchecked")
Class<List<String>> stringListClass = (Class<List<String>>) (Class<?>) List.class;

List<Integer> intList = new ArrayList<>();
intList.add(1);
List<String> stringList = stringListClass.cast(intList);
// Surprise!
String firstElement = stringList.get(0);

The cast() makes it look as if it is safe, but in reality it is not safe at all.


Though I don't get where there can't be List<?>.class = Class<List<?>> since this would be pretty helpful when you have a method which determines the type based on the generic type of a Class argument.

For getClass() there is JDK-6184881 requesting to switch to using wildcards, however it does not look like this change will be performed (very soon) since it is not compatible with previous code (see this comment).

How do you specify a byte literal in Java?

With Java 7 and later version, you can specify a byte literal in this way: byte aByte = (byte)0b00100001;

Reference: http://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html

Tensorflow: how to save/restore a model?

Wherever you want to save the model,

self.saver = tf.train.Saver()
with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            ...
            self.saver.save(sess, filename)

Make sure, all your tf.Variable have names, because you may want to restore them later using their names. And where you want to predict,

saver = tf.train.import_meta_graph(filename)
name = 'name given when you saved the file' 
with tf.Session() as sess:
      saver.restore(sess, name)
      print(sess.run('W1:0')) #example to retrieve by variable name

Make sure that saver runs inside the corresponding session. Remember that, if you use the tf.train.latest_checkpoint('./'), then only the latest check point will be used.

How to change menu item text dynamically in Android

I use this code to costum my bottom navigation item

BottomNavigationView navigation = this.findViewById(R.id.my_bottom_navigation);
Menu menu = navigation.getMenu();
menu.findItem(R.id.nav_wall_see).setTitle("Hello");

What is the difference between ( for... in ) and ( for... of ) statements?

Another difference between the two loops, which nobody has mentioned before:

Destructuring for...in is deprecated. Use for...of instead.

Source

So if we want to use destructuring in a loop, for get both index and value of each array element, we should to use the for...of loop with the Array method entries():

for (const [idx, el] of arr.entries()) {
    console.log( idx + ': ' + el );
}

How to check if a string starts with one of several prefixes?

if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)

You need to include the whole str.startsWith(otherStr) for each item, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.

An example regular expression for detecting day name abbreviations would be:

if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {

How can I install pip on Windows?

Python 2.7.9+ and 3.4+

Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Node.js, Haskell, Perl, Go—almost every other contemporary language with a majority open-source community. Thank you, Python.

If you do find that pip is not available when using Python 3.4+ or Python 2.7.9+, simply execute e.g.:

py -3 -m ensurepip

Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this in the Stack Overflow question Does Python have a package/module management system?.

And, alas for everyone using Python 2.7.8 or earlier (a sizable portion of the community). There's no plan to ship Pip to you. Manual instructions follow.

Python 2 = 2.7.8 and Python 3 = 3.3

Flying in the face of its 'batteries included' motto, Python ships without a package manager. To make matters worse, Pip was—until recently—ironically difficult to install.

Official instructions

Per https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip:

Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt:

python get-pip.py

You possibly need an administrator command prompt to do this. Follow Start a Command Prompt as an Administrator (Microsoft TechNet).

This installs the pip package, which (in Windows) contains ...\Scripts\pip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of 'Alternative Instructions' for adding it to your PATH,

Alternative instructions

The official documentation tells users to install Pip and each of its dependencies from source. That's tedious for the experienced and prohibitively difficult for newbies.

For our sake, Christoph Gohlke prepares Windows installers (.msi) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:

  1. Install setuptools
  2. Install pip

For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (for example, C:\Python27\Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:

pip install httpie

There you go (hopefully)! Solutions for common problems are given below:

Proxy problems

If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables http_proxy and https_proxy. Most Python applications (and other free software) respect these. Example syntax:

http://proxy_url:port
http://username:password@proxy_url:port

If you're really unlucky, your proxy might be a Microsoft NTLM proxy. Free software can't cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. http://cntlm.sourceforge.net/

Unable to find vcvarsall.bat

Python modules can be partly written in C or C++. Pip tries to compile from source. If you don't have a C/C++ compiler installed and configured, you'll see this cryptic error message.

Error: Unable to find vcvarsall.bat

You can fix that by installing a C++ compiler such as MinGW or Visual C++. Microsoft actually ships one specifically for use with Python. Or try Microsoft Visual C++ Compiler for Python 2.7.

Often though it's easier to check Christoph's site for your package.

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

Android: How to change CheckBox size?

I use

android:scaleX="0.70" android:scaleY="0.70"

to ajust the size of checkbox

then I set margins like this

android:layout_marginLeft="-10dp"

to adjust ths location of the checkbox.

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

ActionController::InvalidAuthenticityToken

I had this problem and the reason was because I copied and pasted a controller into my app. I needed to change ApplicationController to ApplicationController::Base

Convert base-2 binary number string to int

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

Note that the unsigned integer is different from the signed integer:

>>> b.int
-1

The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

How to pass password to scp?

You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How to get the pure text without HTML element using JavaScript?

This answer will work to get just the text for any HTML element.

This first parameter "node" is the element to get the text from. The second parameter is optional and if true will add a space between the text within elements if no space would otherwise exist there.

function getTextFromNode(node, addSpaces) {
    var i, result, text, child;
    result = '';
    for (i = 0; i < node.childNodes.length; i++) {
        child = node.childNodes[i];
        text = null;
        if (child.nodeType === 1) {
            text = getTextFromNode(child, addSpaces);
        } else if (child.nodeType === 3) {
            text = child.nodeValue;
        }
        if (text) {
            if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text;
            result += text;
        }
    }
    return result;
}

How to import a JSON file in ECMAScript 6?

Unfortunately ES6/ES2015 doesn't support loading JSON via the module import syntax. But...

There are many ways you can do it. Depending on your needs you can either look into how to read files in JavaScript (window.FileReader could be an option if you're running in the browser) or use some other loaders as described in other questions (assuming you are using NodeJS).

IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way you can just import it where you need it.

Also worth noting if you're using Webpack, importing of JSON files will work by default (since webpack >= v2.0.0).

import config from '../config.json';

Print all properties of a Python Class

In this simple case you can use vars():

an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))

If you want to store Python objects on the disk you should look at shelve — Python object persistence.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Insert into ... values ( SELECT ... FROM ... )

To add something in the first answer, when we want only few records from another table (in this example only one):

INSERT INTO TABLE1
(COLUMN1, COLUMN2, COLUMN3, COLUMN4) 
VALUES (value1, value2, 
(SELECT COLUMN_TABLE2 
FROM TABLE2
WHERE COLUMN_TABLE2 like "blabla"),
value4);

Select columns from result set of stored procedure

I know executing from sp and insert into temp table or table variable would be an option but I don't think that's your requirement. As per your requirement this below query statement should work:

Declare @sql nvarchar(max)
Set @sql='SELECT   col1, col2 FROM OPENROWSET(''SQLNCLI'', ''Server=(local);uid=test;pwd=test'',
     ''EXEC MyStoredProc ''''param1'''', ''''param2'''''')'
 Exec(@sql)

if you have trusted connection then use this below query statement :

Declare @sql nvarchar(max)
Set @sql='SELECT   col1, col2 FROM OPENROWSET(''SQLNCLI'', ''Server=(local);Trusted_Connection=yes;'',
     ''EXEC MyStoredProc ''''param1'''', ''''param2'''''')'
 Exec(@sql)

if you are getting error to run the above statement then just run this statement below:

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

I hope this will help someone who will have faced this kind of similar problem. If someone would to try with temp table or table variable that should be like this below but in this scenario you should to know how many columns your sp is returning then you should create that much columns in temp table or table variable:

--for table variable 
Declare @t table(col1 col1Type, col2 col2Type)
insert into @t exec MyStoredProc 'param1', 'param2'
SELECT col1, col2 FROM @t

--for temp table
create table #t(col1 col1Type, col2 col2Type)
insert into #t exec MyStoredProc 'param1', 'param2'
SELECT col1, col2 FROM #t

Loop inside React JSX

If you opt to convert this inside return( ) of render method, easiest option would be using map( ) method. Map your array into JSX syntax using map() function, as shown below (ES6 syntax is used).


Inside parent component:

<tbody>
   { objectArray.map(object => <ObjectRow key={object.id} object={object.value}>) }
</tbody>

Please note the key attribute added to your child component. If you didn't provide a key attribute, you can see the following warning on your console.

Warning: Each child in an array or iterator should have a unique "key" prop.

Note: One common mistake people do is using index as key when iterating, using index of the element as a key is an anti-pattern and you can read more about it here. In short, if it's NOT a static list never use index as key.


Now at the ObjectRow component, you can access the object from its properties.

Inside ObjectRow component

const { object } = this.props

or

const object = this.props.object

This should fetch you the object you passed from parent component to the variable object in ObjectRow component. Now you can spit out the values in that object according to your purpose.


References :

map() method in Javascript

ECMA Script 6 or ES6

When to use throws in a Java method declaration?

You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.

See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html

If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

A quick fix for capistrano user is to put this line to Capfile

# Uncomment if you are using Rails' asset pipeline
load 'deploy/assets'

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How can I make Jenkins CI with Git trigger on pushes to master?

In my current organization, we don't do this in master but do do it on both develop and release/ branches (we are using Git Flow), in order to generate snapshot builds.

As we are using a multi branch pipeline, we do this in the Jenkinsfile with the when{} syntax...

stage {
    when { 
        expression { 
            branch 'develop'
        }
    }
}

This is detailed in this blog post: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/#longer-pipeline

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

Search of table names

select name
  from DBname.sys.tables
 where name like '%xxx%'
   and is_ms_shipped = 0; -- << comment out if you really want to see them

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Pass array to MySQL stored routine

If you don't want to use temporary tables here is a split string like function you can use

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

Text border using css (border around text)

I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.

The right tool exists, it's SVG <text> The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too, filter: progid:DXImageTransform can be used or IE < 10 but often doesn't work as expected.

To me the best solution remains SVG with a fallback in not-stroked text for older browser:

This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9

Compared to text-shadow whose supports are: Chrome 4.0, FF 3.5, IE 10, Safari 4.0, Opera 9, it results even more compatible.

_x000D_
_x000D_
.stroke {_x000D_
  margin: 0;_x000D_
  font-family: arial;_x000D_
  font-size:70px;_x000D_
  font-weight: bold;_x000D_
  }_x000D_
  _x000D_
  svg {_x000D_
    display: block;_x000D_
  }_x000D_
  _x000D_
  text {_x000D_
    fill: black;_x000D_
    stroke: red;_x000D_
    stroke-width: 3;_x000D_
  }
_x000D_
<p class="stroke">_x000D_
  <svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
    <text x="0" y="70">Stroked text</text>_x000D_
  </svg>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Linq code to select one item

You could use the extension method syntax:

var item = Items.Select(x => x.Id == 123).FirstOrDefault();

Other than that, I'm not sure how much more concise you can get, without maybe writing your own specialized "First" and "FirstOrDefault" extension methods.

jQuery UI autocomplete with JSON

I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}

How can I get selector from jQuery object

Ok, so in a comment above the question asker Fidilip said that what he/she's really after is to get the path to the current element.

Here's a script that will "climb" the DOM ancestor tree and then build fairly specific selector including any id or class attributes on the item clicked.

See it working on jsFiddle: http://jsfiddle.net/Jkj2n/209/

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(function() {
        $("*").on("click", function(e) {
          e.preventDefault();
          var selector = $(this)
            .parents()
            .map(function() { return this.tagName; })
            .get()
            .reverse()
            .concat([this.nodeName])
            .join(">");

          var id = $(this).attr("id");
          if (id) { 
            selector += "#"+ id;
          }

          var classNames = $(this).attr("class");
          if (classNames) {
            selector += "." + $.trim(classNames).replace(/\s/gi, ".");
          }

          alert(selector);
      });
    });
    </script>
</head>
<body>
<h1><span>I love</span> jQuery</h1>
<div>
  <p>It's the <strong>BEST THING</strong> ever</p>
  <button id="myButton">Button test</button>
</div>
<ul>
  <li>Item one
    <ul>
      <li id="sub2" >Sub one</li>
      <li id="sub2" class="subitem otherclass">Sub two</li>
    </ul>
  </li>
</ul>
</body>
</html>

For example, if you were to click the 2nd list nested list item in the HTML below, you would get the following result:

HTML>BODY>UL>LI>UL>LI#sub2.subitem.otherclass

Using python's eval() vs. ast.literal_eval()?

eval: This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.

ast.literal_eval: Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.

Syntax:

eval(expression, globals=None, locals=None)
import ast
ast.literal_eval(node_or_string)

Example:

# python 2.x - doesn't accept operators in string format
import ast
ast.literal_eval('[1, 2, 3]')  # output: [1, 2, 3]
ast.literal_eval('1+1') # output: ValueError: malformed string


# python 3.0 -3.6
import ast
ast.literal_eval("1+1") # output : 2
ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}") # output : {'a': 2, 'b': 3, 3:'xyz'}
# type dictionary
ast.literal_eval("",{}) # output : Syntax Error required only one parameter
ast.literal_eval("__import__('os').system('rm -rf /')") # output : error

eval("__import__('os').system('rm -rf /')") 
# output : start deleting all the files on your computer.
# restricting using global and local variables
eval("__import__('os').system('rm -rf /')",{'__builtins__':{}},{})
# output : Error due to blocked imports by passing  '__builtins__':{} in global

# But still eval is not safe. we can access and break the code as given below
s = """
(lambda fc=(
lambda n: [
    c for c in 
        ().__class__.__bases__[0].__subclasses__() 
        if c.__name__ == n
    ][0]
):
fc("function")(
    fc("code")(
        0,0,0,0,"KABOOM",(),(),(),"","",0,""
    ),{}
)()
)()
"""
eval(s, {'__builtins__':{}})

In the above code ().__class__.__bases__[0] nothing but object itself. Now we instantiated all the subclasses, here our main enter code hereobjective is to find one class named n from it.

We need to code object and function object from instantiated subclasses. This is an alternative way from CPython to access subclasses of object and attach the system.

From python 3.7 ast.literal_eval() is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. link

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

Update ViewPager dynamically?

for those who still face the same problem which i faced before when i have a ViewPager with 7 fragments. the default for these fragments to load the English content from API service but the problem here that i want to change the language from settings activity and after finish settings activity i want ViewPager in main activity to refresh the fragments to match the language selection from the user and load the Arabic content if user chooses Arabic here what i did to work from the first time

1- You must use FragmentStatePagerAdapter as mentioned above.

2- on mainActivity i override the onResume and did the following

if (!(mPagerAdapter == null)) {
    mPagerAdapter.notifyDataSetChanged();
}

3-i overrided the getItemPosition() in mPagerAdapter and make it return POSITION_NONE.

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

works like charm

Use of "this" keyword in formal parameters for static methods in C#

I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Overcoming "Display forbidden by X-Frame-Options"

UPDATE 2019: You can bypass X-Frame-Options in an <iframe> using just client-side JavaScript and my X-Frame-Bypass Web Component. Here is a demo: Hacker News in an X-Frame-Bypass. (Tested in Chrome & Firefox.)

Remove all the children DOM elements in div

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

.NET - How do I retrieve specific items out of a Dataset?

int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

How to set the custom border color of UIView programmatically?

Swift 5.2, UIView+Extension

extension UIView {
    public func addViewBorder(borderColor:CGColor,borderWith:CGFloat,borderCornerRadius:CGFloat){
        self.layer.borderWidth = borderWith
        self.layer.borderColor = borderColor
        self.layer.cornerRadius = borderCornerRadius

    }
}

You used this extension;

yourView.addViewBorder(borderColor: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), borderWith: 1.0, borderCornerRadius: 20)

Immediate exit of 'while' loop in C++

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

Open Url in default web browser

Try this:

import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
  Linking.openURL(url);
};

const App = () => {
  return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};

Hope this will solve your problem.

How to get a MemoryStream from a Stream in .NET?

I use this combination of extension methods:

    public static Stream Copy(this Stream source)
    {
        if (source == null)
            return null;

        long originalPosition = -1;

        if (source.CanSeek)
            originalPosition = source.Position;

        MemoryStream ms = new MemoryStream();

        try
        {
            Copy(source, ms);

            if (originalPosition > -1)
                ms.Seek(originalPosition, SeekOrigin.Begin);
            else
                ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }
        catch
        {
            ms.Dispose();
            throw;
        }
    }

    public static void Copy(this Stream source, Stream target)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (target == null)
            throw new ArgumentNullException("target");

        long originalSourcePosition = -1;
        int count = 0;
        byte[] buffer = new byte[0x1000];

        if (source.CanSeek)
        {
            originalSourcePosition = source.Position;
            source.Seek(0, SeekOrigin.Begin);
        }

        while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
            target.Write(buffer, 0, count);

        if (originalSourcePosition > -1)
        {
            source.Seek(originalSourcePosition, SeekOrigin.Begin);
        }
    }

Restarting cron after changing crontab file?

I had a similar issue on 16.04 VPS Digital Ocean. If you are changing crontabs, make sure to run

sudo service cron restart 

javascript toISOString() ignores timezone offset

My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()

var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();

How to tell if a string is not defined in a Bash shell script

Here is what I think is a much clearer way to check if a variable is defined:

var_defined() {
    local var_name=$1
    set | grep "^${var_name}=" 1>/dev/null
    return $?
}

Use it as follows:

if var_defined foo; then
    echo "foo is defined"
else
    echo "foo is not defined"
fi

How to run multiple SQL commands in a single SQL connection?

Multiple Non-query example if anyone is interested.

using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
  DbConnection.Open();
  using (OdbcCommand DbCommand = DbConnection.CreateCommand())
  {
    DbCommand.CommandText = "INSERT...";
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name";
    DbCommand.ExecuteNonQuery();

    DbCommand.Parameters.Clear();
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name2";
    DbCommand.ExecuteNonQuery();
  }
}

ImportError: Couldn't import Django

you need to go to the root directory and run the below command

source bin/activate

Once the above command is executed, you will be able to create custom apps

How can I convert a zero-terminated byte array to string?

The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.

Find the location of the first zero-byte using a binary search, then slice.

You can find the zero-byte like this:

package main

import "fmt"

func FirstZero(b []byte) int {
    min, max := 0, len(b)
    for {
        if min + 1 == max { return max }
        mid := (min + max) / 2
        if b[mid] == '\000' {
            max = mid
        } else {
            min = mid
        }
    }
    return len(b)
}
func main() {
    b := []byte{1, 2, 3, 0, 0, 0}
    fmt.Println(FirstZero(b))
}

It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Just wanted to drop a note. I was having trouble formatting a text 4000 field that had a mind of its own and the text would seeming wrap (or not wrap) randomly on the report. When I updated the column using the replace chr(10) noted above. My report finally formatted as I wanted. Many Thanx!

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

Dont make name with capital letters . Always use lowercase for naming . This will work fine . like companyLogo.png will raise error but company_logo.png will work fine.

How to set a default Value of a UIPickerView

TL:DR version:

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

OR you didn't use the the following method to get the selected item from your picker

- (NSInteger)selectedRowInComponent:(NSInteger)component

This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.

Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview


EDIT:

An example of manually setting and getting of a selected row in a UIPickerView:

the .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

the .m file:

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [source count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [source objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

EDIT for Swift solution (Source: Dan Beaulieu's answer)

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

adding multiple entries to a HashMap at once in one statement

Based on solution, presented by @Dakusan (the class defining to extend the HashMap), I did it this way:

  public static HashMap<String,String> SetHash(String...pairs) {
     HashMap<String,String> rtn = new HashMap<String,String>(pairs.length/2);
     for ( int n=0; n < pairs.length; n+=2 ) rtn.put(pairs[n], pairs[n + 1]);
    return rtn; 
  }

.. and using it this way:

HashMap<String,String> hm = SetHash( "one","aa", "two","bb", "tree","cc");

(Not sure if there is any disadvantages in that way (I am not a java developer, just has to do some task in java), but it works and seems to me comfortable.)

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

just change the content-type to application/json when you use JSON with POST/PUT, etc...

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

C++ passing an array pointer as a function argument

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
{
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;
}

int main()
{
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;
}

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

Running windows shell commands with python

You would use the os module system method.

You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC

For example:

os.system('python') opens up the windows command prompt and runs the python interpreter

os.system('python') example

The target principal name is incorrect. Cannot generate SSPI context

I was trying to connect to a VM running SQL Server 2015 from my laptop in a Visual Studio 2015 Console App. I run my app the night before and it is fine. In the morning I try to debug the app and I get this error. I tried ipconfig/flush and release + renew and a a bunch of other garbage, but in the end...

Restart your VM and restart the client. That fixed it for me. I should have known, restart works every time.

How to ignore certain files in Git

The problem is that .gitignore ignores just files that weren't tracked before (by git add). Run git reset name_of_file to unstage the file and keep it. In case you want to also remove the given file from the repository (after pushing), use git rm --cached name_of_file.

C# Copy a file to another location with a different name

If you want to use only FileInfo class try this

             string oldPath = @"C:\MyFolder\Myfile.xyz";
             string newpath = @"C:\NewFolder\";
             string newFileName = "new file name";
             FileInfo f1 = new FileInfo(oldPath);
           if(f1.Exists)
             {
                if(!Directory.Exists(newpath))
                {
                    Directory.CreateDirectory(newpath); 
                }
                 f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
             }

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

Violation Long running JavaScript task took xx ms

If you're using Chrome Canary (or Beta), just check the 'Hide Violations' option.

Hide Violations Checkbox in Chrome 56 Console

Show Image View from file path?

onLoadImage Full load

private void onLoadImage(final String imagePath) {
    ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size

    //ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
    com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));

    imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(final String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);

            progress2.setVisibility(View.VISIBLE);

            new Handler().post(new Runnable() {
                public void run() {
                    progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

                    // Picasso.with(getContext()).load(imagePath).into(imageView);
                    // Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);

                    Glide.with(getContext())
                            .load(imagePath)
                            .asBitmap()
                            .into(imageView);
                }
          });
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            // else { 
              Log.e("onLoadImage", "onLoadingComplete");
            //   progress2.setVisibility(View.INVISIBLE);
            // }
            // setLoagingCompileImage();
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadingFailed", imageUri);
            Log.e("onLoadingFailed", failReason.toString());
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadImage", "onLoadingCancelled");
        }
    });
}

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

How can I run dos2unix on an entire directory?

I think the simplest way is:

dos2unix $(find . -type f)

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica;  

also dosent work for me in Postgres 9.1. i use the two function described by bartolo-otrit with some modification. I modified the first function to make it work for me because the namespace or the schema must be present to identify the table correctly. The new code is :

CREATE OR REPLACE FUNCTION disable_triggers(a boolean, nsp character varying)
  RETURNS void AS
$BODY$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I.%I %s trigger all', nsp,r.relname, act); 
    end loop;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION disable_triggers(boolean, character varying)
  OWNER TO postgres;

then i simply do a select query for every schema :

SELECT disable_triggers(true,'public');
SELECT disable_triggers(true,'Adempiere');

How to convert float to varchar in SQL Server

this is the solution I ended up using in sqlserver 2012 (since all the other suggestions had the drawback of truncating fractional part or some other drawback).

declare @float float = 1000000000.1234;
select format(@float, N'#.##############################');

output:

1000000000.1234

this has the further advantage (in my case) to make thousands separator and localization easy:

select format(@float, N'#,##0.##########', 'de-DE');

output:

1.000.000.000,1234

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default

Visual Studio 2010 shortcut to find classes and methods?

try: ctrl + P

type: @

followed by the name of the class,method or variable name you search for.

Equivalent of Math.Min & Math.Max for Dates?

There is no overload for DateTime values, but you can get the long value Ticks that is what the values contain, compare them and then create a new DateTime value from the result:

new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))

(Note that the DateTime structure also contains a Kind property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)

Does Typescript support the ?. operator? (And, what's it called?)

Update: it is supported as of TypeScript 3.7 and called Optional chaining: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

I can't find any reference to it whatsoever in the TypeScript language specification.

As far as what to call this operator in CoffeeScript, it's called the existential operator (specifically, the "accessor variant" of the existential operator).

From CoffeeScript's documentation on Operators:

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined.

So, the accessor variant of the existential operator appears to be the proper way to refer to this operator; and TypeScript does not currently appear to support it (although others have expressed a desire for this functionality).

Creating a SearchView that looks like the material design guidelines

Here's my attempt at doing this:

Step 1: Create a style named SearchViewStyle

<style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
    <!-- Gets rid of the search icon -->
    <item name="searchIcon">@drawable/search</item>
    <!-- Gets rid of the "underline" in the text -->
    <item name="queryBackground">@null</item>
    <!-- Gets rid of the search icon when the SearchView is expanded -->
    <item name="searchHintIcon">@null</item>
    <!-- The hint text that appears when the user has not typed anything -->
    <item name="queryHint">@string/search_hint</item>
</style>

Step 2: Create a layout named simple_search_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SearchView
    android:layout_gravity="end"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    style="@style/SearchViewStyle"
    xmlns:android="http://schemas.android.com/apk/res/android" />  

Step 3: Create a menu item for this search view

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        app:actionLayout="@layout/simple_search_view_item"
        android:title="@string/search"
        android:icon="@drawable/search"
        app:showAsAction="always" />
</menu>  

Step 4: Inflate the menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_searchable_activity, menu);
    return true;
}  

Result:

enter image description here

The only thing I wasn't able to do was to make it fill the entire width of the Toolbar. If someone could help me do that then that'd be golden.

How to "comment-out" (add comment) in a batch/cmd?

This is an old topic and I'd like to add my understanding here to expand the knowledge of this interesting topic.

The key difference between REM and :: is:

REM is a command itself, while :: is NOT.

We can treat :: as a token that as soon as CMD parser encounters the first non-blank space in a line is this :: token, it will just skip the whole line and read next line. That's why REM should be followed by at least a blank space to be able to function as a comment for the line, while :: does not need any blank space behind it.

That REM is a command itself can be best understood from the following FOR syntax

The basic FOR syntax is as follows

FOR %v in (set) DO <Command> [command param] 

here <Command> can be any valid command So we can write the following valid command line as rem is a command

FOR %i in (1,2,3) DO rem echo %i

However, we CANNOT write the following line as :: is not a command

FOR %i in (1,2,3) DO :: echo %i

Downloading images with node.js

I ran into this problem some days ago, for a pure NodeJS answer I would suggest using Stream to merge the chunks together.

var http = require('http'),                                                
    Stream = require('stream').Transform,                                  
    fs = require('fs');                                                    

var url = 'http://www.google.com/images/srpr/logo11w.png';                    

http.request(url, function(response) {                                        
  var data = new Stream();                                                    

  response.on('data', function(chunk) {                                       
    data.push(chunk);                                                         
  });                                                                         

  response.on('end', function() {                                             
    fs.writeFileSync('image.png', data.read());                               
  });                                                                         
}).end();

The newest Node versions won't work well with binary strings, so merging chunks with strings is not a good idea when working with binary data.

*Just be careful when using 'data.read()', it will empty the stream for the next 'read()' operation. If you want to use it more than once, store it somewhere.

How do I clear my Jenkins/Hudson build history?

You could modify the project configuration temporarily to save only the last 1 build, reload the configuration (which should trash the old builds), then change the configuration setting again to your desired value.

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

Why are C++ inline functions in the header?

The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.

Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)

Java, return if trimmed String in List contains String

String search = "A";
for(String s : myList)
    if(s.contains(search)) return true;
return false;

This will iterate over each string in the list, and check if it contains the string you're looking for. If it's only spaces you want to trap for, you can do this:

String search = "A";
for(String s : myList)
    if(s.replaceAll(" ","").contains(search)) return true;
return false;

which will first replace spaces with empty strings before searching. Additionally, if you just want to trim the string first, you can do:

String search = "A";
for(String s : myList)
    if(s.trim().contains(search)) return true;
return false;

How to inflate one view with a layout

I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

HTML5 placeholder css padding

Remove line-height or set using padding...it's working in all browser

How to get textLabel of selected row in swift?

This will work:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!

LaTeX package for syntax highlighting of code in various languages

I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:

listing package

The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.

Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.

The following code

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

produces the following image:

enter image description here

minted package

The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with

python --version

and you can install pygments with

sudo apt-get install python-pygments

Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this

pdflatex -shell-escape yourfile.tex

If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.

The following code

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}{html}
    <!DOCTYPE html>
    <html>
       <head>
           <title>Hello</title>
       </head>

       <body>Hello</body>
    </html>
\end{minted}
\end{document}

produces the following image:

enter image description here

what is the difference between json and xml

They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:

JSON:

{
  "persons": [
    {
      "name": "Ford Prefect",
      "gender": "male"
    },
    {
      "name": "Arthur Dent",
      "gender": "male"
    },
    {
      "name": "Tricia McMillan",
      "gender": "female"
    }
  ]
}

XML:

<persons>
  <person>
    <name>Ford Prefect</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Arthur Dent</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Tricia McMillan</name>
    <gender>female</gender>
  </person>
</persons>

The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.

The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.

While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).

Showing which files have changed between two revisions

And if you are looking for changes only among certain file(s), then:

git diff branch1 branch2 -- myfile1.js myfile2.js

branch1 is optional and your current branch (the branch you are on) will be considered by default if branch1 is not provided. e.g:

git diff master -- controller/index.js

Get value from JToken that may not exist (best practices)

This takes care of nulls

var body = JObject.Parse("anyjsonString");

body?.SelectToken("path-string-prop")?.ToString();

body?.SelectToken("path-double-prop")?.ToObject<double>();

libclntsh.so.11.1: cannot open shared object file.

Possibly you want to specify PATH — and also ORACLE_HOME and LD_LIBRARY_PATH — so that cron(1) knows where to find binaries.
Read "5 Crontab environment" here.

How to use a findBy method with comparative criteria

I like to use such static methods:

$result = $purchases_repository->matching(
    Criteria::create()->where(
        Criteria::expr()->gt('prize', 200)
    )
);

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);

Angular ng-repeat add bootstrap row every 3 or 4 cols

Little bit modification in @alpar 's solution

<div data-ng-app="" data-ng-init="products=['A','B','C','D','E','F', 'G','H','I','J','K','L']" class="container">
    <div ng-repeat="product in products" ng-if="$index % 6 == 0" class="row">
        <div class="col-xs-2" ng-repeat="idx in [0,1,2,3,4,5]">
        {{products[idx+$parent.$index]}} <!-- When this HTML is Big it's useful approach -->
        </div>
    </div>
</div>

jsfiddle

Is an empty href valid?

it's valid but like UpTheCreek said 'There are some downsides to each approach'

if you're calling ajax through an tag leave the href="" like this will keep the page reloading and the ajax code will never be called ...

just got this thought would be good to share

Get the size of the screen, current web page and browser window

In some cases related with responsive layout $(document).height() can return wrong data that displays view port height only. For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use

$('#wrapper').get(0).scrollHeight

That represents actual size of wrapper.

javascript: using a condition in switch case

This works:

switch (true) {
    case liCount == 0:
        setLayoutState('start');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=5 && liCount>0:
        setLayoutState('upload1Row');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=10 && liCount>5:
        setLayoutState('upload2Rows');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount>10:
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;                  
}

A previous version of this answer considered the parentheses to be the culprit. In truth, the parentheses are irrelevant here - the only thing necessary is switch(true){...} and for your case expressions to evaluate to booleans.

It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..} and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.

Eg: if liCount is 3, the first comparison is true === (liCount == 0), meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0). This expression evaluates to true, meaning this case is run, and terminates at the break. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.

It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ... might introduce a lot of visual noise or fragility.

Use with caution, because it is a non-standard pattern, despite being valid code.

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

How to get the size of a JavaScript object?

Here's a slightly more compact solution to the problem:

const typeSizes = {
  "undefined": () => 0,
  "boolean": () => 4,
  "number": () => 8,
  "string": item => 2 * item.length,
  "object": item => !item ? 0 : Object
    .keys(item)
    .reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};

const sizeOf = value => typeSizes[typeof value](value);

How to quickly and conveniently create a one element arraylist

The other answers all use Arrays.asList(), which returns an unmodifiable list (an UnsupportedOperationException is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).

For example:

Lists.newArrayList("Blargle!");

Allowed memory size of 536870912 bytes exhausted in Laravel

For litespeed servers with lsphp*.* package.

Use following command to find out default set memory limit for PHP applications.

php -r "echo ini_get('memory_limit').PHP_EOL;"

To locate active php.ini file from CLI

php -i | grep php.ini

Example:

/usr/local/lsws/lsphp73/etc/php/7.3/litespeed/php.ini

To change php.ini default value to custom:

php_memory_limit=1024M #or what ever you want it set to
sed -i 's/memory_limit = .*/memory_limit = '${php_memory_limit}'/' /usr/local/lsws/lsphp73/etc/php/7.3/litespeed/php.ini

Dont forget to restart lsws with: systemctl restart lsws

While loop to test if a file exists in bash

do it like this

while true
do
  [ -f /tmp/list.txt ] && break
  sleep 2
done
ls -l /tmp/list.txt

How do you clone a Git repository into a specific folder?

There is a very easy option using Visual Studio Code:

  1. Install the GitLab workflow extension
  2. Hit Ctrl + Shift + P
  3. Enter the repository URL (that you copied from GitLab, GitHub, etc.)
  4. Choose local repository location on your computer

Excel formula to search if all cells in a range read "True", if not, then show "False"

=IF(COUNTIF(A1:D1,FALSE)>0,FALSE,TRUE)

(or you can specify any other range to look in)

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

Evaluate empty or null JSTL c tags

This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.

To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
        <c:if test="${not empty description}">
            <c:set var="description" value="${fn:replace(description, ' ', '')}" />
            <c:if test="${not empty description}">
                  The description is not blank.
            </c:if>
        </c:if>

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

Better you update your eclipse by clicking it on help >> check for updates, also you can start eclipse by entering command in command prompt eclipse -clean.
Hope this will help you.

Most Useful Attributes

For what it's worth, here's a list of all .NET attributes. There are several hundred.

I don't know about anyone else but I have some serious RTFM to do!

Call child component method from parent class - Angular

I think most easy way is using Subject. In bellow example code the child will be notified each time 'tellChild' is called.

Parent.component.ts

import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
    changingValue: Subject<boolean> = new Subject();
    tellChild(){
    this.changingValue.next(true);
  }
}

Parent.component.html

<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
  this.changing.subscribe(v => { 
     console.log('value is changing', v);
  });
}

Working sample on Stackblitz

How to get a password from a shell script without echoing

Here is another way to do it:

#!/bin/bash
# Read Password
echo -n Password: 
read -s password
echo
# Run Command
echo $password

The read -s will turn off echo for you. Just replace the echo on the last line with the command you want to run.

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

Run AVD Emulator without Android Studio

Assuming you have installed Android studio properly,Open a command prompt and type emulator -list-avds which will display all the devices and then type emulator @avd_name where avd_name is the the name of your emulator installed.

What is the most accurate way to retrieve a user's correct IP address in PHP?

Here is a shorter, cleaner way to get the IP address:

function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

Your code seems to be pretty complete already, I cannot see any possible bugs in it (aside from the usual IP caveats), I would change the validate_ip() function to rely on the filter extension though:

public function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this

    return true;
}

Also your HTTP_X_FORWARDED_FOR snippet can be simplified from this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    // check if multiple ips exist in var
    if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
    {
        $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
        foreach ($iplist as $ip)
        {
            if ($this->validate_ip($ip))
                return $ip;
        }
    }
    
    else
    {
        if ($this->validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
}

To this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
    foreach ($iplist as $ip)
    {
        if ($this->validate_ip($ip))
            return $ip;
    }
}

You may also want to validate IPv6 addresses.

How can I get CMake to find my alternative Boost installation?

There is a generic method to give CMake directions about where to find libraries.

When looking for a library, CMake looks first in the following variables:

  • CMAKE_LIBRARY_PATH and LD_LIBRARY_PATH for libraries
  • CMAKE_INCLUDE_PATH and INCLUDE_PATH for includes

If you declare your Boost files in one of the environment variables, CMake will find it. Example:

export CMAKE_LIBRARY_PATH="/stuff/lib.boost.1.52/lib:$CMAKE_LIBRARY_PATH"
export CMAKE_INCLUDE_PATH="/stuff/lib.boost.1.52/include:$CMAKE_INCLUDE_PATH"

If it's too cumbersome, you can also use a nice installing tool I wrote that will do everything for you: C++ version manager

How can I make space between two buttons in same div?

I used the Bootstrap 4 buttons plugin (https://getbootstrap.com/docs/4.0/components/buttons/#button-plugin) and added the class rounded to the labels and the class mx-1 to the middle button to achieve the desired look and feel of separate radio buttons. Using the class btn-toolbar made the radio button circles appear for me which is not what I wanted. Hope this helps someone.

        <div class="btn-group btn-group-toggle" data-toggle="buttons">
            <label class="btn btn-secondary active rounded">
                <input type="radio" name="options" id="option1" autocomplete="off" checked> Active
            </label>
            <label class="btn btn-secondary rounded mx-1">
                <input type="radio" name="options" id="option2" autocomplete="off"> Radio
            </label>
            <label class="btn btn-secondary rounded">
                <input type="radio" name="options" id="option3" autocomplete="off"> Radio
            </label>
        </div>

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

Set Canvas size using javascript

You can also use this script , just change the height and width

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

   <script>
      var canvas = document.getElementById("Canvas01");
      var ctx = canvas.getContext("2d");

How to check if a key exists in Json Object and get its value

Try

private boolean hasKey(JSONObject jsonObject, String key) {
    return jsonObject != null && jsonObject.has(key);
}

  try {
        JSONObject jsonObject = new JSONObject(yourJson);
        if (hasKey(jsonObject, "labelData")) {
            JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
            if (hasKey(labelDataJson, "video")) {
                String video = labelDataJson.getString("video");
            }
        }
    } catch (JSONException e) {

    }

Gradle, Android and the ANDROID_HOME SDK location

For Windows:

  1. Add ANDROID_HOME to the Environment Variables: ANDROID_HOME = C:/Users/YOUR_USERNAME/AppData/Local/Android/sdk
  2. Add %ANDROID_HOME%\platform-tools to the PATH.

'adb' is not recognized as an internal or external command, operable program or batch file

for me I was still getting

'adb' is not recognized as an internal or external command,
operable program or batch file. 

even after setting the path in environment variables...... restarting Android Studio solved the problem.

SQL Server Escape an Underscore

This worked for me, just use the escape '%\_%'

Count how many rows have the same value

SELECT SUM(IF(your_column=3,1,0)) FROM your_table WHERE your_where_contion='something';

e.g. for you query:-

SELECT SUM(IF(num=1,1,0)) FROM your_table_name;

If else on WHERE clause

IF is used to select the field, then the LIKE clause is placed after it:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE IF(`email` != '', `email`, `email2`) LIKE  '%@domain.nl%'

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

How to see docker image contents

There is a free open source tool called Anchore that you can use to scan container images. This command will allow you to list all files in a container image

anchore-cli image content myrepo/app:latest files

https://anchore.com/opensource/

Of Countries and their Cities

Check this out:

Cities of the world database donated by MaxMind.com

The company MaxMind.com1 has agreed to release their cities of the world database under the GPL. The database contains locations by country, city, latitude and longitude. There are over 3,047,000 records in the database. For those of you who have tried the location.module with the zipcodes database from CivicSpace, you will recognize how cool it is and how well this fits with that project and therefore Drupal.

Here's another free one that might help you get started.

Creating and maintaining such a database is quite a bit of work - so anyone who's done it is likely keeping it to themselves, or offering it for a fee.

link_to image tag. how to add class to a tag

hi you can try doing this

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}

or even

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'

note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)

and according to the api for link_to:

link_to(name, options = {}, html_options = nil)
  1. the first parameter is the string to be shown (or it can be an image_tag as well)
  2. the second is the parameter for the url of the link
  3. the last item is the optional parameter for declaring the html tag, e.g. class, onchange, etc.

hope it helps! =)

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

PHP json_decode() returns NULL with valid JSON?

For me, I had to turn off the error_reporting, to get json_decode() working correctly. It sounds weird, but true in my case. Because there is some notice printed between the JSON string that I am trying to decode.

CSS position absolute full width problem

You could set both left and right property to 0. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header is position: relative;)

#site_nav_global_primary {    
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}

Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative; from #header

How to customize the background color of a UITableViewCell?

This is really simple, since OS 3.0 just set the background color of the cell in the willDisplayCell method. You must not set the color in the cellForRowAtIndexPath.

This works for both the plain and grouped style :

Code:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor redColor];
}

P.S: Here the documentation extract for willDisplayCell :

"A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out."

I've found this information in this post from colionel. Thank him!

Android getResources().getDrawable() deprecated API 22

In Kotlin you can use extension

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

    return  ContextCompat.getDrawable(this, id)
}

then use like

context.getMyDrawable(R.drawable.my_icon)

round() for float in C++

Boost offers a simple set of rounding functions.

#include <boost/math/special_functions/round.hpp>

double a = boost::math::round(1.5); // Yields 2.0
int b = boost::math::iround(1.5); // Yields 2 as an integer

For more information, see the Boost documentation.

Edit: Since C++11, there are std::round, std::lround, and std::llround.

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

C# Switch-case string starting with

This is now possible with C# 7.0's pattern matching. For example:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

"Prevent saving changes that require the table to be re-created" negative effects

The table is only dropped and re-created in cases where that's the only way SQL Server's Management Studio has been programmed to know how to do it.

There are certainly cases where it will do that when it doesn't need to, but there will also be cases where edits you make in Management Studio will not drop and re-create because it doesn't have to.

The problem is that enumerating all of the cases and determining which side of the line they fall on will be quite tedious.

This is why I like to use ALTER TABLE in a query window, instead of visual designers that hide what they're doing (and quite frankly have bugs) - I know exactly what is going to happen, and I can prepare for cases where the only possibility is to drop and re-create the table (which is some number less than how often SSMS will do that to you).

Unresolved external symbol on static class members

Static data members declarations in the class declaration are not definition of them. To define them you should do this in the .CPP file to avoid duplicated symbols.

The only data you can declare and define is integral static constants. (Values of enums can be used as constant values as well)

You might want to rewrite your code as:

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}

.prop() vs .attr()

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

Further detail

If you change an attribute, the change will be reflected in the DOM (sometimes with a different name).

Example: Changing the class attribute of a tag will change the className property of that tag in the DOM. If you have no attribute on a tag, you still have the corresponding DOM property with an empty or a default value.

Example: While your tag has no class attribute, the DOM property className does exist with a empty string value.

edit

If you change the one, the other will be changed by a controller, and vice versa. This controller is not in jQuery, but in the browser's native code.

How to create a Custom Dialog box in android?

Add the below theme in values -> style.xml

<style name="Theme_Dialog" parent="android:Theme.Light">
     <item name="android:windowNoTitle">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
</style>

Use this theme in your onCreateDialog method like this:

Dialog dialog = new Dialog(FlightBookActivity.this,R.style.Theme_Dialog);

Define your dialog layout including title bar in the xml file and set that xml file like this:

dialog.setContentView(R.layout.your_dialog_layout);

How can I find the location of origin/master in git, and how do I change it?

I am struggling with this problem and none of the previous answers tackle the question as I see it. I have stripped the problem back down to its basics to see if I can make my problem clear.

I create a new repository (rep1), put one file in it and commit it.

mkdir rep1
cd rep1
git init
echo "Line1" > README
git add README
git commit -m "Commit 1"

I create a clone of rep1 and call it rep2. I look inside rep2 and see the file is correct.

cd ~
git clone ~/rep1 rep2
cat ~/rep2/README

In rep1 I make a single change to the file and commit it. Then in rep1 I create a remote to point to rep2 and push the changes.

cd ~/rep1
<change file and commit>
git remote add rep2 ~/rep2
git push rep2 master

Now when I go into rep2 and do a 'git status' I get told I am ahead of origin.

# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   README
#

README in rep2 is as it was originally, before the second commit. The only modifications I have done are to rep1 and all I wanted to do was push them out to rep2. What is it I am not grasping?

File Explorer in Android Studio

1- menu, "Tools" -> "Android" -> "DDMS (monitor included)" 2- Open the File Explorer tab.

Is < faster than <=?

TL;DR answer

For most combinations of architecture, compiler and language, < will not be faster than <=.

Full answer

Other answers have concentrated on x86 architecture, and I don't know the ARM architecture (which your example assembler seems to be) well enough to comment specifically on the code generated, but this is an example of a micro-optimisation which is very architecture specific, and is as likely to be an anti-optimisation as it is to be an optimisation.

As such, I would suggest that this sort of micro-optimisation is an example of cargo cult programming rather than best software engineering practice.

Counterexample

There are probably some architectures where this is an optimisation, but I know of at least one architecture where the opposite may be true. The venerable Transputer architecture only had machine code instructions for equal to and greater than or equal to, so all comparisons had to be built from these primitives.

Even then, in almost all cases, the compiler could order the evaluation instructions in such a way that in practice, no comparison had any advantage over any other. Worst case though, it might need to add a reverse instruction (REV) to swap the top two items on the operand stack. This was a single byte instruction which took a single cycle to run, so had the smallest overhead possible.

Summary

Whether or not a micro-optimisation like this is an optimisation or an anti-optimisation depends on the specific architecture you are using, so it is usually a bad idea to get into the habit of using architecture specific micro-optimisations, otherwise you might instinctively use one when it is inappropriate to do so, and it looks like this is exactly what the book you are reading is advocating.

Java - Check Not Null/Empty else assign default value

Sounds like you probably want a simple method like this:

public String getValueOrDefault(String value, String defaultValue) {
    return isNotNullOrEmpty(value) ? value : defaultValue;
}

Then:

String result = getValueOrDefault(System.getProperty("XYZ"), "default");

At this point, you don't need temp... you've effectively used the method parameter as a way of initializing the temporary variable.

If you really want temp and you don't want an extra method, you can do it in one statement, but I really wouldn't:

public class Test {
    public static void main(String[] args) {
        String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
        System.out.println("result: " + result);
        System.out.println("temp: " + temp);
    }

    private static boolean isNotNullOrEmpty(String str) {
        return str != null && !str.isEmpty();
    }
}

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

How to start a Process as administrator mode in C#

You probably need to set your application as an x64 app.

The IIS Snap In only works in 64 bit and doesn't work in 32 bit, and a process spawned from a 32 bit app seems to work to be a 32 bit process and the same goes for 64 bit apps.

Look at: Start process as 64 bit

Need table of key codes for android and presenter

The actual standard key-layout is found in /system/usr/keylayout/qwerty.kl within the Android running on the handset. And it is a generic keylayout also.

key 115   VOLUME_UP         WAKE
key 114   VOLUME_DOWN       WAKE

From the AOSP source it can be found in sdk/emulator/keymaps/qwerty.kl.

But bear in mind this, when the source gets compiled along with a device specific keylayout, that will override the standard layout instead so the mileage will vary depending on what the manufacturer has programmed into the keycode for the volume up/down buttons in your case!

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

"Parser Error Message: Could not load type" in Global.asax

I faced the problem in VS 2017 out of no where, took my whole day going through 100 of solutions any of these didnt work. I then took my whole solution and started it on different machine having VS 2017 installation.. IT FINALLY WORKED. Than reinstalled VS 2017 on the original one and it started running on that too. I strongly recommend you try your solution on a different machine before wasting much time to debug it, bcz it is a BUG in VS 2017 as it seemed for me, have reported same to VS TEAM. Hope this helps any one in grief. Cheers.

Display an image with Python

Your first suggestion works for me

from IPython.display import display, Image
display(Image(filename='path/to/image.jpg'))

How to set time zone of a java.util.Date?

This code was helpful in an app I'm working on:

    Instant date = null;
    Date sdf = null;
    String formatTemplate = "EEE MMM dd yyyy HH:mm:ss";
    try {
        SimpleDateFormat isoFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
        isoFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("US/Pacific")));
        sdf = isoFormat.parse(timeAtWhichToMakeAvailable);
        date = sdf.toInstant();

    } catch (Exception e) {
        System.out.println("did not parse: " + timeAtWhichToMakeAvailable);
    }

    LOGGER.info("timeAtWhichToMakeAvailable: " + timeAtWhichToMakeAvailable);
    LOGGER.info("sdf: " + sdf);
    LOGGER.info("parsed to: " + date);

ASP.NET email validator regex

We can use RegularExpressionValidator to validate email address format. You need to specify the regular expression in ValidationExpression property of RegularExpressionValidator. So it will look like

 <asp:RegularExpressionValidator ID="validateEmail"    
  runat="server" ErrorMessage="Invalid email."
  ControlToValidate="txtEmail" 
  ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />

Also in event handler of button or link you need to check !Page.IsValid. Check sample code here : sample code

Also if you don't want to use RegularExpressionValidator you can write simple validate method and in that method usinf RegEx class of System.Text.RegularExpressions namespace.

Check example:

example

Change Placeholder Text using jQuery

The plugin doesn't look very robust. If you call .placeholder() again, it creates a new Placeholder instance while events are still bound to the old one.

Looking at the code, it looks like you could do:

$("#serMemtb").attr("placeholder", "Type a name (Lastname, Firstname)").blur();

EDIT

placeholder is an HTML5 attribute, guess who's not supporting it?

Your plugin doesn't really seem to help you overcome the fact that IE doesn't support it, so while my solution works, your plugin doesn't. Why don't you find one that does.

Running a cron job on Linux every six hours

Please keep attention at this syntax:

* */6 * * *

This means 60 times (every minute) every 6 hours,

not

one time every 6 hours.

Reading entire html file to String?

I prefers using Guava :

import com.google.common.base.Charsets;
import com.google.common.io.Files;
File file = new File("/path/to/file", Charsets.UTF_8);
String content = Files.toString(file);

Counting repeated elements in an integer array

If you have values in a short set of possible values then you can use something like Counting Sort

If not you have to use another data structure like a Dictionary, in java a Map

int[] array
Map<Integer, Integer> 

where Key = array value for example array[i] and value = a counter

Example:

int[] array = new int [50];
Map<Integer,Integer> counterMap = new HashMap<>();

//fill the array

    for(int i=0;i<array.length;i++){
         if(counterMap.containsKey(array[i])){
          counterMap.put(array[i], counterMap.get(array[i])+1 );
         }else{
          counterMap.put(array[i], 1);
         }
    }

Convert column classes in data.table

Raising Matt Dowle's comment to Geneorama's answer (https://stackoverflow.com/a/20808945/4241780) to make it more obvious (as encouraged), you can use for(...)set(...).


library(data.table)

DT = data.table(a = LETTERS[c(3L,1:3)], b = 4:7, c = letters[1:4])
DT1 <- copy(DT)
names_factors <- c("a", "c")

for(col in names_factors)
  set(DT, j = col, value = as.factor(DT[[col]]))

sapply(DT, class)
#>         a         b         c 
#>  "factor" "integer"  "factor"

Created on 2020-02-12 by the reprex package (v0.3.0)

See another of Matt's comments at https://stackoverflow.com/a/33000778/4241780 for more info.

Edit.

As noted by Espen and in help(set), j may be "Column name(s) (character) or number(s) (integer) to be assigned value when column(s) already exist". So names_factors <- c(1L, 3L) will also work.

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

You can find out what library depends on a wrong version of the support library and exclude it like this:

compile ('com.stripe:stripe-android:5.1.1') {
    exclude group: 'com.android.support'
  }

stripe-android in my case.

Python Pandas - Find difference between two data frames

For rows, try this, where Name is the joint index column (can be a list for multiple common columns, or specify left_on and right_on):

m = df1.merge(df2, on='Name', how='outer', suffixes=['', '_'], indicator=True)

The indicator=True setting is useful as it adds a column called _merge, with all changes between df1 and df2, categorized into 3 possible kinds: "left_only", "right_only" or "both".

For columns, try this:

set(df1.columns).symmetric_difference(df2.columns)

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

Adding external library in Android studio

Try one of these approaches:

Approach 1)

1- Choose project view

enter image description here

2- Copy your JAR file in app -> lib folder

enter image description here

3- Right click on your JAR file and choose add as library

enter image description here enter image description here

4- Check it in build.gradle

enter image description here


Approach 2)

1- File -> New -> New Module

enter image description here

2- Import .JAR/.AAR Package

enter image description here

3- Browse your JAR File

enter image description here

4- Finish

5- File -> Project Structure -> Dependencies

enter image description here

6- You should click on + button and then click on Module Dependency

enter image description here

7- You will see your library here

enter image description here

8- choose your library and click ok

enter image description here

9- Then, you will see that your library is added.

enter image description here


For first two approaches, you need a JAR file. You can search http://search.maven.org/ to find JAR files that are related to Android. For example, this is the search result for jdom in this link

Search result for jdom


Approach 3) Android is using http://jcenter.bintray.com/ as remote library. For example, this is the search result for jdom in the link.

jcenter jdom

To add a library in this approach, please follow these steps:

1- File -> Project Structure -> Dependencies

enter image description here

2- Click on + button and choose library dependency

enter image description here enter image description here

3- find your library and select it, then click OK.


I hope it helps.

java.io.FileNotFoundException: the system cannot find the file specified

Your file should directly be under the project folder, and not inside any other sub-folder.

If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.

Aproject
        src
        word.txt

Windows batch file file download from a URL

Downloading files in PURE BATCH... Without any JScript, VBScript, Powershell, etc... Only pure Batch!

Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!

Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.

For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

Enjoy!


USAGE:

You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"

Proxy Server:
For connecting using a proxy, use this command before downloading.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

Click this LINK if you want more info about BITSadmin.exe


TROUBLESHOOTING:
If you get this error: "Unable to connect to BITS - 0x80070422"
Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)


CUSTOM FUNCTIONS
Call :DOWNLOAD_FILE "URL"
Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
Call :DOWNLOAD_PROXY_OFF

I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

PLEASE NOTE...
Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

:DOWNLOAD_FILE "URL"
The main function, will download files from URL.

:DOWNLOAD_PROXY_ON "SERVER:PORT"
(Optional) You can use this function if you need to use a proxy server.
Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

EXAMPLE:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"
CALL :DOWNLOAD_PROXY_OFF


CUSTOM_FUNCTIONS.CMD

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

DOWNLOAD-EXAMPLE.CMD

@ECHO OFF
SETLOCAL

rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.


:SETUP

rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"

rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"

rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"

:MAIN

ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO:  "%SAVING_TO%"
ECHO.

rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
 
rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF

:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.

:EXIT_SCRIPT
PAUSE
EXIT /B




rem FUNCTIONS SECTION


:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

How to call getClass() from a static method in Java?

Try something like this. It works for me. Logg (Class name)

    String level= "";

    Properties prop = new Properties();

    InputStream in =
            Logg.class.getResourceAsStream("resources\\config");

    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    level = prop.getProperty("Level");

Calling a particular PHP function on form submit

If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form you can do that as :

<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
       display();
} 
?>
</body>
</html>

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Run Python script at startup in Ubuntu

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

Cannot run Eclipse; JVM terminated. Exit code=13

I was using Eclipse Juno and I didn't remember if it was 32 or 64 bits. I installed Java 32 bits and that's why it failed. I then installed Java 64 bits and Eclipse Juno is working again.

I also removed any java or jre reference in my environment variables (PATH).

Length of string in bash

Using your example provided

#KISS (Keep it simple stupid)
size=${#myvar}
echo $size

How to calculate date difference in JavaScript?

If you are using moment.js then it is pretty simple to find date difference.

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

How to make Twitter bootstrap modal full screen

I've came up with a "responsive" solution for fullscreen modals:

Fullscreen Modals that can be enabled only on certain breakpoints. In this way the modal will display "normal" on wider (desktop) screens and fullscreen on smaller (tablet or mobile) screens, giving it the feeling of a native app.

Implemented for Bootstrap 3 and Bootstrap 4. Included by default in Bootstrap 5.


Bootstrap v5

Fullscreen modals are included by default in Bootstrap 5: https://getbootstrap.com/docs/5.0/components/modal/#fullscreen-modal


Bootstrap v4

The following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}
.modal .modal-dialog {
  width: 100%;
  max-width: none;
  height: 100%;
  margin: 0;
}
.modal .modal-content {
  height: 100%;
  border: 0;
  border-radius: 0;
}
.modal .modal-body {
  overflow-y: auto;
}

By including the scss code below, it generates the following classes that need to be added to the .modal element:

+---------------+---------+---------+---------+---------+---------+
|               |   xs    |   sm    |   md    |   lg    |   xl    | 
|               | <576px  | =576px  | =768px  | =992px  | =1200px |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen    |  100%   | default | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-sm |  100%   |  100%   | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-md |  100%   |  100%   |  100%   | default | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-lg |  100%   |  100%   |  100%   |  100%   | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-xl |  100%   |  100%   |  100%   |  100%   |  100%   |
+---------------+---------+---------+---------+---------+---------+

The scss code is:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    max-width: none;
    height: 100%;
    margin: 0;
  }

  .modal-content {
    height: 100%;
    border: 0;
    border-radius: 0;
  }

  .modal-body {
    overflow-y: auto;
  }

}

@each $breakpoint in map-keys($grid-breakpoints) {
  @include media-breakpoint-down($breakpoint) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    .modal-fullscreen#{$infix} {
      @include modal-fullscreen();
    }
  }
}

Demo on Codepen: https://codepen.io/andreivictor/full/MWYNPBV/


Bootstrap v3

Based on previous responses to this topic (@Chris J, @kkarli), the following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}

.modal .modal-dialog {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.modal .modal-content {
  height: auto;
  min-height: 100%;
  border: 0 none;
  border-radius: 0;
  box-shadow: none;
}

If you want to use responsive fullscreen modals, use the following classes that need to be added to .modal element:

  • .modal-fullscreen-md-down - the modal is fullscreen for screens smaller than 1200px.
  • .modal-fullscreen-sm-down - the modal is fullscreen for screens smaller than 922px.
  • .modal-fullscreen-xs-down - the modal is fullscreen for screen smaller than 768px.

Take a look at the following code:

/* Extra small devices (less than 768px) */
@media (max-width: 767px) {
  .modal-fullscreen-xs-down {
    padding: 0 !important;
  }
  .modal-fullscreen-xs-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-xs-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  } 
}

/* Small devices (less than 992px) */
@media (max-width: 991px) {
  .modal-fullscreen-sm-down {
    padding: 0 !important;
  }
  .modal-fullscreen-sm-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-sm-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

/* Medium devices (less than 1200px) */
@media (max-width: 1199px) {
  .modal-fullscreen-md-down {
    padding: 0 !important;
  }
  .modal-fullscreen-md-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-md-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

Demo is available on Codepen: https://codepen.io/andreivictor/full/KXNdoO.

Those who use Sass as a preprocessor can take advantage of the following mixin:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }

  .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }

}

Retrieving the output of subprocess.call()

I recently just figured out how to do this, and here's some example code from a current project of mine:

#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...

You now have the output of the command stored in the variable "output". "stdout = subprocess.PIPE" tells the class to create a file object named 'stdout' from within Popen. The communicate() method, from what I can tell, just acts as a convenient way to return a tuple of the output and the errors from the process you've run. Also, the process is run when instantiating Popen.

How would you do a "not in" query with LINQ?

I don't know if this will help you but..

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers    
    where !(from o in dc.Orders    
            select o.CustomerID)    
           .Contains(c.CustomerID)    
    select c;

foreach (var c in query) Console.WriteLine( c );

from The NOT IN clause in LINQ to SQL by Marco Russo

Remove IE10's "clear field" X button on certain inputs?

To hide arrows and cross in a "time" input :

#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
    -webkit-appearance: none;
    margin: 0;
}

Certificate has either expired or has been revoked

After all above step clean and Rebuild is also a factor.

jQuery click / toggle between two functions

I used this to create a toggle effect between two functions.

var x = false;
$(element).on('click', function(){
 if (!x){
  //function
  x = true;
 }
 else {
  //function
  x = false;
 }
});

ZIP Code (US Postal Code) validation

function isValidUSZip(sZip) {
   return /^\d{5}(-\d{4})?$/.test(sZip);
}

Formatting a double to two decimal places

The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :

 0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64) 

As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :

double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta


    public static double AddRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d+val));
    }
    public static double MulRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d*val));
    }

How to run VBScript from command line without Cscript/Wscript

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

Check the answer -> Here

And here is an example:

Converter.bat

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

How can I use jQuery in Greasemonkey?

If you are using chrome you have to opt for an alternative as Chromium does not support @require.

Source: The Chromium Project - User scripts

More details and alternatives on How can I use jQuery in Greasemonkey scripts in Google Chrome?

What is the purpose and use of **kwargs?

Here's a simple function that serves to explain the usage:

def print_wrap(arg1, *args, **kwargs):
    print(arg1)
    print(args)
    print(kwargs)
    print(arg1, *args, **kwargs)

Any arguments that are not specified in the function definition will be put in the args list, or the kwargs list, depending on whether they are keyword arguments or not:

>>> print_wrap('one', 'two', 'three', end='blah', sep='--')
one
('two', 'three')
{'end': 'blah', 'sep': '--'}
one--two--threeblah

If you add a keyword argument that never gets passed to a function, an error will be raised:

>>> print_wrap('blah', dead_arg='anything')
TypeError: 'dead_arg' is an invalid keyword argument for this function

How to get distinct values for non-key column fields in Laravel?

Though I am late to answer this, a better approach to get distinct records using Eloquent would be

$user_names = User::distinct()->get(['name']);

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

How to fix corrupt HDFS FIles

If you just want to get your HDFS back to normal state and don't worry much about the data, then

This will list the corrupt HDFS blocks:

hdfs fsck -list-corruptfileblocks

This will delete the corrupted HDFS blocks:

hdfs fsck / -delete

Note that, you might have to use sudo -u hdfs if you are not the sudo user (assuming "hdfs" is name of the sudo user)

How to copy Docker images from one host to another without using a repository

I assume you need to save couchdb-cartridge which has an image id of 7ebc8510bc2c:

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest              7ebc8510bc2c        17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest              7ebc8510bc2c        17 hours ago        1.102 GB
ubuntu                                 14.04               53bf7a53e890        3 days ago          221.3 MB

Save the archiveName image to a tar file. I will use the /media/sf_docker_vm/ to save the image.

stratos@Dev-PC:~$ docker save imageID > /media/sf_docker_vm/archiveName.tar

Copy the archiveName.tar file to your new Docker instance using whatever method works in your environment, for example FTP, SCP, etc.

Run the docker load command on your new Docker instance and specify the location of the image tar file.

stratos@Dev-PC:~$ docker load < /media/sf_docker_vm/archiveName.tar

Finally, run the docker images command to check that the image is now available.

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG        IMAGE ID         CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest     7ebc8510bc2c     17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest     bc8510bc2c       17 hours ago        1.102 GB
ubuntu                                 14.04      4d2eab1c0b9a     3 days ago          221.3 MB

Please find this detailed post.

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

How do I convert an integer to binary in JavaScript?

A solution i'd go with that's fine for 32-bits, is the code the end of this answer, which is from developer.mozilla.org(MDN), but with some lines added for A)formatting and B)checking that the number is in range.

Some suggested x.toString(2) which doesn't work for negatives, it just sticks a minus sign in there for them, which is no good.

Fernando mentioned a simple solution of (x>>>0).toString(2); which is fine for negatives, but has a slight issue when x is positive. It has the output starting with 1, which for positive numbers isn't proper 2s complement.

Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?

A solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. And one could accept sometimes having a 33bit number, or one could make sure that the number to convert is within range -(2^31)<=x<2^31-1. So the number is always 32bits. But rather than do that, you can go with this solution on mozilla.org

Patrick's answer and code is long and apparently works for 64-bit, but had a bug that a commenter found, and the commenter fixed patrick's bug, but patrick has some "magic number" in his code that he didn't comment about and has forgotten about and patrick no longer fully understands his own code / why it works.

Annan had some incorrect and unclear terminology but mentioned a solution by developer.mozilla.org https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators This works for 32-bit numbers.

The code is pretty compact, a function of three lines.

But I have added a regex to format the output in groups of 8 bits. Based on How to print a number with commas as thousands separators in JavaScript (I just amended it from grouping it in 3s right to left and adding commas, to grouping in 8s right to left, and adding spaces)

And, while mozilla made a comment about the size of nMask(the number fed in)..that it has to be in range, they didn't test for or throw an error when the number is out of range, so i've added that.

I'm not sure why they named their parameter 'nMask' but i'll leave that as is.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

_x000D_
_x000D_
function createBinaryString(nMask) {_x000D_
  // nMask must be between -2147483648 and 2147483647_x000D_
  if (nMask > 2**31-1) _x000D_
     throw "number too large. number shouldn't be > 2**31-1"; //added_x000D_
  if (nMask < -1*(2**31))_x000D_
     throw "number too far negative, number shouldn't be < 2**31" //added_x000D_
  for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32;_x000D_
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);_x000D_
  sMask=sMask.replace(/\B(?=(.{8})+(?!.))/g, " ") // added_x000D_
  return sMask;_x000D_
}_x000D_
_x000D_
_x000D_
console.log(createBinaryString(-1))    // "11111111 11111111 11111111 11111111"_x000D_
console.log(createBinaryString(1024))  // "00000000 00000000 00000100 00000000"_x000D_
console.log(createBinaryString(-2))    // "11111111 11111111 11111111 11111110"_x000D_
console.log(createBinaryString(-1024)) // "11111111 11111111 11111100 00000000"
_x000D_
_x000D_
_x000D_

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

How to create a directory and give permission in single command

Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.

Subtract two variables in Bash

For simple integer arithmetic, you can also use the builtin let command.

 ONE=1
 TWO=2
 let "THREE = $ONE + $TWO"
 echo $THREE
    3

For more info on let, look here.

Use 'import module' or 'from module import'?

To add to what people have said about from x import *: besides making it more difficult to tell where names came from, this throws off code checkers like Pylint. They will report those names as undefined variables.

When is a C++ destructor called?

  1. When you create an object with new, you are responsible for calling delete. When you create an object with make_shared, the resulting shared_ptr is responsible for keeping count and calling delete when the use count goes to zero.
  2. Going out of scope does mean leaving a block. This is when the destructor is called, assuming that the object was not allocated with new (i.e. it is a stack object).
  3. About the only time when you need to call a destructor explicitly is when you allocate the object with a placement new.

Request Permission for Camera and Library in iOS 10 - Info.plist

Info.plist

Limited Photos

<key>PHPhotoLibraryPreventAutomaticLimitedAccessAlert</key>
<true/>

Camera

<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) camera description.</string>

Photos

<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME)photos description.</string>

Save Photos

<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME) photos add description.</string>

Location

<key> NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) location description.</string>

Apple Music

<key>NSAppleMusicUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>

Calendar

<key>NSCalendarsUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>

Siri

<key>NSSiriUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>