Programs & Examples On #Rooted device

Rooting is the process of attaining privileged control (known as "root access") on a UNIX based device. A rooted device is one on which root access has been gained.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Why use armeabi-v7a code over armeabi code?

Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

Images can't contain alpha channels or transparencies

Extending Roman B. answer. This is still a problem, I was uploading a cordova app. my solution using mogrify:

brew install imagemagick
* navigate to `platforms/ios/<your_app_name>/Images.xcassets/AppIcon.appiconset`*
mogrify -alpha off *.png

Then archived and validated successfully.

HTML colspan in CSS

There is no colspan in css as far as I know, but there will be column-span for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div and span with table-like display like this.

This would be the HTML:

<div class="table">
  <div class="row">
    <span class="cell red first"></span>
    <span class="cell blue fill"></span>
    <span class="cell green last"></span>
  </div>
</div>
<div class="table">
  <div class="row">
    <span class="cell black"></span>
  </div>
</div>

And this would be the css:

  /* this is to reproduce table-like structure
     for the sake of table-less layout. */
  .table { display:table; table-layout:fixed; width:100px; }
  .row { display:table-row; height:10px; }
  .cell { display:table-cell; }

  /* this is where the colspan tricks works. */
  span { width:100%; }

  /* below is for visual recognition test purposes only. */
  .red { background:red; }
  .blue { background:blue; }
  .green { background:green; }
  .black { background:black; }

  /* this is the benefit of using table display, it is able 
     to set the width of it's child object to fill the rest of 
     the parent width as in table */
  .first { width: 20px; }
  .last { width: 30px; }
  .fill { width: 100%; }

The only reason to use this trick is to gain the benefit of table-layout behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.

But if you don't need to benefit from the table-layout behaviour, then durilai's answer would suit you enough.

Oracle SQL: Update a table with data from another table

Here seems to be an even better answer with 'in' clause that allows for multiple keys for the join:

update fp_active set STATE='E', 
   LAST_DATE_MAJ = sysdate where (client,code) in (select (client,code) from fp_detail
  where valid = 1) ...

The full example is here: http://forums.devshed.com/oracle-development-96/how-to-update-from-two-tables-195893.html - from web archive since link was dead.

The beef is in having the columns that you want to use as the key in parentheses in the where clause before 'in' and have the select statement with the same column names in parentheses. where (column1,column2) in ( select (column1,column2) from table where "the set I want" );

Add a linebreak in an HTML text area

Add a linefeed ("\n") to the output:

<textarea>Hello


Bybye</textarea>

Will have a newline in it.

How to save/restore serializable object to/from file?

I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.

Binary

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

XML

Requires the System.Xml assembly to be included in your project.

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Json

You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
        writer = new StreamWriter(filePath, append);
        writer.Write(contentsToWriteToFile);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Example

// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);

// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");

Regex: matching up to the first occurrence of a character

this is not a regex solution, but something simple enough for your problem description. Just split your string and get the first item from your array.

$str = "match everything until first ; blah ; blah end ";
$s = explode(";",$str,2);
print $s[0];

output

$ php test.php
match everything until first

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

How to enter a multi-line command

You can use a space followed by the grave accent (backtick):

Get-ChildItem -Recurse `
  -Filter *.jpg `
  | Select LastWriteTime

However, this is only ever necessary in such cases as shown above. Usually you get automatic line continuation when a command cannot syntactically be complete at that point. This includes starting a new pipeline element:

Get-ChildItem |
  Select Name,Length

will work without problems since after the | the command cannot be complete since it's missing another pipeline element. Also opening curly braces or any other kind of parentheses will allow line continuation directly:

$x=1..5
$x[
  0,3
] | % {
  "Number: $_"
}

Similar to the | a comma will also work in some contexts:

1,
2

Keep in mind, though, similar to JavaScript's Automatic Semicolon Insertion, there are some things that are similarly broken because the line break occurs at a point where it is preceded by a valid statement:

return
  5

will not work.

Finally, strings (in all varieties) may also extend beyond a single line:

'Foo
bar'

They include the line breaks within the string, then.

How to extract URL parameters from a URL with Ruby or Rails?

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

process.waitFor() never returns

You should try consume output and error in the same while

    private void runCMD(String CMD) throws IOException, InterruptedException {
    System.out.println("Standard output: " + CMD);
    Process process = Runtime.getRuntime().exec(CMD);

    // Get input streams
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String line = "";
    String newLineCharacter = System.getProperty("line.separator");

    boolean isOutReady = false;
    boolean isErrorReady = false;
    boolean isProcessAlive = false;

    boolean isErrorOut = true;
    boolean isErrorError = true;


    System.out.println("Read command ");
    while (process.isAlive()) {
        //Read the stdOut

        do {
            isOutReady = stdInput.ready();
            //System.out.println("OUT READY " + isOutReady);
            isErrorOut = true;
            isErrorError = true;

            if (isOutReady) {
                line = stdInput.readLine();
                isErrorOut = false;
                System.out.println("=====================================================================================" + line + newLineCharacter);
            }
            isErrorReady = stdError.ready();
            //System.out.println("ERROR READY " + isErrorReady);
            if (isErrorReady) {
                line = stdError.readLine();
                isErrorError = false;
                System.out.println("ERROR::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" + line + newLineCharacter);

            }
            isProcessAlive = process.isAlive();
            //System.out.println("Process Alive " + isProcessAlive);
            if (!isProcessAlive) {
                System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Process DIE " + line + newLineCharacter);
                line = null;
                isErrorError = false;
                process.waitFor(1000, TimeUnit.MILLISECONDS);
            }

        } while (line != null);

        //Nothing else to read, lets pause for a bit before trying again
        System.out.println("PROCESS WAIT FOR");
        process.waitFor(100, TimeUnit.MILLISECONDS);
    }
    System.out.println("Command finished");
}

How do I programmatically change file permissions?

simple java code  for change file permission in java  

   String path="D:\\file\\read.txt";
        File file=new File(path);
        if (file.exists()) {
            System.out.println("read="+file.canRead());
            System.out.println("write="+file.canWrite());
            System.out.println("Execute="+file.canExecute());
            file.setReadOnly();
        }     

Reference : how to change file permission in java

Iterating over all the keys of a map

Here's some easy way to get slice of the map-keys.

// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

// use `Keys` func
func main() {
    m := map[string]interface{}{
        "foo": 1,
        "bar": true,
        "baz": "baz",
    }
    fmt.Println(Keys(m)) // [foo bar baz]
}

Are there bookmarks in Visual Studio Code?

If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:

m {a-z A-Z} for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.

To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}. I don't think these bookmarks stay across different VSCode sessions though.

More vim shortcuts here.

Compare DATETIME and DATE ignoring time portion

Use the CAST to the new DATE data type in SQL Server 2008 to compare just the date portion:

IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)

Check if a given key already exists in a dictionary and increment it

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

The difference between sys.stdout.write and print?

print is just a thin wrapper that formats the inputs (modifiable, but by default with a space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something other than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).

In case of an error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

Laravel 5 PDOException Could Not Find Driver

sudo apt-get update

For Mysql Database

sudo apt-get install php-mysql

For PostgreSQL Database

sudo apt-get install php-pgsql

Than

php artisan migrate

Hibernate: hbm2ddl.auto=update in production?

No, it's unsafe.

Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates in production. Write your own patches, review them with DBA, test them, then apply them manually.

Theoretically, if hbm2ddl update worked in development, it should work in production too. But in reality, it's not always the case.

Even if it worked OK, it may be sub-optimal. DBAs are paid that much for a reason.

CSS – why doesn’t percentage height work?

Another option is to add style to div

<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
 //to be scrolled 
</div>

And it means that an element is positioned relative to the nearest positioned ancestor.

What is a Y-combinator?

A Y-Combinator is another name for a flux capacitor.

How to concatenate text from multiple rows into a single text string in SQL server?

   declare @phone varchar(max)='' 
   select @phone=@phone + mobileno +',' from  members
   select @phone

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

Get last key-value pair in PHP array

As the key is needed, the accepted solution doesn't work.

This:

end($array);
return array(key($array) => array_pop($array));

will return exactly as the example in the question.

How to make canvas responsive

You can have a responsive canvas in 3 short and simple steps:

  1. Remove the width and height attributes from your <canvas>.

    <canvas id="responsive-canvas"></canvas>
    
  2. Using CSS, set the width of your canvas to 100%.

    #responsive-canvas {
      width: 100%;
    }
    
  3. Using JavaScript, set the height to some ratio of the width.

    var canvas = document.getElementById('responsive-canvas');
    var heightRatio = 1.5;
    canvas.height = canvas.width * heightRatio;
    

How to label each equation in align environment?

Within the environment align from the package amsmath it is possible to combine the use of \label and \tag for each equation or line. For example, the code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}

produces:

screenshot of output

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

Copy output of a JavaScript variable to the clipboard

For general purposes of copying any text to the clipboard, I wrote the following function:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.

Check if table exists

Adding to Gaby's post, my jdbc getTables() for Oracle 10g requires all caps to work:

"employee" -> "EMPLOYEE"

Otherwise I would get an exception:

java.sql.SqlExcepcion exhausted resultset

(even though "employee" is in the schema)

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.

Converting double to string

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

How can I check if an argument is defined when starting/calling a batch file?

Get rid of the parentheses.

Sample batch file:

echo "%1"

if ("%1"=="") echo match1

if "%1"=="" echo match2

Output from running above script:

C:\>echo "" 
""

C:\>if ("" == "") echo match1 

C:\>if "" == "" echo match2 
match2

I think it is actually taking the parentheses to be part of the strings and they are being compared.

Illegal mix of collations MySQL Error

My user account did not have the permissions to alter the database and table, as suggested in this solution.

If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:

SET collation_connection = 'latin1_swedish_ci';

jquery remove "selected" attribute of option?

The question is asked in a misleading manner. "Removing the selected attribute" and "deselecting all options" are entirely different things.

To deselect all options in a documented, cross-browser manner use either

$("select").val([]);

or

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

OWIN Startup Class Missing

I ran into this problem after experimenting with SignalR and then removing it from the project. To resolve I had to delete the contents of the bin folder for the site on the remote server and then publish again.

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Error while inserting date - Incorrect date value:

I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.

My error message:

Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.

Get time in milliseconds using C#

I use the following class. I found it on the Internet once, postulated to be the best NOW().

/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
    private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    /// <summary>Get extra long current timestamp</summary>
    public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}

Source unknown.

Python subprocess/Popen with a modified environment

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

Variable not accessible when initialized outside function

To define a global variable which is based off a DOM element a few things must be checked. First, if the code is in the <head> section, then the DOM will not loaded on execution. In this case, an event handler must be placed in order to set the variable after the DOM has been loaded, like this:

var systemStatus;
window.onload = function(){ systemStatus = document.getElementById("system_status"); };

However, if this script is inline in the page as the DOM loads, then it can be done as long as the DOM element in question has loaded above where the script is located. This is because javascript executes synchronously. This would be valid:

<div id="system_status"></div>
<script type="text/javascript">
 var systemStatus = document.getElementById("system_status");
</script>

As a result of the latter example, most pages which run scripts in the body save them until the very end of the document. This will allow the page to load, and then the javascript to execute which in most cases causes a visually faster rendering of the DOM.

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

My problem was executing the command (npm audit fix all). I solved it when closing VSCODE and re-executed the command without problems.

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

Is there any difference between DECIMAL and NUMERIC in SQL Server?

This is what then SQL2003 standard (§6.1 Data Types) says about the two:

 <exact numeric type> ::=
    NUMERIC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DECIMAL [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DEC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | SMALLINT
  | INTEGER
  | INT
  | BIGINT

 ...

21) NUMERIC specifies the data type
    exact numeric, with the decimal
    precision and scale specified by the
    <precision> and <scale>.

22) DECIMAL specifies the data type
    exact numeric, with the decimal scale
    specified by the <scale> and the
    implementation-defined decimal
    precision equal to or greater than the
    value of the specified <precision>.

#ifdef replacement in the Swift language

In Swift projects created with Xcode Version 9.4.1, Swift 4.1

#if DEBUG
#endif

works by default because in the Preprocessor Macros DEBUG=1 has already been set by Xcode.

So you can use #if DEBUG "out of box".

By the way, how to use the condition compilation blocks in general is written in Apple's book The Swift Programming Language 4.1 (the section Compiler Control Statements) and how to write the compile flags and what is counterpart of the C macros in Swift is written in another Apple's book Using Swift with Cocoa and Objective C (in the section Preprocessor Directives)

Hope in future Apple will write the more detailed contents and the indexes for their books.

Remove a HTML tag but keep the innerHtml

$('b').contents().unwrap();

This selects all <b> elements, then uses .contents() to target the text content of the <b>, then .unwrap() to remove its parent <b> element.


For the greatest performance, always go native:

var b = document.getElementsByTagName('b');

while(b.length) {
    var parent = b[ 0 ].parentNode;
    while( b[ 0 ].firstChild ) {
        parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
    }
     parent.removeChild( b[ 0 ] );
}

This will be much faster than any jQuery solution provided here.

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

Python regex findall

you can replace your pattern with

regex = ur"\[P\]([\w\s]+)\[\/P\]"

How to redirect the output of the time command to a file in Linux?

Try

{ time sleep 1 ; } 2> time.txt

which combines the STDERR of "time" and your command into time.txt

Or use

{ time sleep 1 2> sleep.stderr ; } 2> time.txt

which puts STDERR from "sleep" into the file "sleep.stderr" and only STDERR from "time" goes into "time.txt"

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.

Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.

Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.

Write these down.

In a recent version of eclipse :

  • Go to Window -> Preferences -> General -> Network Connections=
  • Change the provider to "Manual"
  • Select the "HTTP" line and click the edit button
  • Add the IP address and port number above to the http line
  • If you have to authenticate to use the proxy,
    • select "Requires Authentication"
    • type in your username. Note that if your authentication is on a Windows domain, you might have to prepend the domain name and a backslash (\) like: MYDOMAIN\MYUSERID
    • Type in your password
  • Click OK
  • Click Apply
  • Click OK

At this point, you should be able to browse using the internal web browser (at least on http URLs).

Good luck.

Edit: Just so you know, it's WAY easier to use Nexus, one set of <mirror> tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.

Comparing chars in Java

Using Guava:

if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }

Or if many of those characters are a range, such as "A" to "U" but some aren't:

CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))

You can also declare this as a static final field so the matcher doesn't have to be created each time.

private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");

Convert string to decimal, keeping fractions

Here is a solution I came up with for myself. This is ready to run as a command prompt project. You need to clean some stuff if not. Hope this helps. It accepts several input formats like: 1.234.567,89 1,234,567.89 etc

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Globalization;
    using System.Linq;

    namespace ConvertStringDecimal
    {
        class Program
        {
            static void Main(string[] args)
            {
                while(true)
                {
                    // reads input number from keyboard
                    string input = Console.ReadLine();
                    double result = 0;
                    // remove empty spaces
                    input = input.Replace(" ", "");
                    // checks if the string is empty
                    if (string.IsNullOrEmpty(input) == false)
                    {
                        // check if input has , and . for thousands separator and decimal place
                        if (input.Contains(",") && input.Contains("."))
                        {
                            // find the decimal separator, might be , or .
                            int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
                            // uses | as a temporary decimal separator
                            input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
                            // formats the output removing the , and . and replacing the temporary | with .
                            input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
                        }
                        // replaces , with .
                        if (input.Contains(","))
                        {
                            input = input.Replace(',', '.');
                        }
                        // checks if the input number has thousands separator and no decimal places
                        if(input.Count(item => item == '.') > 1)
                        {
                            input = input.Replace(".", "");
                        }
                        // tries to convert input to double
                        if (double.TryParse(input, out result) == true)
                        {
                            result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
                        }
                    }
                    // outputs the result
                    Console.WriteLine(result.ToString());
                    Console.WriteLine("----------------");
                }
            }
        }
    }

How do I get the last character of a string using an Excel function?

=RIGHT(A1)  

is quite sufficient (where the string is contained in A1).

Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:

SYNTAX

RIGHT( text, [number_of_characters] )

Parameters or Arguments

text

The string that you wish to extract from.

number_of_characters

Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.

Applies To

Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Since number_of_characters is optional and defaults to 1 it is not required in this case.

However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):

=RIGHT(TRIM(A1))  

might be preferred.

Making a Simple Ajax call to controller in asp.net mvc

instead of url: serviceURL, use

url: '<%= serviceURL%>',

and are you passing 2 parameters to successFunc?

function successFunc(data)
 {
   alert(data);
 }

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

How do I run a program with commandline arguments using GDB within a Bash script?

Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args parameter), is to compile normally, and use r arg1 arg2 arg3 directly from within gdb, like so:

$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3

Laravel orderBy on a relationship

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

How do I import the javax.servlet API in my Eclipse project?

From wikipedia.

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
                "Transitional//EN\">\n" +
                "<html>\n" +
                "<head><title>Hello WWW</title></head>\n" +
                "<body>\n" +
                "<h1>Hello WWW</h1>\n" +
                "</body></html>");
  }
}

This, of course, works only if you have added the servlet-api.jar to Eclipse build path. Typically your application server (e.g Tomcat) will have the right jar file.

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

Html.HiddenFor value property not getting set

Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Using Font Awesome icon for bullet points, with a single list item element

There's an example of how to use Font Awesome alongside an unordered list on their examples page.

<ul class="icons">
  <li><i class="icon-ok"></i> Lists</li>
  <li><i class="icon-ok"></i> Buttons</li>
  <li><i class="icon-ok"></i> Button groups</li>
  <li><i class="icon-ok"></i> Navigation</li>
  <li><i class="icon-ok"></i> Prepended form inputs</li>
</ul>

If you can't find it working after trying this code then you're not including the library correctly. According to their website, you should include the libraries as such:

<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/font-awesome.css">

Also check out the whimsical Chris Coyier's post on icon fonts on his website CSS Tricks.

Here's a screencast by him as well talking about how to create your own icon font-face.

how to download file in react js

Solution (Work Perfect for React JS, Next JS)

You can use js-file-download and this is my example:

import axios from 'axios'
import fileDownload from 'js-file-download'
 
...

handleDownload = (url, filename) => {
  axios.get(url, {
    responseType: 'blob',
  })
  .then((res) => {
    fileDownload(res.data, filename)
  })
}
 
...

<button onClick={() => {this.handleDownload('https://your-website.com/your-image.jpg', 'test-download.jpg')
}}>Download Image</button>

This plugin can download excel and other file types.

How do I clear inner HTML

The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah), it works just fine:

Live: Version using clear which fails | Version using blah which works

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
    function go(what) {
        document.getElementById("goy").innerHTML = what;
    }
    function blah() {
        document.getElementById("goy").innerHTML = "";
    }
    </script>
</body>
</html>

This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.

A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 id="the-header">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
      // Scoping function makes the declarations within
      // it *not* globals
      (function(){
        var header = document.getElementById("the-header");
        header.onmouseover = function() {
          go('The dog is in its shed');
        };
        header.onmouseout = clear;

        function go(what) {
          document.getElementById("goy").innerHTML = what;
        }
        function clear() {
          document.getElementById("goy").innerHTML = "";
        }
      })();
    </script>
</body>
</html>

...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.

Iterate through dictionary values?

If all your values are unique, you can make a reverse dictionary:

PIXO_reverse = {v: k for k, v in PIX0.items()}

Result:

>>> PIXO_reverse

{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}

Now you can use the same logic as before.

Difference between Activity Context and Application Context

This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context. In the second place, the doc should specify which context to use or not explicitly.

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

That's a tricky one... Your storage letter must be capical. For example "C:\..."

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

For the iOS9, Apple made a radical decision with iOS 9, disabling all unsecured HTTP traffic from iOS apps, as a part of App Transport Security (ATS).

To simply disable ATS, you can follow this steps by open Info.plist, and add the following lines:

<key>NSAppTransportSecurity</key>
  <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
  </dict>

How do I switch between command and insert mode in Vim?

You can use Alt+H,J,K,L to move cursor in insert mode.

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I did try giving access to the folders but that did not help. My solution was to make the below highlighted options in red selected for the logged in user

This is what you see when you right click and select the username you have logged in for windows authentication mode.

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

Calculate percentage Javascript

You can use this

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 

Example to calculate the percentage of a course progress base in their activities.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

document.createElement("script") synchronously

This isn't pretty, but it works:

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
</script>

<script type="text/javascript">
  functionFromOther();
</script>

Or

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
  window.onload = function() {
    functionFromOther();
  };
</script>

The script must be included either in a separate <script> tag or before window.onload().

This will not work:

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
  functionFromOther(); // Error
</script>

The same can be done with creating a node, as Pointy did, but only in FF. You have no guarantee when the script will be ready in other browsers.

Being an XML Purist I really hate this. But it does work predictably. You could easily wrap those ugly document.write()s so you don't have to look at them. You could even do tests and create a node and append it then fall back on document.write().

how to call a onclick function in <a> tag?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.

Example:

function newwin() {              
 myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}

See how to call it from your anchor tag

<a onclick='newwin()'>Anchor</a>

Update

Visit this jsbin

http://jsbin.com/icUTUjI/1/edit

May be this will help you a lot to understand your problem.

ng-if, not equal to?

Try this:

ng-if="details.Payment[0].Status != '6'".

Sorry about that, but I think you can use ng-show or ng-hide.

How do I sort a VARCHAR column in SQL server that contains numbers?

I solved it in a very simple way writing this in the "order" part

ORDER BY (
sr.codice +0
)
ASC

This seems to work very well, in fact I had the following sorting:

16079   Customer X 
016082  Customer Y
16413   Customer Z

So the 0 in front of 16082 is considered correctly.

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

How to find keys of a hash?

For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure Object.keys in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty feature.

As of ECMAScript 5 - Object.defineProperty

As of ECMA5 you can use Object.defineProperty() to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    var keys = [];
    for(var i in this) if (this.hasOwnProperty(i)) {
      keys.push(i);
    }
    return keys;
  },
  enumerable: false
});

var o = {
    'a': 1,
    'b': 2
}

for (var k in o) {
    console.log(k, o[k])
}

console.log(o.keys())

# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]

However, since ECMA5 already added Object.keys you might as well use:

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    return Object.keys(this);
  },
  enumerable: false
});

Original answer

Object.prototype.keys = function ()
{
  var keys = [];
  for(var i in this) if (this.hasOwnProperty(i))
  {
    keys.push(i);
  }
  return keys;
}

Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.

There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.

Deleting folders in python recursively

For Linux users, you can simply run the shell command in a pythonic way

import os
os.system("rm -r /home/user/folder1  /home/user/folder2  ...")

If facing any issue then instead of rm -r use rm -rf but remember f will delete the directory forcefully.

Where rm stands for remove, -r for recursively and -rf for recursively + forcefully.

Note: It doesn't matter either the directories are empty or not, they'll get deleted.

Node.js - EJS - including a partial

Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.

No shadow by default on Toolbar?

My problem is that the toolbar does not cast any shadow if I don't set the "elevation" attribute. Is that the normal behavior or I'm doing something wrong?

That's the normal behavior. Also see the FAQ at the end of this post.

Kotlin Android start new Activity

Remember to add the activity you want to present, to your AndroidManifest.xml too :-) That was the issue for me.

CSS body background image fixed to full screen even when zooming in/out

Here is the simple code for full page background image when zooming you just apply the width:100% in style/css thats it

position:absolute; width:100%;

How to wait for 2 seconds?

How about this?

WAITFOR DELAY '00:00:02';

If you have "00:02" it's interpreting that as Hours:Minutes.

./xx.py: line 1: import: command not found

Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:

#!/usr/bin/python

Underneath which you would have the rest of the code (xx.py in your case) that you already have. Then run that same command at the terminal:

$ python xx.py

This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.

Cannot use object of type stdClass as array?

instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB:

class DB {
private static $_instance = null;
private $_pdo,
        $_query, 
        $_error = false,
        $_results,
        $_count = 0;



private function __construct() {
    try{
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );


    } catch(PDOException $e) {
        $this->_error = true;
        $newsMessage = 'Sorry.  Database is off line';
        $pagetitle = 'Teknikal Tim - Database Error';
        $pagedescription = 'Teknikal Tim Database Error page';
        include_once 'dbdown.html.php';
        exit;
    }
    $headerinc = 'header.html.php';
}

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }

    return self::$_instance;

}


    public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
    $x = 1;
        if(count($params)) {
        foreach($params as $param){
            $this->_query->bindValue($x, $param);
            $x++;
            }
        }
    }
    if($this->_query->execute()) {

        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
        $this->_count = $this->_query->rowCount();

    }

    else{
        $this->_error = true;
    }

    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) ===3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} = ?";

            if(!$this->query($sql, array($value))->error()) {
            return $this;
            }
        }

    }
    return false;
}

    public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

public function results() {
    return $this->_results;
}

public function first() {
    return $this->_results[0];
}

public function count() {
    return $this->_count;
}

}

to access the information I use this code on the controller script:

<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';

$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID',
 '=','$_SESSION['UserID']));

if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';



?>

then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it's not an array I am referencing so I access the records with the object operator "->" like this:

<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from the
  header -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article>
    <h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){
     foreach ($servicecalls as $servicecall) {
        echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'
  .$servicecall->ServiceCallDescription .'</a>';
    }
}else echo 'No service Calls';

}

?>
<a href="/servicecalls/?new=true">Raise New Service Call</a>
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>

How to change a TextView's style at runtime

See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html

To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

Setting the filter to an OpenFileDialog to allow the typical image formats?

In order to match a list of different categories of file, you can use the filter like this:

        var dlg = new Microsoft.Win32.OpenFileDialog()
        {
            DefaultExt = ".xlsx",
            Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx|CSV Files (*.csv)|*.csv"
        };

php timeout - set_time_limit(0); - don't work

Check the php.ini

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

ini_set('max_execution_time', 0); //0=NOLIMIT

Using app.config in .Net Core

I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.

Breaking this down to a simple answer for .Net core 3.1:

  • add/ensure nuget package: System.Configuration.ConfigurationManager to project
  • add your app.config(xml) to project.

If it is a MSTest project:

  • rename file in project to testhost.dll.config

    OR

  • Use post-build command provided by DeepSpace101

npm can't find package.json

Thank you! I also tried many options for this. I am also using windows.This command helped and saved my time:

npm install -g npm@lts

matplotlib savefig in jpeg format

You can save an image as 'png' and use the python imaging library (PIL) to convert this file to 'jpg':

import Image
import matplotlib.pyplot as plt

plt.plot(range(10))
plt.savefig('testplot.png')
Image.open('testplot.png').save('testplot.jpg','JPEG')

The original:

enter image description here

The JPEG image:

enter image description here

How to configure custom PYTHONPATH with VM and PyCharm?

In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.

Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.

See e.g. this SO question for more details on .pth files....

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

For Xiaomi mobile

1.Setting=>About phone=>tap 7 times on MIUI version


2.Setting=>Developer options=> Developer options (ON)

                            => USB Debugging (ON)

                            => Install via USB(ON)

Install via USB

if

enable to ON then

Disable WiFi and switch install via USB on while you are connected through mobile data and under your xiaomi account. It works!

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I was getting the same error in python 3.4.3 too and I tried using the solutions mentioned here and elsewhere with no success.

Microsoft makes a compiler available for Python 2.7 but it didn't do me much good since I am on 3.4.3.

Python since 3.3 has transitioned over to 2010 and you can download and install Visual C++ 2010 Express for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express

Here is the official blog post talking about the transition to 2010 for 3.3: http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html

Because previous versions gave a different error for vcvarsall.bat I would double check the version you are using with "pip -V"

C:\Users\B>pip -V
pip 6.0.8 from C:\Python34\lib\site-packages (python 3.4)

As a side note, I too tried using the latest version of VC++ (2013) first but it required installing 2010 express.

From that point forward it should work for anyone using the 32 bit version, if you are on the 64 bit version you will then get the ValueError: ['path'] message because VC++ 2010 doesn't have a 64 bit compuler. For that you have to get the Microsoft SDK 7.1. I can't hyperlink the instruction for 64 bit because I am limited to 2 links per post but its at

Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

How do I initialize a byte array in Java?

private static final int[] CDRIVES = new int[] {0xe0, 0xf4, ...};

and after access convert to byte.

What's the fastest algorithm for sorting a linked list?

Depending on a number of factors, it may actually be faster to copy the list to an array and then use a Quicksort.

The reason this might be faster is that an array has much better cache performance than a linked list. If the nodes in the list are dispersed in memory, you may be generating cache misses all over the place. Then again, if the array is large you will get cache misses anyway.

Mergesort parallelises better, so it may be a better choice if that is what you want. It is also much faster if you perform it directly on the linked list.

Since both algorithms run in O(n * log n), making an informed decision would involve profiling them both on the machine you would like to run them on.

--- EDIT

I decided to test my hypothesis and wrote a C-program which measured the time (using clock()) taken to sort a linked list of ints. I tried with a linked list where each node was allocated with malloc() and a linked list where the nodes were laid out linearly in an array, so the cache performance would be better. I compared these with the built-in qsort, which included copying everything from a fragmented list to an array and copying the result back again. Each algorithm was run on the same 10 data sets and the results were averaged.

These are the results:

N = 1000:

Fragmented list with merge sort: 0.000000 seconds

Array with qsort: 0.000000 seconds

Packed list with merge sort: 0.000000 seconds

N = 100000:

Fragmented list with merge sort: 0.039000 seconds

Array with qsort: 0.025000 seconds

Packed list with merge sort: 0.009000 seconds

N = 1000000:

Fragmented list with merge sort: 1.162000 seconds

Array with qsort: 0.420000 seconds

Packed list with merge sort: 0.112000 seconds

N = 100000000:

Fragmented list with merge sort: 364.797000 seconds

Array with qsort: 61.166000 seconds

Packed list with merge sort: 16.525000 seconds

Conclusion:

At least on my machine, copying into an array is well worth it to improve the cache performance, since you rarely have a completely packed linked list in real life. It should be noted that my machine has a 2.8GHz Phenom II, but only 0.6GHz RAM, so the cache is very important.

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable. It uses the Trim function to remove both types of spaces and means before and after spaces of string.

SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

How to simulate a click with JavaScript?

The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'.

So, I changed the document.createEvent to 'MouseEvents' and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('MouseEvents');
    evObj.initEvent(etype, true, false);
    var canceled = !el.dispatchEvent(evObj);
    if (canceled) {
      // A handler called preventDefault.
      console.log("automatic click canceled");
    } else {
      // None of the handlers called preventDefault.
    } 
  }
}

Create a temporary table in a SELECT statement without a separate CREATE TABLE

CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)

From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

You should add dataType: "html" to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)

instead.

How to apply box-shadow on all four sides?

Just simple as this code:

box-shadow: 0px 0px 2px 2px black; /*any color you want*/

How do you properly use namespaces in C++?

Namespaces are packages essentially. They can be used like this:

namespace MyNamespace
{
  class MyClass
  {
  };
}

Then in code:

MyNamespace::MyClass* pClass = new MyNamespace::MyClass();

Or, if you want to always use a specific namespace, you can do this:

using namespace MyNamespace;

MyClass* pClass = new MyClass();

Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).

And as you asked below, you can use as many namespaces as you like.

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

Git branching: master vs. origin/master vs. remotes/origin/master

I would try to make @ErichBSchulz's answer simpler for beginners:

  • origin/master is the state of master branch on remote repository
  • master is the state of master branch on local repository

How to stop BackgroundWorker correctly

I agree with guys. But sometimes you have to add more things.

IE

1) Add this worker.WorkerSupportsCancellation = true;

2) Add to you class some method to do the following things

public void KillMe()
{
   worker.CancelAsync();
   worker.Dispose();
   worker = null;
   GC.Collect();
}

So before close your application your have to call this method.

3) Probably you can Dispose, null all variables and timers which are inside of the BackgroundWorker.

How can I show an image using the ImageView component in javafx and fxml?

It's recommended to put the image to the resources, than you can use it like this:

imageView = new ImageView("/gui.img/img.jpg");

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.

OR

b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on php.net

Add line break within tooltips

Just add this code snippet in your script:

    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });

and ofcourse as mentioned in above answers the data-html should be "true". This will allow you to use html tags and formatting inside the value of title attribute.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

force browsers to get latest js and css files in asp.net application

For ASP.NET pages I am using the following

BEFORE

<script src="/Scripts/pages/common.js" type="text/javascript"></script>

AFTER (force reload)

 <script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

Adding the DateTime.Now.Ticks works very well.

How to make a local variable (inside a function) global

If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:

class StatefulFunction( object ):
    def __init__( self ):
        self.public_value = 'foo'

    def __call__( self ):
        return self.public_value


>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

BEGIN and END have been well answered by others.

As Gary points out, GO is a batch separator, used by most of the Microsoft supplied client tools, such as isql, sqlcmd, query analyzer and SQL Server Management studio. (At least some of the tools allow the batch separator to be changed. I have never seen a use for changing the batch separator.)

To answer the question of when to use GO, one needs to know when the SQL must be separated into batches.

Some statements must be the first statement of a batch.

select 1
create procedure #Zero as
    return 0

On SQL Server 2000 the error is:

Msg 111, Level 15, State 1, Line 3
'CREATE PROCEDURE' must be the first statement in a query batch.
Msg 178, Level 15, State 1, Line 4
A RETURN statement with a return value cannot be used in this context.

On SQL Server 2005 the error is less helpful:

Msg 178, Level 15, State 1, Procedure #Zero, Line 5
A RETURN statement with a return value cannot be used in this context.

So, use GO to separate statements that have to be the start of a batch from the statements that precede it in a script.

When running a script, many errors will cause execution of the batch to stop, but then the client will simply send the next batch, execution of the script will not stop. I often use this in testing. I will start the script with begin transaction and end with rollback, doing all the testing in the middle:

begin transaction
go
... test code here ...
go
rollback transaction

That way I always return to the starting state, even if an error happened in the test code, the begin and rollback transaction statements being part of a separate batches still happens. If they weren't in separate batches, then a syntax error would keep begin transaction from happening, since a batch is parsed as a unit. And a runtime error would keep the rollback from happening.

Also, if you are doing an install script, and have several batches in one file, an error in one batch will not keep the script from continuing to run, which may leave a mess. (Always backup before installing.)

Related to what Dave Markel pointed out, there are cases when parsing will fail because SQL Server is looking in the data dictionary for objects that are created earlier in the batch, but parsing can happen before any statements are run. Sometimes this is an issue, sometimes not. I can't come up with a good example. But if you ever get an 'X does not exist' error, when it plainly will exist by that statement break into batches.

And a final note. Transaction can span batches. (See above.) Variables do not span batches.

declare @i int
set @i = 0
go
print @i

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".

SQL: How to get the id of values I just INSERTed?

Again no language agnostic response, but in Java it goes like this:

Connection conn = Database.getCurrent().getConnection();  
PreparedStatement ps =  conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
try {  
    ps.executeUpdate();  
    ResultSet rs = ps.getGeneratedKeys();  
    rs.next();  
    long primaryKey = rs.getLong(1);  
} finally {  
    ps.close();  
}  

PostgreSQL function for last inserted ID

You can use RETURNING id after insert query.

INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;

and result:

 id 
----
  1

In the above example id is auto-increment filed.

HTML input field hint

I think for your situation, the easy and simple for your html input , you can probably add the attribute title

<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">

get the titles of all open windows

Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows function:

public class InfoWindow
{
            public IntPtr Handle = IntPtr.Zero;
            public FileInfo File = new FileInfo( Application.ExecutablePath );
            public string Title = Application.ProductName;
            public override string ToString() {
                return  File.Name + "\t>\t" + Title;
            }
 }//CLASS

/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{   
            internal static event EventHandler WindowActivatedChanged;    
            internal static Timer TimerWatcher = new Timer();    
            internal static InfoWindow WindowActive = new InfoWindow();       
            internal static void DoStartWatcher() {
                TimerWatcher.Interval = 500;
                TimerWatcher.Tick += TimerWatcher_Tick;
                TimerWatcher.Start();    
            }                    

            /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
            /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
            public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
            {
                IntPtr shellWindow = GetShellWindow();
                Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();

                EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
                    if ( hWnd == shellWindow ) return true;
                    if ( !IsWindowVisible( hWnd ) ) return true;    
                    int length = GetWindowTextLength( hWnd );
                    if ( length == 0 ) return true;    
                    StringBuilder builder = new StringBuilder( length );
                    GetWindowText( hWnd , builder , length + 1 );    
                    var info = new InfoWindow();
                    info.Handle = hWnd;
                    info.File = new FileInfo( GetProcessPath( hWnd ) );
                    info.Title = builder.ToString();    
                    windows[hWnd] = info;
                    return true;    
                } ) , 0 );    
                return windows;
            }

            private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );  

            public static string GetProcessPath( IntPtr hwnd )
            {
                uint pid = 0;
                GetWindowThreadProcessId( hwnd , out pid );
                if ( hwnd != IntPtr.Zero ) {
                    if ( pid != 0 ) {
                        var process = Process.GetProcessById( (int) pid );
                        if ( process != null ) {
                            return process.MainModule.FileName.ToString();
                        }
                    }
                }
                return "";
            }    

            [DllImport( "USER32.DLL" )]
            private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowTextLength( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern bool IsWindowVisible( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern IntPtr GetShellWindow();

            [DllImport( "user32.dll" )]
            private static extern IntPtr GetForegroundWindow();

            //WARN: Only for "Any CPU":
            [DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
            private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );    


            static void TimerWatcher_Tick( object sender , EventArgs e )
            {
                var windowActive = new InfoWindow();
                windowActive.Handle = GetForegroundWindow();
                string path = GetProcessPath( windowActive.Handle );
                if ( string.IsNullOrEmpty( path ) ) return;
                windowActive.File = new FileInfo( path );
                int length = GetWindowTextLength( windowActive.Handle );
                if ( length == 0 ) return;
                StringBuilder builder = new StringBuilder( length );
                GetWindowText( windowActive.Handle , builder , length + 1 );
                windowActive.Title = builder.ToString();
                if ( windowActive.ToString() != WindowActive.ToString() ) {
                    //fire:
                    WindowActive = windowActive;
                    if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
                    Console.WriteLine( "Window: " + WindowActive.ToString() );
                }
            }

}//CLASS

Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...

Print Pdf in C#

You can create the PDF document using PdfSharp. It is an open source .NET library.

When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.

I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.

var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = @"C:\Test.pdf" };
doc.Print();

That just prints to the default printer without showing. There are several alternatives and options.

What is the difference between an expression and a statement in Python?

Though this isn't related to Python:

An expression evaluates to a value. A statement does something.

>>> x + 2         # an expression
>>> x = 1         # a statement 
>>> y = x + 1     # a statement
>>> print y       # a statement (in 2.x)
2

How to debug a bash script?

sh -x script [arg1 ...]
bash -x script [arg1 ...]

These give you a trace of what is being executed. (See also 'Clarification' near the bottom of the answer.)

Sometimes, you need to control the debugging within the script. In that case, as Cheeto reminded me, you can use:

set -x

This turns debugging on. You can then turn it off again with:

set +x

(You can find out the current tracing state by analyzing $-, the current flags, for x.)

Also, shells generally provide options '-n' for 'no execution' and '-v' for 'verbose' mode; you can use these in combination to see whether the shell thinks it could execute your script — occasionally useful if you have an unbalanced quote somewhere.


There is contention that the '-x' option in Bash is different from other shells (see the comments). The Bash Manual says:

  • -x

    Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

That much does not seem to indicate different behaviour at all. I don't see any other relevant references to '-x' in the manual. It does not describe differences in the startup sequence.

Clarification: On systems such as a typical Linux box, where '/bin/sh' is a symlink to '/bin/bash' (or wherever the Bash executable is found), the two command lines achieve the equivalent effect of running the script with execution trace on. On other systems (for example, Solaris, and some more modern variants of Linux), /bin/sh is not Bash, and the two command lines would give (slightly) different results. Most notably, '/bin/sh' would be confused by constructs in Bash that it does not recognize at all. (On Solaris, /bin/sh is a Bourne shell; on modern Linux, it is sometimes Dash — a smaller, more strictly POSIX-only shell.) When invoked by name like this, the 'shebang' line ('#!/bin/bash' vs '#!/bin/sh') at the start of the file has no effect on how the contents are interpreted.

The Bash manual has a section on Bash POSIX mode which, contrary to a long-standing but erroneous version of this answer (see also the comments below), does describe in extensive detail the difference between 'Bash invoked as sh' and 'Bash invoked as bash'.

When debugging a (Bash) shell script, it will be sensible and sane — necessary even — to use the shell named in the shebang line with the -x option. Otherwise, you may (will?) get different behaviour when debugging from when running the script.

CSS hexadecimal RGBA?

Well, different color notations is what you will have to learn.
Kuler gives you a better chance to find color and in multiple notations.
Hex is not different from RGB, FF = 255 and 00 = 0, but that's what you know. So in a way, you have to visualize it.
I use Hex, RGBA and RGB. Unless mass conversion is required, manually doing this will help you remember some odd 100 colors and their codes.
For mass conversion write some script like one given by Alarie. Have a blast with Colors.

Self-reference for cell, column and row in worksheet functions

For a cell to self-reference itself:

INDIRECT(ADDRESS(ROW(), COLUMN()))

For a cell to self-reference its column:

INDIRECT(ADDRESS(1,COLUMN()) & ":" & ADDRESS(65536, COLUMN()))

For a cell to self-reference its row:

INDIRECT(ADDRESS(ROW(),1) & ":" & ADDRESS(ROW(),256))
or
INDIRECT("A" & ROW() & ":IV" & ROW())

The numbers are for 2003 and earlier, use column:XFD and row:1048576 for 2007+.

Note: The INDIRECT function is volatile and should only be used when needed.

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

Printing with "\t" (tabs) does not result in aligned columns

The "problem" with the tabs is that they indent the text to fixed tab positions, typically multiples of 4 or 8 characters (depending on the console or editor displaying them). Your first filename is 7 chars, so the next tab stop after its end is at position 8. Your subsequent filenames however are 8 chars long, so the next tab stop is at position 12.

If you want to ensure that columns get nicely indented at the same position, you need to take into account the actual length of previous columns, and either modify the number of following tabs, or pad with the required number of spaces instead. The latter can be achieved using e.g. System.out.printf with an appropriate format specification (e.g. "%1$13s" specifies a minimum width of 13 characters for displaying the first argument as a string).

How do I supply an initial value to a text field?

If you are using TextEditingController then set the text to it, like below

TextEditingController _controller = new TextEditingController();


_controller.text = 'your initial text';

final your_text_name = TextFormField(
      autofocus: false,
      controller: _controller,
      decoration: InputDecoration(
        hintText: 'Hint Value',
      ),
    );

and if you are not using any TextEditingController then you can directly use initialValue like below

final last_name = TextFormField(
      autofocus: false,
      initialValue: 'your initial text',
      decoration: InputDecoration(
        hintText: 'Last Name',
      ),
    );

For more reference TextEditingController

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

How to store arbitrary data for some HTML tags

You could use hidden input tags. I get no validation errors at w3.org with this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />
    <title>Hello</title>
  </head>
  <body>
    <div>
      <a class="article" href="link/for/non-js-users.html">
        <input style="display: none" name="articleid" type="hidden" value="5" />
      </a>
    </div>
  </body>
</html>

With jQuery you'd get the article ID with something like (not tested):

$('.article input[name=articleid]').val();

But I'd recommend HTML5 if that is an option.

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

How to compress image size?

Use Compressor (Image compression library). Visit zetbaitsu/Compressor for code and documentation.

  1. add dependency in gradle (app level)

    dependencies {
        implementation 'id.zelory:compressor:3.0.0'
    }
    
  2. To Compress Image use one of these approaches:

  • Compress Image File:

          val compressedImageFile = Compressor.compress(context, actualImageFile)
    
  • Compress Image File to Bitmap:

          val compressedImageFile = Compressor.compress(context, actualImageFile)
          val bitmap = BitmapFactory.decodeFile(compressedImageFile.path)
    

assign multiple variables to the same value in Javascript

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

_x000D_
_x000D_
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
_x000D_
_x000D_

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Make a dictionary with duplicate keys in Python

Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.

One easy way to achieve this is by using defaultdict:

from collections import defaultdict

data_dict = defaultdict(list)

All you have to do is replace

data_dict[regNumber] = details

with

data_dict[regNumber].append(details)

and you'll get a dictionary of lists.

Algorithm: efficient way to remove duplicate integers from an array

Let's see:

  • O(N) pass to find min/max allocate
  • bit-array for found
  • O(N) pass swapping duplicates to end.

Why is my Git Submodule HEAD detached from master?

EDIT:

See @Simba Answer for valid solution

submodule.<name>.update is what you want to change, see the docs - default checkout
submodule.<name>.branch specify remote branch to be tracked - default master


OLD ANSWER:

Personally I hate answers here which direct to external links which may stop working over time and check my answer here (Unless question is duplicate) - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."

So back to the question: Why does it happen?

Situation you described

After pulling changes from server, many times my submodule head gets detached from master branch.

This is a common case when one does not use submodules too often or has just started with submodules. I believe that I am correct in stating, that we all have been there at some point where our submodule's HEAD gets detached.

  • Cause: Your submodule is not tracking correct branch (default master).
    Solution: Make sure your submodule is tracking the correct branch
$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
#    Set up <branchname>'s tracking information so <upstream>
#    is considered <branchname>'s upstream branch.
#    If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
  • Cause: Your parent repo is not configured to track submodules branch.
    Solution: Make your submodule track its remote branch by adding new submodules with the following two commands.
    • First you tell git to track your remote <branch>.
    • you tell git to perform rebase or merge instead of checkout
    • you tell git to update your submodule from remote.
    $ git submodule add -b <branch> <repository> [<submodule-path>]
    $ git config -f .gitmodules submodule.<submodule-path>.update rebase
    $ git submodule update --remote
  • If you haven't added your existing submodule like this you can easily fix that:
    • First you want to make sure that your submodule has the branch checked out which you want to be tracked.
    $ cd <submodule-path>
    $ git checkout <branch>
    $ cd <parent-repo-path>
    # <submodule-path> is here path releative to parent repo root
    # without starting path separator
    $ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
    $ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>

In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.

fixing DETACHED HEAD when .update = checkout

$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
    modified:   path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote. 
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since 
# you told already parent repo which is the submodules commit hash 
# to track so you don't see it anymore as untracked.

But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:

$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:

The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just git cherry-pick <hash> in this case.

$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>

Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.

Declaring and initializing a string array in VB.NET

Public Function TestError() As String()
     Return {"foo", "bar"}
End Function

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Batch file to copy directories recursively

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

xcopy a: b: /s /e

How to use glob() to find files recursively?

Here is a solution that will match the pattern against the full path and not just the base filename.

It uses fnmatch.translate to convert a glob-style pattern into a regular expression, which is then matched against the full path of each file found while walking the directory.

re.IGNORECASE is optional, but desirable on Windows since the file system itself is not case-sensitive. (I didn't bother compiling the regex because docs indicate it should be cached internally.)

import fnmatch
import os
import re

def findfiles(dir, pattern):
    patternregex = fnmatch.translate(pattern)
    for root, dirs, files in os.walk(dir):
        for basename in files:
            filename = os.path.join(root, basename)
            if re.search(patternregex, filename, re.IGNORECASE):
                yield filename

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

I would suggest to remove the Mysql connection -

UPDATE-This is for Mysql version 5.5,if your version is different ,please change the first line accordingly

sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean

And Install Again But this time set a root password yourself. This will save a lot of effort.

sudo apt-get update
sudo apt-get install mysql-server

In log4j, does checking isDebugEnabled before logging improve performance?

If you use option 2 you are doing a Boolean check which is fast. In option one you are doing a method call (pushing stuff on the stack) and then doing a Boolean check which is still fast. The problem I see is consistency. If some of your debug and info statements are wrapped and some are not it is not a consistent code style. Plus someone later on could change the debug statement to include concatenate strings, which is still pretty fast. I found that when we wrapped out debug and info statement in a large application and profiled it we saved a couple of percentage points in performance. Not much, but enough to make it worth the work. I now have a couple of macros setup in IntelliJ to automatically generate wrapped debug and info statements for me.

What is an attribute in Java?

An abstract class is a type of class that can only be used as a base class for another class; such thus cannot be instantiated. To make a class abstract, the keyword abstract is used. Abstract classes may have one or more abstract methods that only have a header line (no method body). The method header line ends with a semicolon (;). Any class that is derived from the base class can define the method body in a way that is consistent with the header line using all the designated parameters and returning the correct data type (if the return type is not void). An abstract method acts as a place holder; all derived classes are expected to override and complete the method.

Example in Java

abstract public class Shape

{

double area;

public abstract double getArea();

}

How can I inject a property value into a Spring Bean which was configured using annotations?

Before we get Spring 3 - which allows you to inject property constants directly into your beans using annotations - I wrote a sub-class of the PropertyPlaceholderConfigurer bean that does the same thing. So, you can mark up your property setters and Spring will autowire your properties into your beans like so:

@Property(key="property.key", defaultValue="default")
public void setProperty(String property) {
    this.property = property;
}

The Annotation is as follows:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Property {
    String key();
    String defaultValue() default "";
}

The PropertyAnnotationAndPlaceholderConfigurer is as follows:

public class PropertyAnnotationAndPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private static Logger log = Logger.getLogger(PropertyAnnotationAndPlaceholderConfigurer.class);

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties properties) throws BeansException {
        super.processProperties(beanFactory, properties);

        for (String name : beanFactory.getBeanDefinitionNames()) {
            MutablePropertyValues mpv = beanFactory.getBeanDefinition(name).getPropertyValues();
            Class clazz = beanFactory.getType(name);

            if(log.isDebugEnabled()) log.debug("Configuring properties for bean="+name+"["+clazz+"]");

            if(clazz != null) {
                for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
                    Method setter = property.getWriteMethod();
                    Method getter = property.getReadMethod();
                    Property annotation = null;
                    if(setter != null && setter.isAnnotationPresent(Property.class)) {
                        annotation = setter.getAnnotation(Property.class);
                    } else if(setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                        annotation = getter.getAnnotation(Property.class);
                    }
                    if(annotation != null) {
                        String value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(StringUtils.isEmpty(value)) {
                            value = annotation.defaultValue();
                        }
                        if(StringUtils.isEmpty(value)) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+property.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }

                for(Field field : clazz.getDeclaredFields()) {
                    if(log.isDebugEnabled()) log.debug("examining field=["+clazz.getName()+"."+field.getName()+"]");
                    if(field.isAnnotationPresent(Property.class)) {
                        Property annotation = field.getAnnotation(Property.class);
                        PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                        if(property.getWriteMethod() == null) {
                            throw new BeanConfigurationException("setter for property=["+clazz.getName()+"."+field.getName()+"] not available.");
                        }

                        Object value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(value == null) {
                            value = annotation.defaultValue();
                        }
                        if(value == null) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+field.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }
            }
        }
    }

}

Feel free to modify to taste

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

What is the syntax of the enhanced for loop in Java?

An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

"Find next" in Vim

When I was beginning I needed to watch a demo.

How to search in Vim

  1. type /
  2. type search term e.g. "var"
  3. press enter
  4. for next instance press n (for previous N)

How to use comparison operators like >, =, < on BigDecimal

BigDecimal isn't a primitive, so you cannot use the <, > operators. However, since it's a Comparable, you can use the compareTo(BigDecimal) to the same effect. E.g.:

public class Domain {
    private BigDecimal unitPrice;

    public boolean isCheaperThan(BigDecimal other) {
        return unitPirce.compareTo(other.unitPrice) < 0;
    }

    // etc...
}

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How to install the Six module in Python2.7

I had the same question for macOS.

But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew.

I fixed my issue with: $ brew uninstall python@2

Some context on here: https://bugs.swift.org/browse/SR-1061

Safely override C++ virtual functions

Make the function abstract, so that derived classes have no other choice than to override it.

@Ray Your code is invalid.

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

Abstract functions cannot have bodies defined inline. It must be modified to become

class parent {
public:
  virtual void handle_event(int something) const = 0;
};

void parent::handle_event( int something ) { /* do w/e you want here. */ }

rsync - mkstemp failed: Permission denied (13)

I encountered the same problem and solved it by chown the user of the destination folder. The current user does not have the permission to read, write and execute the destination folder files. Try adding the permission by chmod a+rwx <folder/file name>.

How to check if a variable is set in Bash?

To see if a variable is nonempty, I use

if [[ $var ]]; then ...       # `$var' expands to a nonempty string

The opposite tests if a variable is either unset or empty:

if [[ ! $var ]]; then ...     # `$var' expands to the empty string (set or not)

To see if a variable is set (empty or nonempty), I use

if [[ ${var+x} ]]; then ...   # `var' exists (empty or nonempty)
if [[ ${1+x} ]]; then ...     # Parameter 1 exists (empty or nonempty)

The opposite tests if a variable is unset:

if [[ ! ${var+x} ]]; then ... # `var' is not set at all
if [[ ! ${1+x} ]]; then ...   # We were called with no arguments

SQL Server : How to test if a string has only digit characters

Use Not Like

where some_column NOT LIKE '%[^0-9]%'

Demo

declare @str varchar(50)='50'--'asdarew345'

select 1 where @str NOT LIKE '%[^0-9]%'

Should CSS always preceed Javascript?

The 2020 answer: it probably doesn't matter

The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.

I included a more detailed writeup on my blog

Read a XML (from a string) and get some fields - Problems reading XML

Or use the XmlSerializer class.

XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));

C++ Dynamic Shared Library on Linux

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  void* handle = dlopen("myclass.so", RTLD_LAZY);

  MyClass* (*create)();
  void (*destroy)(MyClass*);

  create = (MyClass* (*)())dlsym(handle, "create_object");
  destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");

  MyClass* myClass = (MyClass*)create();
  myClass->DoSomething();
  destroy( myClass );
}

On Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object and destroy_object. Your main application would not need to be changed in any way.

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

How to make a floated div 100% height of its parent?

For the parent:

display: flex;

You should add some prefixes http://css-tricks.com/using-flexbox/

Edit: Only drawback is IE as usual, IE9 does not support flex. http://caniuse.com/flexbox

Edit 2: As @toddsby noted, align items is for parent, and its default value actually is stretch. If you want a different value for child, there is align-self property.

Edit 3: jsFiddle: https://jsfiddle.net/bv71tms5/2/

Python slice first and last element in list

first, last = some_list[0], some_list[-1]

Can I make a phone call from HTML on Android?

Yes you can; it works on Android too:

tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:

* tel:2125551212
* tel: (212) 555 1212

The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:

<a href="tel:2125551212">2125551212</a>

on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.

Have a look to RFC3966

Reloading a ViewController

Direct to your ViewController again. in my situation [self.view setNeedsDisplay]; and [self viewDidLoad]; [self viewWillAppear:YES];does not work, but the method below worked.

In objective C

UIStoryboard *MyStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil ];
UIViewController *vc = [MyStoryboard instantiateViewControllerWithIdentifier:@"ViewControllerStoryBoardID"];
[self presentViewController:vc animated:YES completion:nil];

Swift:

let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ViewControllerStoryBoardID")   
self.presentViewController(secondViewController, animated: true, completion: nil)

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Going through a text file line by line in C

Say you're dealing with some other delimiter, such as a \t tab, instead of a \n newline.

A more general approach to delimiters is the use of getc(), which grabs one character at a time.

Note that getc() returns an int, so that we can test for equality with EOF.

Secondly, we define an array line[BUFFER_MAX_LENGTH] of type char, in order to store up to BUFFER_MAX_LENGTH-1 characters on the stack (we have to save that last character for a \0 terminator character).

Use of an array avoids the need to use malloc and free to create a character pointer of the right length on the heap.

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    /* get a character from the file pointer */
    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            fprintf(stdout, "%s\n", line);
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            fprintf(stdout, "%s\n", line);
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

If you must use a char *, then you can still use this code, but you strdup() the line[] array, once it is filled up with a line's worth of input. You must free this duplicated string once you're done with it, or you'll get a memory leak:

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;
    char *dynamicLine = NULL;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

or if you want date time format then you can also do this

TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = dateTime.ToString("hh:mm:tt");

For more you can check Custom TimeSpan Format Strings

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

What is the error "Every derived table must have its own alias" in MySQL?

I think it's asking you to do this:

SELECT ID
FROM (SELECT ID,
             msisdn 
      FROM (SELECT * FROM TT2) as myalias
     ) as anotheralias;

But why would you write this query in the first place?

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.

Rails migration for change column

Just generate migration:

rails g migration change_column_to_new_from_table_name

Update migration like this:

class ClassName < ActiveRecord::Migration
  change_table :table_name do |table|
    table.change :column_name, :data_type
  end
end

and finally

rake db:migrate

how to add jquery in laravel project

In Laravel 6 you can get it like this:

try {
    window.$ = window.jQuery = require('jquery');
} catch (e) {}

Custom height Bootstrap's navbar

You need also to set .min-height: 0px; please see bellow:

.navbar-inner {
    min-height: 0px;
}

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

If you set .min-height: 0px; then you can choose any height you want!

Good Luck!

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

PKIX path building failed in Java application

I ran into similar issues whose cause and solution turned out both to be rather simple:

Main Cause: Did not import the proper cert using keytool

NOTE: Only import root CA (or your own self-signed) certificates

NOTE: don't import an intermediate, non certificate chain root cert

Solution Example for imap.gmail.com

  1. Determine the root CA cert:

    openssl s_client -showcerts -connect imap.gmail.com:993
    

    in this case we find the root CA is Equifax Secure Certificate Authority

  2. Download root CA cert.
  3. Verify downloaded cert has proper SHA-1 and/or MD5 fingerprints by comparing with info found here
  4. Import cert for javax.net.ssl.trustStore:

    keytool -import -alias gmail_imap -file Equifax_Secure_Certificate_Authority.pem
    
  5. Run your java code

binning data in python with scipy/numpy

The Scipy (>=0.11) function scipy.stats.binned_statistic specifically addresses the above question.

For the same example as in the previous answers, the Scipy solution would be

import numpy as np
from scipy.stats import binned_statistic

data = np.random.rand(100)
bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

C# try catch continue execution

In your second function remove the e variable in the catch block then add throw.

This will carry over the generated exception the the final function and output it.

Its very common when you dont want your business logic code to throw exception but your UI.

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

PHP Get URL with Parameter

Finally found this method:

basename($_SERVER['REQUEST_URI']);

This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10).

FlutterError: Unable to load asset

Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app.

Here is an example:

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

To include all assets under a directory, specify the directory name with the / character at the end:

flutter:
  assets:
    - directory/
    - directory/subdirectory/

For more info, see https://flutter.dev/docs/development/ui/assets-and-images

xpath find if node exists

<xsl:if test="xpath-expression">...</xsl:if>

so for example

<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>

Get latitude and longitude automatically using php, API

Two ideas:

  • Are Address and Region URL Encoded?
  • Perhaps your computer running the code doesn't allow http access. Try loading another page (like 'http://www.google.com') and see if that works. If that also doesn't work, then there's something wrong with PHP settings.

How to get the children of the $(this) selector?

You can use Child Selecor to reference the child elements available within the parent.

$(' > img', this).attr("src");

And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.

 $('#divid > img').attr("src");

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}