Programs & Examples On #Touchscreen

A touchscreen is an electronic visual display that can detect the presence and location of a touch within the display area. (Wikipedia)

Detecting a long press with Android

Try this:

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        Log.e("", "Longpress detected");
    }
});

public boolean onTouchEvent(MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
};

How to use ADB to send touch events to device using sendevent command?

Android comes with an input command-line tool that can simulate miscellaneous input events. To simulate tapping, it's:

input tap x y

You can use the adb shell ( > 2.3.5) to run the command remotely:

adb shell input tap x y

Disable EditText blinking cursor

In my case, I wanted to enable/disable the cursor when the edit is focused.

In your Activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            EditText edit = ((EditText) v);
            Rect outR = new Rect();
            edit.getGlobalVisibleRect(outR);
            Boolean isKeyboardOpen = !outR.contains((int)ev.getRawX(), (int)ev.getRawY());
            System.out.print("Is Keyboard? " + isKeyboardOpen);
            if (isKeyboardOpen) {
                System.out.print("Entro al IF");
                edit.clearFocus();
                InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
            }

            edit.setCursorVisible(!isKeyboardOpen);

        }
    }
    return super.dispatchTouchEvent(ev);
}

Why use Optional.of over Optional.ofNullable?

Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

So if you have something like:

@Html.DropDownList("MyList", Model.DropDownData, "")

And Model.DropDownData is null, MVC looks through your ViewData for something named MyList and throws an error if there's no object in ViewData with that name.

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

What is VanillaJS?

VanillaJS is a term for library/framework free javascript.

Its sometimes ironically referred to as a library, as a joke for people who could be seen as mindlessly using different frameworks, especially jQuery.

Some people have gone so far to release this library, usually with an empty or comment-only js file.

Returning data from Axios API

You can use Async - Await:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

Print a string as hex bytes?

Another answer in two lines that some might find easier to read, and helps with debugging line breaks or other odd characters in a string:

For Python 2.7

for character in string:
    print character, character.encode('hex')

For Python 3.7 (not tested on all releases of 3)

for character in string:
    print(character, character.encode('utf-8').hex())

Generate class from database table

I tried to use the suggestions above and in the process improved upon the solutions in this thread.

Let us say you use a base class (ObservableObject in this case) that implements the PropertyChanged Event, you would do something like this. I will probably write a blog post one day in my blog sqljana.wordpress.com

Please do substitute the values for the first three variables:

    --These three things have to be substituted (when called from Powershell, they are replaced before execution)
DECLARE @Schema VARCHAR(MAX) = N'&Schema'
DECLARE @TableName VARCHAR(MAX) = N'&TableName'
DECLARE @Namespace VARCHAR(MAX) = N'&Namespace'

DECLARE @CRLF VARCHAR(2) = CHAR(13) + CHAR(10);
DECLARE @result VARCHAR(max) = ' '

DECLARE @PrivateProp VARCHAR(100) = @CRLF + 
                CHAR(9) + CHAR(9) + 'private <ColumnType> _<ColumnName>;';
DECLARE @PublicProp VARCHAR(255) = @CRLF + 
                CHAR(9) + CHAR(9) + 'public <ColumnType> <ColumnName> '  + @CRLF +
                CHAR(9) + CHAR(9) + '{ ' + @CRLF +
                CHAR(9) + CHAR(9) + '   get { return _<ColumnName>; } ' + @CRLF +
                CHAR(9) + CHAR(9) + '   set ' + @CRLF +
                CHAR(9) + CHAR(9) + '   { ' + @CRLF +
                CHAR(9) + CHAR(9) + '       _<ColumnName> = value;' + @CRLF +
                CHAR(9) + CHAR(9) + '       base.RaisePropertyChanged();' + @CRLF +
                CHAR(9) + CHAR(9) + '   } ' + @CRLF +
                CHAR(9) + CHAR(9) + '}' + @CRLF;

DECLARE @RPCProc VARCHAR(MAX) = @CRLF +         
                CHAR(9) + CHAR(9) + 'public event PropertyChangedEventHandler PropertyChanged; ' + @CRLF +
                CHAR(9) + CHAR(9) + 'private void RaisePropertyChanged( ' + @CRLF +
                CHAR(9) + CHAR(9) + '       [CallerMemberName] string caller = "" ) ' + @CRLF +
                CHAR(9) + CHAR(9) + '{  ' + @CRLF +
                CHAR(9) + CHAR(9) + '   if (PropertyChanged != null)  ' + @CRLF +
                CHAR(9) + CHAR(9) + '   { ' + @CRLF +
                CHAR(9) + CHAR(9) + '       PropertyChanged( this, new PropertyChangedEventArgs( caller ) );  ' + @CRLF +
                CHAR(9) + CHAR(9) + '   } ' + @CRLF +
                CHAR(9) + CHAR(9) + '}';

DECLARE @PropChanged VARCHAR(200) =  @CRLF +            
                CHAR(9) + CHAR(9) + 'protected override void AfterPropertyChanged(string propertyName) ' + @CRLF +
                CHAR(9) + CHAR(9) + '{ ' + @CRLF +
                CHAR(9) + CHAR(9) + '   System.Diagnostics.Debug.WriteLine("' + @TableName + ' property changed: " + propertyName); ' + @CRLF +
                CHAR(9) + CHAR(9) + '}';

SET @result = 'using System;' + @CRLF + @CRLF +
                'using MyCompany.Business;' + @CRLF + @CRLF +
                'namespace ' + @Namespace  + @CRLF + '{' + @CRLF +
                '   public class ' + @TableName + ' : ObservableObject' + @CRLF + 
                '   {' + @CRLF +
                '   #region Instance Properties' + @CRLF 

SELECT @result = @result
                 + 
                REPLACE(
                            REPLACE(@PrivateProp
                            , '<ColumnName>', ColumnName)
                        , '<ColumnType>', ColumnType)
                +                           
                REPLACE(
                            REPLACE(@PublicProp
                            , '<ColumnName>', ColumnName)
                        , '<ColumnType>', ColumnType)                   
FROM
(
    SELECT  c.COLUMN_NAME   AS ColumnName 
        , CASE c.DATA_TYPE   
            WHEN 'bigint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
            WHEN 'binary' THEN 'Byte[]'
            WHEN 'bit' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END            
            WHEN 'char' THEN 'String'
            WHEN 'date' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime2' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetimeoffset' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                    
            WHEN 'decimal' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                    
            WHEN 'float' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                    
            WHEN 'image' THEN 'Byte[]'
            WHEN 'int' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
            WHEN 'money' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                
            WHEN 'nchar' THEN 'String'
            WHEN 'ntext' THEN 'String'
            WHEN 'numeric' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                            
            WHEN 'nvarchar' THEN 'String'
            WHEN 'real' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                        
            WHEN 'smalldatetime' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'smallint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END            
            WHEN 'smallmoney' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                        
            WHEN 'text' THEN 'String'
            WHEN 'time' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                                                                    
            WHEN 'timestamp' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'tinyint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                                
            WHEN 'uniqueidentifier' THEN 'Guid'
            WHEN 'varbinary' THEN 'Byte[]'
            WHEN 'varchar' THEN 'String'
            ELSE 'Object'
        END AS ColumnType
        , c.ORDINAL_POSITION 
FROM    INFORMATION_SCHEMA.COLUMNS c
WHERE   c.TABLE_NAME = @TableName 
    AND ISNULL(@Schema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA  
) t
ORDER BY t.ORDINAL_POSITION

SELECT @result = @result + @CRLF + 
                CHAR(9) + '#endregion Instance Properties' + @CRLF +
                --CHAR(9) + @RPCProc + @CRLF +
                CHAR(9) + @PropChanged + @CRLF +
                CHAR(9) + '}' + @CRLF +
                @CRLF + '}' 
--SELECT @result
PRINT @result

The base class is based on Josh Smith's article here From http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/

I did rename the class to be called ObservableObject and also took advantage of a c# 5 feature using the CallerMemberName attribute

//From http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/
//
//Jana's change: Used c# 5 feature to bypass passing in the property name using [CallerMemberName] 
//  protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace MyCompany.Business
{

    /// <summary>
    /// Implements the INotifyPropertyChanged interface and 
    /// exposes a RaisePropertyChanged method for derived 
    /// classes to raise the PropertyChange event.  The event 
    /// arguments created by this class are cached to prevent 
    /// managed heap fragmentation.
    /// </summary>
    [Serializable]
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        #region Data

        private static readonly Dictionary<string, PropertyChangedEventArgs> eventArgCache;
        private const string ERROR_MSG = "{0} is not a public property of {1}";

        #endregion // Data

        #region Constructors

        static ObservableObject()
        {
            eventArgCache = new Dictionary<string, PropertyChangedEventArgs>();
        }

        protected ObservableObject()
        {
        }

        #endregion // Constructors

        #region Public Members

        /// <summary>
        /// Raised when a public property of this object is set.
        /// </summary>
        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Returns an instance of PropertyChangedEventArgs for 
        /// the specified property name.
        /// </summary>
        /// <param name="propertyName">
        /// The name of the property to create event args for.
        /// </param>        
        public static PropertyChangedEventArgs
            GetPropertyChangedEventArgs(string propertyName)
        {
            if (String.IsNullOrEmpty(propertyName))
                throw new ArgumentException(
                    "propertyName cannot be null or empty.");

            PropertyChangedEventArgs args;

            // Get the event args from the cache, creating them
            // and adding to the cache if necessary.
            lock (typeof(ObservableObject))
            {
                bool isCached = eventArgCache.ContainsKey(propertyName);
                if (!isCached)
                {
                    eventArgCache.Add(
                        propertyName,
                        new PropertyChangedEventArgs(propertyName));
                }

                args = eventArgCache[propertyName];
            }

            return args;
        }

        #endregion // Public Members

        #region Protected Members

        /// <summary>
        /// Derived classes can override this method to
        /// execute logic after a property is set. The 
        /// base implementation does nothing.
        /// </summary>
        /// <param name="propertyName">
        /// The property which was changed.
        /// </param>
        protected virtual void AfterPropertyChanged(string propertyName)
        {
        }

        /// <summary>
        /// Attempts to raise the PropertyChanged event, and 
        /// invokes the virtual AfterPropertyChanged method, 
        /// regardless of whether the event was raised or not.
        /// </summary>
        /// <param name="propertyName">
        /// The property which was changed.
        /// </param>
        protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            this.VerifyProperty(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                // Get the cached event args.
                PropertyChangedEventArgs args =
                    GetPropertyChangedEventArgs(propertyName);

                // Raise the PropertyChanged event.
                handler(this, args);
            }

            this.AfterPropertyChanged(propertyName);
        }

        #endregion // Protected Members

        #region Private Helpers

        [Conditional("DEBUG")]
        private void VerifyProperty(string propertyName)
        {
            Type type = this.GetType();

            // Look for a public property with the specified name.
            PropertyInfo propInfo = type.GetProperty(propertyName);

            if (propInfo == null)
            {
                // The property could not be found,
                // so alert the developer of the problem.

                string msg = string.Format(
                    ERROR_MSG,
                    propertyName,
                    type.FullName);

                Debug.Fail(msg);
            }
        }

        #endregion // Private Helpers
    }
}

Here is the part that you guys are going to like some more. I built a Powershell script to generate for all the tables in a SQL database. It is based on a Powershell guru named Chad Miller's Invoke-SQLCmd2 cmdlet which can be downloaded from here: http://gallery.technet.microsoft.com/ScriptCenter/7985b7ef-ed89-4dfd-b02a-433cc4e30894/

Once you have that cmdlet, the Powershell script to generate for all tables becomes simple (do substitute the variables with your specific values).

. C:\MyScripts\Invoke-Sqlcmd2.ps1

$serverInstance = "MySQLInstance"
$databaseName = "MyDb"
$generatorSQLFile = "C:\MyScripts\ModelGen.sql" 
$tableListSQL = "SELECT name FROM $databaseName.sys.tables"
$outputFolder = "C:\MyScripts\Output\"
$namespace = "MyCompany.Business"

$placeHolderSchema = "&Schema"
$placeHolderTableName = "&TableName"
$placeHolderNamespace = "&Namespace"

#Get the list of tables in the database to generate c# models for
$tables = Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $tableListSQL -As DataRow -Verbose

foreach ($table in $tables)
{
    $table1 = $table[0]
    $outputFile = "$outputFolder\$table1.cs"


    #Replace variables with values (returns an array that we convert to a string to use as query)
    $generatorSQLFileWSubstitutions = (Get-Content $generatorSQLFile).
                                            Replace($placeHolderSchema,"dbo").
                                            Replace($placeHolderTableName, $table1).
                                            Replace($placeHolderNamespace, $namespace) | Out-String

    "Ouputing for $table1 to $outputFile"

    #The command generates .cs file content for model using "PRINT" statements which then gets written to verbose output (stream 4)
    # ...capture the verbose output and redirect to a file
    (Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $generatorSQLFileWSubstitutions -Verbose) 4> $outputFile

}

How do I get the full url of the page I am on in C#

I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

Regular expression for excluding special characters

Here's all the french accented characters: àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ

I would google a list of German accented characters. There aren't THAT many. You should be able to get them all.

For URLS I Replace accented URLs with regular letters like so:

string beforeConversion = "àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ";
string afterConversion = "aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n";
for (int i = 0; i < beforeConversion.Length; i++) {

     cleaned = Regex.Replace(cleaned, beforeConversion[i].ToString(), afterConversion[i].ToString());
}

There's probably a more efficient way, mind you.

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

How to change ProgressBar's progress indicator color in Android

You can use custom drawable to make your Progressbar stylable. Create a drawable file

progress_user_badge.xml

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <corners android:radius="@dimen/_5sdp"/>
            <solid android:color="@color/your_default_color" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle">
                <corners android:radius="@dimen/_5sdp"/>
                <solid android:color="@color/your_exact_color" />
            </shape>
        </clip>
    </item>

</layer-list>

now use this drawable file in your widget

<ProgressBar
    android:id="@+id/badge_progress_bar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="@dimen/_200sdp"
    android:layout_height="@dimen/_7sdp"
    android:layout_gravity="center"
    android:layout_marginTop="@dimen/_15sdp"
    android:indeterminate="false"
    android:max="100"
    android:progress="70"
    android:progressDrawable="@drawable/progress_user_badge"/>

You can use the bellow line to change the progress color of Progressbar programmatically

badge_progress_bar.progressTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.your_color))

What's the u prefix in a Python string?

My guess is that it indicates "Unicode", is it correct?

Yes.

If so, since when is it available?

Python 2.x.

In Python 3.x the strings use Unicode by default and there's no need for the u prefix. Note: in Python 3.0-3.2, the u is a syntax error. In Python 3.3+ it's legal again to make it easier to write 2/3 compatible apps.

Uncaught TypeError: Cannot set property 'value' of null

h_url=document.getElementById("u") is null here

There is no element exist with id as u

Differences between fork and exec

I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()/exec(), especially for someone used to the Windows CreateProcess() model:

A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)

.

In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)

.

It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3 exec System Calls)

Once you understand the distinction between a program and a process, the behavior of fork() and exec() function can be summarized as:

  • fork() creates a duplicate of the current process
  • exec() replaces the program in the current process with another program

(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

Using sed, how do you print the first 'N' characters of a line?

How about head ?

echo alonglineoftext | head -c 9

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

In my case i just went through following steps in windows 10.

  1. goto control panel
  2. click administrative
  3. click services
  4. find OracelServeceXE, OracleXEClrAgeng, OracleXETNSListener
  5. Right click and press Start/Restart
  6. After Completing Process. Check it will work or it will work ;)
  7. Done
  8. All the Best.

Erase whole array Python

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

Connection string with relative path to the database file

In your config file give the relative path

ConnectionString = "Data Source=|DataDirectory|\Database.sdf";

Change the DataDirectory to your executable path

string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);

If you are using EntityFramework, then you can set the DataDirectory path in your Context class

PHP find difference between two datetimes

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I did it by passing the cookie through the HttpContext:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);

How to get the background color of an HTML element?

With jQuery:

jQuery('#myDivID').css("background-color");

With prototype:

$('myDivID').getStyle('backgroundColor'); 

With pure JS:

document.getElementById("myDivID").style.backgroundColor

How can I read numeric strings in Excel cells as string (not numbers)?

There is a ready-to-use wrapper (some additional optimizations can be applied)

  • it supports numeric and String cells

  • formulas are recognized and handled automatically

  • avoid some boilerplate

     public final class Cell {
    
     private final static DataFormatter FORMATTER = new DataFormatter();
    
     private XSSFCell mCell;
    
     public Cell(@NotNull XSSFCell cell) {
         mCell = cell;
    
         if (isFormula()) {
             XSSFWorkbook book = mCell.getSheet().getWorkbook();
             FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
             mCell = (XSSFCell) evaluator.evaluateInCell(mCell);
         }
     }
    
     /**
      * Get content
      */
     public final int getInt() {
         return (int) getLong();
     }
    
     public final long getLong() {
         return Math.round(getDouble());
     }
    
     public final double getDouble() {
         return mCell.getNumericCellValue();
     }
    
     public final String getString() {
         if (!isString()) {
             return FORMATTER.formatCellValue(mCell);
         }
         return mCell.getStringCellValue();
     }
    
     /**
      * Get properties
      */
     public final boolean isNumber() {
         if (isFormula()) {
             return mCell.getCachedFormulaResultType().equals(CellType.NUMERIC);
         }
         return mCell.getCellType().equals(CellType.NUMERIC);
     }
    
     public final boolean isString() {
         if (isFormula()) {
             return mCell.getCachedFormulaResultType().equals(CellType.STRING);
         }
         return mCell.getCellType().equals(CellType.STRING);
     }
    
     public final boolean isFormula() {
         return mCell.getCellType().equals(CellType.FORMULA);
     }
    
     /**
      * Debug info
      */
     @Override
     public String toString() {
         return getString();
     }
     }
    

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

How do I find the caller of a method using stacktrace or reflection?

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).

Responsive image map

David Bradshaw wrote a nice little library that solves this problem. It can be used with or without jQuery.

Available here: https://github.com/davidjbradshaw/imagemap-resizer

Creating a List of Lists in C#

A quick example:

List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });

// To iterate over it.
foreach (List<string> subList in myList)
{
    foreach (string item in subList)
    {
        Console.WriteLine(item);
    }
}

Is that what you were looking for? Or are you trying to create a new class that extends List<T> that has a member that is a `List'?

How to create materialized views in SQL Server?

When indexed view is not an option, and quick updates are not necessary, you can create a hack cache table:

select * into cachetablename from myviewname
alter table cachetablename add primary key (columns)
-- OR alter table cachetablename add rid bigint identity primary key
create index...

then sp_rename view/table or change any queries or other views that reference it to point to the cache table.

schedule daily/nightly/weekly/whatnot refresh like

begin transaction
truncate table cachetablename
insert into cachetablename select * from viewname
commit transaction

NB: this will eat space, also in your tx logs. Best used for small datasets that are slow to compute. Maybe refactor to eliminate "easy but large" columns first into an outer view.

What's the difference between console.dir and console.log?

Difference between console.log() and console.dir():

Here is the difference in a nutshell:

  • console.log(input): The browser logs in a nicely formatted manner
  • console.dir(input): The browser logs just the object with all its properties

Example:

The following code:

let obj = {a: 1, b: 2};
let DOMel = document.getElementById('foo');
let arr = [1,2,3];

console.log(DOMel);
console.dir(DOMel);

console.log(obj);
console.dir(obj);

console.log(arr);
console.dir(arr);

Logs the following in google dev tools:

enter image description here

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

EditText onClickListener in Android

This Works For me:

mEditInit = (EditText) findViewById(R.id.date_init);
mEditInit.setKeyListener(null);
mEditInit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
            {
                mEditInit.callOnClick();
            }
        }
    });
mEditInit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        showDialog(DATEINIT_DIALOG);
    }

});

How do I remove diacritics (accents) from a string in .NET?

The CodePage of Greek (ISO) can do it

The information about this codepage is into System.Text.Encoding.GetEncodings(). Learn about in: https://msdn.microsoft.com/pt-br/library/system.text.encodinginfo.getencoding(v=vs.110).aspx

Greek (ISO) has codepage 28597 and name iso-8859-7.

Go to the code... \o/

string text = "Você está numa situação lamentável";

string textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding("iso-8859-7"));
//result: "Voce+esta+numa+situacao+lamentavel"

string textDecode = System.Web.HttpUtility.UrlDecode(textEncode);
//result: "Voce esta numa situacao lamentavel"

So, write this function...

public string RemoveAcentuation(string text)
{
    return
        System.Web.HttpUtility.UrlDecode(
            System.Web.HttpUtility.UrlEncode(
                text, Encoding.GetEncoding("iso-8859-7")));
}

Note that... Encoding.GetEncoding("iso-8859-7") is equivalent to Encoding.GetEncoding(28597) because first is the name, and second the codepage of Encoding.

Get the data received in a Flask request

request.data

This is great to use but remember that it comes in as a string and will need iterated through.

How can I backup a remote SQL Server database to a local drive?

There is the 99% solution to get bak file from remote sql server to your local pc. I described it there in my post http://www.ok.unsode.com/post/2015/06/27/remote-sql-backup-to-local-pc

In general it will look like this:

  • execute sql script to generate bak files

  • execute sql script to insert each bak file into temp table with varbinary field type and select this row and download data

  • repeat prev. step as many time as you have bak files

  • execute sql script to remove all temporary resources

that's it, you have your bak files on your local pc.

Refresh a page using PHP

PHP is server-side language, so you can not refresh the page with PHP, but JavaScript is the best option to refresh the page:

location.reload();

The visit Location reload() method.

Why does NULL = NULL evaluate to false in SQL server

Because NULL means 'unknown value' and two unknown values cannot be equal.

So, if to our logic NULL N°1 is equal to NULL N°2, then we have to tell that somehow:

SELECT 1
WHERE ISNULL(nullParam1, -1) = ISNULL(nullParam2, -1)

where known value -1 N°1 is equal to -1 N°2

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

npm behind a proxy fails with status 403

If you need to provide a username and password to authenticate at your proxy, this is the syntax to use:

npm config set proxy http://usr:pwd@host:port
npm config set https-proxy http://usr:pwd@host:port

What do 'real', 'user' and 'sys' mean in the output of time(1)?

To expand on the accepted answer, I just wanted to provide another reason why real ? user + sys.

Keep in mind that real represents actual elapsed time, while user and sys values represent CPU execution time. As a result, on a multicore system, the user and/or sys time (as well as their sum) can actually exceed the real time. For example, on a Java app I'm running for class I get this set of values:

real    1m47.363s
user    2m41.318s
sys     0m4.013s

How can I convert a Word document to PDF?

This is quite a hard task, ever harder if you want perfect results (impossible without using Word) as such the number of APIs that just do it all for you in pure Java and are open source is zero I believe (Update: I am wrong, see below).

Your basic options are as follows:

  1. Using JNI/a C# web service/etc script MS Office (only option for 100% perfect results)
  2. Using the available APIs script Open Office (90+% perfect)
  3. Use Apache POI & iText (very large job, will never be perfect).

Update - 2016-02-11 Here is a cut down copy of my blog post on this subject which outlines existing products that support Word-to-PDF in Java.

Converting Microsoft Office (Word, Excel) documents to PDFs in Java

Three products that I know of can render Office documents:

yeokm1/docs-to-pdf-converter Irregularly maintained, Pure Java, Open Source Ties together a number of libraries to perform the conversion.

xdocreport Actively developed, Pure Java, Open Source It's Java API to merge XML document created with MS Office (docx) or OpenOffice (odt), LibreOffice (odt) with a Java model to generate report and convert it if you need to another format (PDF, XHTML...).

Snowbound Imaging SDK Closed Source, Pure Java Snowbound appears to be a 100% Java solution and costs over $2,500. It contains samples describing how to convert documents in the evaluation download.

OpenOffice API Open Source, Not Pure Java - Requires Open Office installed OpenOffice is a native Office suite which supports a Java API. This supports reading Office documents and writing PDF documents. The SDK contains an example in document conversion (examples/java/DocumentHandling/DocumentConverter.java). To write PDFs you need to pass the "writer_pdf_Export" writer rather than the "MS Word 97" one. Or you can use the wrapper API JODConverter.

JDocToPdf - Dead as of 2016-02-11 Uses Apache POI to read the Word document and iText to write the PDF. Completely free, 100% Java but has some limitations.

How to make sure that string is valid JSON using JSON.NET

I'm using this one:

  internal static bool IsValidJson(string data)
  {
     data = data.Trim();
     try
     {
        if (data.StartsWith("{") && data.EndsWith("}"))
        {
           JToken.Parse(data);
        }
        else if (data.StartsWith("[") && data.EndsWith("]"))
        {
           JArray.Parse(data);
        }
        else
        {
           return false;
        }
        return true;
     }
     catch
     {
        return false;
     }
  }

jQuery: more than one handler for same event

You should be able to use chaining to execute the events in sequence, e.g.:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

I guess the below code is doing the same

$('#target')
      .click(function(event) {
        alert('Hello!');
      })
      .click(function(event) {
        alert('Hello again!');
      })
      .click(function(event) {
        alert('Hello yet again!');
      });

Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3

TFM also says:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

How to get absolute path to file in /resources folder of your project

To return a file or filepath

URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();  // return file path

Escape a string in SQL Server so that it is safe to use in LIKE expression

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

Stop Chrome Caching My JS Files

add Something like script.js?a=[random Number] with the Random number generated by PHP.

Have you tried expire=0, the pragma "no-cache" and "cache-control=NO-CACHE"? (I dunno what they say about Scripts).

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

What does enctype='multipart/form-data' mean?

The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

The enctype attribute can be used only if method="post".

No characters are encoded. This value is required when you are using forms that have a file upload control

From W3Schools

How to merge two arrays of objects by ID using lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

var merge = _.merge(arr1, arr2);

Which is the short version of:

var merge = _.chain(arr1).zip(arr2).map(function(item) {
    return _.merge.apply(null, item);
}).value();

Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

var merge = _.map(arr1, function(item) {
    return _.merge(item, _.find(arr2, { 'member' : item.member }));
});

You can easily convert this to a mixin. See the example below:

_x000D_
_x000D_
_.mixin({_x000D_
  'mergeByKey' : function(arr1, arr2, key) {_x000D_
    var criteria = {};_x000D_
    criteria[key] = null;_x000D_
    return _.map(arr1, function(item) {_x000D_
      criteria[key] = item[key];_x000D_
      return _.merge(item, _.find(arr2, criteria));_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "name": 'yyyyyyyyyy',_x000D_
  "age": 26_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "name": 'xxxxxx',_x000D_
  "age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I create directories recursively?

a fresh answer to a very old question:

starting from python 3.2 you can do this:

import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)

thanks to the exist_ok flag this will not even complain if the directory exists (depending on your needs....).


starting from python 3.4 (which includes the pathlib module) you can do this:

from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)

starting from python 3.5 mkdir also has an exist_ok flag - setting it to True will raise no exception if the directory exists:

path.mkdir(parents=True, exist_ok=True)

TypeError: 'module' object is not callable

When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.

Traceback (most recent call last):
   File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable

For example

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule]
    },
# ...
)

Should have been

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule:main]
    },
# ...
)

So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable.

Use multiple custom fonts using @font-face?

You can use multiple font faces quite easily. Below is an example of how I used it in the past:

<!--[if (IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.eot);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.eot);
        }
    </style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.ttf);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.ttf);
        }
    </style>
<!--<![endif]-->

It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.

That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.

If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.

Hope that helps.

Fastest way to convert JavaScript NodeList to Array?

Assuming nodeList = document.querySelectorAll("div"), this is a concise form of converting nodelist to array.

var nodeArray = [].slice.call(nodeList);

See me use it here.

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

Read a zipped file as a pandas DataFrame

https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial

Please follow this link.

import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)

cannot find module "lodash"

Be sure to install lodash in the required folder. This is probably your C:\gwsk directory.

If that folder has a package.json file, it is also best to add --save behind the install command.

$ npm install lodash --save

The package.json file holds information about the project, but to keep it simple, it holds your project dependencies.

The save command will add the installed module to the project dependencies.

If the package.json file exists, and if it contains the lodash dependency you could try to remove the node_modules folder and run following command:

$ npm cache clean    
$ npm install

The first command will clean the npm cache. (just to be sure) The second command will install all (missing) dependencies of the project.

Hope this helps you understand the node package manager a little bit more.

Is it better to use "is" or "==" for number comparison in Python?

>>> 2 == 2.0
True
>>> 2 is 2.0
False

Use ==

Using IF ELSE statement based on Count to execute different Insert statements

As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:

IF EXISTS (SELECT 1 FROM INCIDENTS  WHERE [Some Column] = 'Target Data')
BEGIN
    -- TRUE Procedure
END
ELSE BEGIN
    -- FALSE Procedure
END

How does one convert a grayscale image to RGB in OpenCV (Python)?

I am promoting my comment to an answer:

The easy way is:

You could draw in the original 'frame' itself instead of using gray image.

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Working with Bjarne Stroustrup Programming Principles and Practice Using C++ "FLTK" example i got the same error but after like 1 hour i got an idea, i tracked one of the libs already seen in Project Properties -> Linker -> Input -> Additional Dependencies, in my case i tracked the kernel32.lib to see where was located and saw there were many kernel32.lib's in different folders. So i started copy the FLTK libs in those folders and the last one i tried worked. Visual Studio 2013 Express found the fltkd.lib and the code worked.

In my case the correct route was C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86

I don't know how to set that route inside Visual Studio.

Not sure if that Windows kits folder was created when i installed Microsoft Windows SDK for Windows 7 and .NET Framework 4 (ISO) http://www.microsoft.com/en-us/download/details.aspx?id=8442

Hope that helps you people.

How to integrate sourcetree for gitlab

This worked for me,

Step 1: Click on + New Repository> Clone from URL

Step 2: In Source URL provide URL followed by your user name,

Example:

  • GitLab Repo URL : http://git.zaid-labs.info/zaid/iosapp.git
  • GitLab User Name : zaid.pathan

So final URL should be http://[email protected]/zaid/iosapp.git

Note: zaid.pathan@ added before git.

Step 3: Enjoy cloning :).

Hosting a Maven repository on github

Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

add this to your build section

     <extensions>
        <extension>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <groupId>org.apache.maven.wagon</groupId>
        <version>2.2</version>
        </extension>
    </extensions>

Add something like this to your distributionManagement section

<repository>
    <id>release.repo</id>
    <url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>

Finally make sure to setup the repository access in your settings.xml

add this to your servers section

    <server>
        <id>release.repo</id>
        <username>xxxx</username>
        <password>xxxx</password>
    </server>

and a definition to your repositories section

            <repository>
                <id>release.repo</id>
                <url>http://repo.jillesvangurp.com/releases</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>

Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Cannot open include file with Visual Studio

If you've tried the other answers and your include file still can't be found, here are some additional debugging steps and sanity-checks:

  • Ensure that you are building to a platform that is supported by your code. (If not, consider removing this platform as a target)
  • Verify that the filename/path is correct. Modify your source code to #include the whole absolute path of the header file instead, and see if the file can be found now. If not, copy-paste the path from your source code into a command line to validate that the file exists at that full path with no typos. Open the header file to ensure you have read access. (Change the source code back when done.)
  • If you've already added the path to Additional Include Directories, try clicking the drop-down combo box for Additional Include Directories, and select <Edit...>. This will show you evaluated values of paths. (If it does not show the correct evaluated values, variables in your path might not be set. Click Macros>> to see variables.) Copy-paste the evaluated path into windows explorer to validate that the path exists.
  • Create a new empty C++ "Windows Console Application" project. Set just the one Include Directory, and #include just the one file in your main.cpp, and see if that builds.

how to get all markers on google-maps-v3

If you mean "how can I get a reference to all markers on a given map" - then I think the answer is "Sorry, you have to do it yourself". I don't think there is any handy "maps.getMarkers()" type function: you have to keep your own references as the points are created:

var allMarkers = [];
....
// Create some markers
for(var i = 0; i < 10; i++) {
    var marker = new google.maps.Marker({...});
    allMarkers.push(marker);
}
...

Then you can loop over the allMarkers array to and do whatever you need to do.

ASP.NET Background image

You can use this if you want to assign a background image on the backend:

divContent.Attributes.Add("style"," background-image:
url('images/icon_stock.gif');");

cmake - find_library - custom library location

The simplest solution may be to add HINTS to each find_* request.

For example:

find_library(CURL_LIBRARY
    NAMES curl curllib libcurl_imp curllib_static
    HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)

For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR variable to point to your Boost libraries.

Using .text() to retrieve only text not nested in child tags

I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

Code provided for easy reference:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

How to select following sibling/xml tag using xpath

Try the following-sibling axis (following-sibling::td).

JavaScript: function returning an object

In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.

As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.

var player = makeGamePlayer("John Smith", 15, 3);

The code above calls function makeGamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function makeGamePlayer(name, totalScore, gamesPlayed) {
  // Define desired object
  var obj = {
    name:  name,
    totalScore: totalScore,
    gamesPlayed: gamesPlayed
  };
  // Return it
  return obj;
}

Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this inside the function. In the case above, since makeGamePlayer is not called as a method, the this value will be the global object in sloppy mode, or undefined in strict mode.

As constructors, you can use the new operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:

  1. Creates a new object which inherits from the .prototype of the constructor
  2. Calls the constructor passing this object as the this value
  3. It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
var player = new GamePlayer("John Smith", 15, 3);

The code above creates an instance of GamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function GamePlayer(name,totalScore,gamesPlayed) {
  // `this` is the instance which is currently being created
  this.name =  name;
  this.totalScore = totalScore;
  this.gamesPlayed = gamesPlayed;
  // No need to return, but you can use `return this;` if you want
}

By convention, constructor names begin with an uppercase letter.

The advantage of using constructors is that the instances inherit from GamePlayer.prototype. Then, you can define properties there and make them available in all instances

What does the arrow operator, '->', do in Java?

That's part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here's a link to one. Basically, the -> separates the parameters (left-side) from the implementation (right side).

The general syntax for using lambda expressions is

(Parameters) -> { Body } where the -> separates parameters and lambda expression body.

The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

How to ssh from within a bash script?

If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN

Swap two items in List<T>

List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.

your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.

Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

How to use a table type in a SELECT FROM statement?

In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

create type exch_row as object (
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);

create type exch_tbl as table of exch_row;

And then you can use it in SQL with TABLE operator, for example:

declare
   l_row     exch_row;
   exch_rt   exch_tbl;
begin
   l_row := exch_row('PLN', 100, 100);
   exch_rt  := exch_tbl(l_row);

   for r in (select i.*
               from item i, TABLE(exch_rt) rt
              where i.currency = rt.currency_cd) loop
      -- your code here
   end loop;
end;
/

Get the current date in java.sql.Date format

In order to get "the current date" (as in today's date), you can use LocalDate.now() and pass that into the java.sql.Date method valueOf(LocalDate).

import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());

Field 'browser' doesn't contain a valid alias configuration

In my case it was a package that was installed as a dependency in package.json with a relative path like this:

"dependencies": {
  ...
  "phoenix_html": "file:../deps/phoenix_html"
},

and imported in js/app.js with import "phoenix_html"

This had worked but after an update of node, npm, etc... it failed with the above error-message.

Changing the import line to import "../../deps/phoenix_html" fixed it.

Rename computer and join to domain in one step with PowerShell

I was able to accomplish both tasks with one reboot using the following method and it worked with the following JoinDomainOrWorkGroup flags. This was a new build and using Windows 2008 R2 Enterprise. I verified that it does create the computer account as well in AD with the new name.

1 (0x1) Default. Joins a computer to a domain. If this value is not specified, the join is a computer to a workgroup

32 (0x20) Allows a join to a new domain, even if the computer is already joined to a domain

$comp=gwmi win32_computersystem
$cred=get-credential
$newname="*newcomputername*"
$domain="*domainname*"
$OU="OU=Servers, DC=domain, DC=Domain, DC=com"
$comp.JoinDomainOrWorkGroup($domain ,($cred.getnetworkcredential()).password, $cred.username, $OU, 33)
$comp.rename($newname,$cred.getnetworkcredential()).password,$cred.username)

Find the last time table was updated

To persist audit data regarding data modifications, you will need to implement a DML Trigger on each table that you are interested in. You will need to create an Audit table, and add code to your triggers to write to this table.

For more details on how to implement DML triggers, refer to this MDSN article http://msdn.microsoft.com/en-us/library/ms191524%28v=sql.105%29.aspx

Windows 10 SSH keys

Warning: If you are saving your keys under C:/User/username/.ssh ( the default place), make sure to back up your keys somewhere (eg your password manager).

After the most recent Windows 10 Update (version 1607), my .ssh folder was empty. This is where my keys have always been, but Windows decided to delete them when updating.

Thankfully I had backed up my keys... But... I bet some people will be reverting their PC's today.

mysql_fetch_array() expects parameter 1 to be resource problem

Make sure that your query ran successfully and you got the results. You can check like this:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());


if (is_resource($result))
{
   // your while loop and fetch array function here....
}

Removing the title text of an iOS UIBarButtonItem

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefaultPrompt];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(10.0, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                               NSFontAttributeName:[UIFont systemFontOfSize:1]}
                                                    forState:UIControlStateNormal];

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

How to edit .csproj file

in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File" enter image description here

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

Most useful NLog configurations

Apparently, you can now use NLog with Growl for Windows.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <extensions>
        <add assembly="NLog.Targets.GrowlNotify" />
    </extensions>

    <targets>
        <target name="growl" type="GrowlNotify" password="" host="" port="" />
    </targets>

    <rules>
        <logger name="*" minLevel="Trace" appendTo="growl"/>
    </rules>

</nlog>

NLog with Growl for Windows NLog trace message with Growl for Windows NLog debug message with Growl for Windows NLog info message with Growl for Windows NLog warn message with Growl for Windows NLog error message with Growl for Windows NLog fatal message with Growl for Windows

How to make Firefox headless programmatically in Selenium with Python?

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()

There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don't set it at all.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

or

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

C++ deprecated conversion from string constant to 'char*'

I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Resize height with Highcharts

According to the API Reference:

By default the height is calculated from the offset height of the containing element. Defaults to null.

So, you can control it's height according to the parent div using redraw event, which is called when it changes it's size.

References

Executing Javascript code "on the spot" in Chrome?

You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Use Set in Python

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

Iterate over object attributes in python

Assuming you have a class such as

>>> class Cls(object):
...     foo = 1
...     bar = 'hello'
...     def func(self):
...         return 'call me'
...
>>> obj = Cls()

calling dir on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.

>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']

You can always filter out the special methods by using a list comprehension.

>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']

or if you prefer map/filters.

>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']

If you want to filter out the methods, you can use the builtin callable as a check.

>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']

You could also inspect the difference between your class and its instance object using.

>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])

How to style dt and dd so they are on the same line?

Here is one possible flex-based solution (SCSS):

dl {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  dt {
    width: 150px;
  }
  dd {
    margin: 0;
    flex: 1 0 calc(100% - 150px);
  }
}

that works for the following HTML (pug)

dl
  dt item 1
  dd desc 1
  dt item 2
  dd desc 2

How can I pass some data from one controller to another peer controller

Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    });

Setting HttpContext.Current.Session in a unit test

Never mock.. never! The solution is pretty simple. Why fake such a beautiful creation like HttpContext?

Push the session down! (Just this line is enough for most of us to understand but explained in detail below)

(string)HttpContext.Current.Session["CustomerId"]; is how we access it now. Change this to

_customObject.SessionProperty("CustomerId")

When called from test, _customObject uses alternative store (DB or cloud key value[ http://www.kvstore.io/] )

But when called from the real application, _customObject uses Session.

how is this done? well... Dependency Injection!

So test can set the session(underground) and then call the application method as if it knows nothing about the session. Then test secretly checks if the application code correctly updated the session. Or if the application behaves based on the session value set by the test.

Actually, we did end up mocking even though I said: "never mock". Becuase we couldn't help but slip to the next rule, "mock where it hurts the least!". Mocking huge HttpContext or mocking a tiny session, which hurts the least? don't ask me where these rules came from. Let us just say common sense. Here is an interesting read on not mocking as unit test can kills us

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How do I wrap text in a pre tag?

You can either:

pre { white-space: normal; }

to maintain the monospace font but add word-wrap, or:

pre { overflow: auto; }

which will allow a fixed size with horizontal scrolling for long lines.

Why is sed not recognizing \t as a tab?

I think others have clarified this adequately for other approaches (sed, AWK, etc.). However, my bash-specific answers (tested on macOS High Sierra and CentOS 6/7) follow.

1) If OP wanted to use a search-and-replace method similar to what they originally proposed, then I would suggest using perl for this, as follows. Notes: backslashes before parentheses for regex shouldn't be necessary, and this code line reflects how $1 is better to use than \1 with perl substitution operator (e.g. per Perl 5 documentation).

perl -pe 's/(.*)/\t$1/' $filename > $sedTmpFile && mv $sedTmpFile $filename

2) However, as pointed out by ghostdog74, since the desired operation is actually to simply add a tab at the start of each line before changing the tmp file to the input/target file ($filename), I would recommend perl again but with the following modification(s):

perl -pe 's/^/\t/' $filename > $sedTmpFile && mv $sedTmpFile $filename
## OR
perl -pe $'s/^/\t/' $filename > $sedTmpFile && mv $sedTmpFile $filename

3) Of course, the tmp file is superfluous, so it's better to just do everything 'in place' (adding -i flag) and simplify things to a more elegant one-liner with

perl -i -pe $'s/^/\t/' $filename

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

MySQL Workbench - Connect to a Localhost

if you are using localhost database, try port 3306

How do I turn a C# object into a JSON string in .NET?

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}

Inserting records into a MySQL table using Java

This should work for any table, instead of hard-coding the columns.

_x000D_
_x000D_
//Source details_x000D_
    String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
    String sourceUserName = "src";_x000D_
    String sourcePassword = "***";_x000D_
_x000D_
    // Destination details_x000D_
    String destinationUserName = "dest";_x000D_
    String destinationPassword = "***";_x000D_
    String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
_x000D_
    Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
    Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
_x000D_
    PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");_x000D_
    ResultSet rs = sourceStatement.executeQuery();_x000D_
    rs.setFetchSize(1000); // not needed_x000D_
_x000D_
_x000D_
    ResultSetMetaData meta = rs.getMetaData();_x000D_
_x000D_
_x000D_
_x000D_
    List<String> columns = new ArrayList<>();_x000D_
    for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
        columns.add(meta.getColumnName(i));_x000D_
_x000D_
    try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
            "INSERT INTO dest_table ("_x000D_
                    + columns.stream().collect(Collectors.joining(", "))_x000D_
                    + ") VALUES ("_x000D_
                    + columns.stream().map(c -> "?").collect(Collectors.joining(", "))_x000D_
                    + ")"_x000D_
            )_x000D_
    )_x000D_
    {_x000D_
        int count = 0;_x000D_
        while (rs.next()) {_x000D_
            for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
                destStatement.setObject(i, rs.getObject(i));_x000D_
            }_x000D_
            _x000D_
            destStatement.addBatch();_x000D_
            count++;_x000D_
        }_x000D_
        destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
        System.out.println("done " + count);_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

npm install error from the terminal

npm install -d --save worked for me. -d flag command force npm to install your dependencies and --save will save the all updated dependencies in your package.json

MVC 4 Edit modal form using Bootstrap

I prefer to avoid using Ajax.BeginForm helper and do an Ajax call with JQuery. In my experience it is easier to maintain code written like this. So below are the details:

Models

public class ManagePeopleModel
{
    public List<PersonModel> People { get; set; }
    ... any other properties
}

public class PersonModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    ... any other properties
}

Parent View

This view contains the following things:

  • records of people to iterate through
  • an empty div that will be populated with a modal when a Person needs to be edited
  • some JavaScript handling all ajax calls
@model ManagePeopleModel

<h1>Manage People</h1>

@using(var table = Html.Bootstrap().Begin(new Table()))
{
    foreach(var person in Model.People)
    {
        <tr>
            <td>@person.Id</td>
            <td>@Person.Name</td>
            <td>@person.Age</td>
            <td>@html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal")</td>
        </tr>
    }
}

@using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person")))
{

}

@section Scripts
{
    <script type="text/javascript">
        // Handle "Edit Person" button click.
        // This will make an ajax call, get information for person,
        // put it all in the modal and display it
        $(document).on('click', '.btn-trigger-modal', function(){
            var personId = $(this).data('id');
            $.ajax({
                url: '/[WhateverControllerName]/GetPersonInfo',
                type: 'GET',
                data: { id: personId },
                success: function(data){
                    var m = $('#modal-person');
                    m.find('.modal-content').html(data);
                    m.modal('show');
                }
            });
        });

        // Handle submitting of new information for Person.
        // This will attempt to save new info
        // If save was successful, it will close the Modal and reload page to see updated info
        // Otherwise it will only reload contents of the Modal
        $(document).on('click', '#btn-person-submit', function() {
            var self = $(this);
            $.ajax({
                url: '/[WhateverControllerName]/UpdatePersonInfo',
                type: 'POST',
                data: self.closest('form').serialize(),
                success: function(data) {
                    if(data.success == true) {
                        $('#modal-person').modal('hide');
                        location.reload(false)
                    } else {
                        $('#modal-person').html(data);
                    }
                }
            });
        });
    </script>
}

Partial View

This view contains a modal that will be populated with information about person.

@model PersonModel
@{
    // get modal helper
    var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
}

@modal.Header("Edit Person")
@using (var f = Html.Bootstrap.Begin(new Form()))
{
    using (modal.BeginBody())
    {
        @Html.HiddenFor(x => x.Id)
        @f.ControlGroup().TextBoxFor(x => x.Name)
        @f.ControlGroup().TextBoxFor(x => x.Age)
    }
    using (modal.BeginFooter())
    {
        // if needed, add here @Html.Bootstrap().ValidationSummary()
        @:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
        @Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
    }
}

Controller Actions

public ActionResult GetPersonInfo(int id)
{
    var model = db.GetPerson(id); // get your person however you need
    return PartialView("[Partial View Name]", model)
}

public ActionResult UpdatePersonInfo(PersonModel model)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model); // update person however you need
        return Json(new { success = true });
    }
    // else
    return PartialView("[Partial View Name]", model);
}

COUNT / GROUP BY with active record?

This code counts rows with date range:

Controller:

$this->load->model("YourModelName");
$data ['query'] = $this->YourModelName->get_report();

Model:

  public function get_report()
     {   
       $query = $this->db->query("SELECT  *
FROM   reservation WHERE arvdate <= '2016-7-20' AND  dptrdate >= '2016-10-25' ");
       return $query;
     }

where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.

View:

<?php
 echo $query->num_rows();
?>

This code is to return number of rows. To return table data, then use

$query->rows();
return $row->table_column_name;

How do you properly use WideCharToMultiByte

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

Create line after text with css

You could achieve this with an extra <span>:

HTML

<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

CSS

h2 {
    position: relative;
}

h2 span {
    background-color: white;
    padding-right: 10px;
}

h2:after {
    content:"";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 0.5em;
    border-top: 1px solid black;
    z-index: -1;
}

http://jsfiddle.net/myajouri/pkm5r/

Another solution without the extra <span> but requires an overflow: hidden on the <h2>:

h2 {
    overflow: hidden;
}

h2:after {
    content:"";
    display: inline-block;
    height: 0.5em;
    vertical-align: bottom;
    width: 100%;
    margin-right: -100%;
    margin-left: 10px;
    border-top: 1px solid black;
}

http://jsfiddle.net/myajouri/h2JRj/

How to add a ListView to a Column in Flutter?

I have SingleChildScrollView as a parent, and one Column Widget and then List View Widget as last child.

Adding these properties in List View Worked for me.

  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  scrollDirection: Axis.vertical,

How to Convert unsigned char* to std::string in C++?

BYTE is nothing but typedef unsigned char BYTE;

You can easily use any of below constructors

string ( const char * s, size_t n );
string ( const char * s );

How to get input text value from inside td

Maybe this will help.

var inputVal = $(this).closest('tr').find("td:eq(x) input").val();

AngularJS - Multiple ng-view in single template

You can have just one ng-view.

You can change its content in several ways: ng-include, ng-switch or mapping different controllers and templates through the routeProvider.

Loop code for each file in a directory

Looks for the function glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

PHP: How do I display the contents of a textfile on my page?

I had to use nl2br to display the carriage returns correctly and it worked for me:

<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>

Invert match with regexp

You can also do this (in python) by using re.split, and splitting based on your regular expression, thus returning all the parts that don't match the regex, splitting based on what doesn't match a regularexpression

Rendering HTML in a WebView with custom CSS

You could use WebView.loadDataWithBaseURL

htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData;
// lets assume we have /assets/style.css file
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

And only after that WebView will be able to find and use css-files from the assets directory.

ps And, yes, if you load your html-file form the assets folder, you don't need to specify a base url.

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

How to find Control in TemplateField of GridView?

Try with below code.

Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.

<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
    OnRowDataBound="mainGrid_RowDataBound"  EmptyDataText="No Data Found.">
    <Columns>
        <asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
                <asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
                <a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
                <input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Handling RowDataBound event,

protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblName = (Label)e.Row.FindControl("lblName");
        LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
        HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
        HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
    }
}

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

compare two files in UNIX

Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)

Best way to find if an item is in a JavaScript array?

First, implement indexOf in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras (also, the associated blog post). And then you can use indexOf without worrying about browser support. Here's a slightly optimised version of his indexOf implementation:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var i = -1, j = arr.length; ++i < j;)
            if(arr[i] === obj) return true;
        return false;
    };

I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

How to change Bootstrap's global default font size?

Add !importent in your css

* {
   font-size: 16px !importent;
   line-height: 2;
}

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

Read each line of txt file to new array element

This has been covered here quite well, but if you REALLY need even better performance than anything listed here, you can use this approach that uses strtok.

$Names_Keys = [];
$Name = strtok(file_get_contents($file), "\n");
while ($Name !== false) {
    $Names_Keys[$Name] = 0;
    $Name = strtok("\n");
}

Note, this assumes your file is saved with \n as the newline character (you can update that as need be), and it also stores the words/names/lines as the array keys instead of the values, so that you can use it as a lookup table, allowing the use of isset (much, much faster), instead of in_array.

Getting View's coordinates relative to the root layout

Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.

    int pos[] = new int[2];
    view.getLocationOnScreen(pos);
    int centerX = pos[0] + view.getMeasuredWidth() / 2;
    int centerY = pos[1] + view.getMeasuredHeight() / 2;

How to count frequency of characters in a string?

This is more Effective way to count frequency of characters in a string

public class demo {
    public static void main(String[] args) {
        String s = "babdcwertyuiuygf";
        Map<Character, Integer> map = new TreeMap<>();
        s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
        StringBuffer myValue = new StringBuffer();
        String myMapKeyValue = "";
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            myMapKeyValue = Character.toString(entry.getKey()).concat(
                Integer.toString(entry.getValue()));
            myValue.append(myMapKeyValue);
        }
        System.out.println(myValue);
    }
}

Spring Boot @autowired does not work, classes in different package

Try annotating your Configuration Class(es) with the @ComponentScan("com.esri.birthdays") annotation. Generally spoken: If you have sub-packages in your project, then you have to scan for your relevant classes on project-root. I guess for your case it'll be "com.esri.birthdays". You won't need the ComponentScan, if you have no sub-packaging in your project.

Use CSS to make a span not clickable

Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:

<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

You can then style it so that it looks un-clickable too:

<html>
<head>
     <style type='text/css'>
     a span.unclickable  { text-decoration: none; }
     a span.unclickable:hover { cursor: default; }
     </style>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span class='unclickable' onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Text inset for UITextField?

Swift 5 version of Christopher's answer with extra usage sample

import UIKit

private class InsetTextField: UITextField {
    var insets: UIEdgeInsets

    init(insets: UIEdgeInsets) {
        self.insets = insets
        super.init(frame: .zero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("not intended for use from a NIB")
    }

    // placeholder position
    override func textRect(forBounds bounds: CGRect) -> CGRect {
         return super.textRect(forBounds: bounds.inset(by: insets))
    }
 
    // text position
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
         return super.editingRect(forBounds: bounds.inset(by: insets))
    }
}

extension UITextField {

    class func textFieldWithInsets(insets: UIEdgeInsets) -> UITextField {
        return InsetTextField(insets: insets)
    }

}

Usage: -

class ViewController: UIViewController {

  private let passwordTextField: UITextField = {

        let textField = UITextField.textFieldWithInsets(insets: UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15))
     // ---
   
        return textField
    }()

}

Passing argument to alias in bash

This is the solution which can avoid using function:

alias addone='{ num=$(cat -); echo "input: $num"; echo "result:$(($num+1))"; }<<<'

test result

addone 200
input: 200
result:201

Remove an array element and shift the remaining ones

Programming Hub randomly provided a code snippet which in fact does reduce the length of an array

for (i = position_to_remove; i < length_of_array; ++i) {
        inputarray[i] = inputarray[i + 1];
}

Not sure if it's behaviour that was added only later. It does the trick though.

INSERT with SELECT

We all know this works.

INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT  `col-1`,`col-2` 

===========================
Below method can be used in case of multiple "select" statements. Just for information.

INSERT INTO `TableName`(`col-1`,`col-2`)
 select 1,2  union all
 select 1,2   union all
 select 1,2 ;

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

How do I draw a circle in iOS Swift?

Make a class UIView and assign it this code for a simple circle

import UIKit
@IBDesignable
class DRAW: UIView {

    override func draw(_ rect: CGRect) {

        var path = UIBezierPath()
        path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100))
        UIColor.yellow.setStroke()
        UIColor.red.setFill()
        path.lineWidth = 5
        path.stroke()
        path.fill()


    }


}

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Git Stash vs Shelve in IntelliJ IDEA

Shelf is a JetBrains feature while Stash is a Git feature for same work. You can switch to different branch without commit and loss of work using either of features. My personal experience is to use Shelf.

maxReceivedMessageSize and maxBufferSize in app.config

binding name="BindingName" 
maxReceivedMessageSize="2097152" 
maxBufferSize="2097152" 
maxBufferPoolSize="2097152" 

on client side and server side

Recursively find files with a specific extension

Using bash globbing (if find is not a must)

ls Robert.{pdf,jpg} 

Set background image according to screen resolution

I've had this same issue but have now found the resolution for it.

The trick is to create a wallpaper image of 1920*1200. When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.

Hope this helps you all

not None test in Python

if val is not None:
    # ...

is the Pythonic idiom for testing that a variable is not set to None. This idiom has particular uses in the case of declaring keyword functions with default parameters. is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program, is is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".

As for why this is preferred to

if not (val is None):
    # ...

this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.

How to implement HorizontalScrollView like Gallery?

You may use HorizontalScrollView to implement Horizontal scrolling.

Code

<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
 android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
    android:id="@+id/innerLay"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

featured.xml:

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="160dp"
   android:layout_margin="4dp"
android:layout_height="match_parent"
android:orientation="vertical" >

      <RelativeLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
>

<ProgressBar                
    android:layout_width="15dip"       
    android:layout_height="15dip"
    android:id="@+id/progress" 
    android:layout_centerInParent="true"
    />

<ImageView
    android:id="@+id/image"       
    android:layout_width="fill_parent"       
    android:layout_height="fill_parent"
    android:background="#20000000"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:gravity="center"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Java Code:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Note: to implement lazy loading, please use this link for AQUERY

https://code.google.com/p/android-query/wiki/ImageLoading

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

How to programmatically round corners and set random background colors

You can dynamically change color of any items ( layout, textview ) . Try below code to set color programmatically in layout

in activity.java file


String quote_bg_color = "#FFC107"
quoteContainer= (LinearLayout)view.findViewById(R.id.id_quotecontainer);
quoteContainer.setBackgroundResource(R.drawable.layout_round);
GradientDrawable drawable = (GradientDrawable) quoteContainer.getBackground();
drawable.setColor(Color.parseColor(quote_bg_color));

create layout_round.xml in drawable folder

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimaryLight"/>
    <stroke android:width="0dp" android:color="#B1BCBE" />
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>

layout in activity.xml file

<LinearLayout
        android:id="@+id/id_quotecontainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

----other components---

</LinearLayout>


How to insert &nbsp; in XSLT

In addition to victor hugo's answer it is possible to get all known character references legal in an XSLT file, like this:

<!DOCTYPE stylesheet [
  <!ENTITY % w3centities-f PUBLIC "-//W3C//ENTITIES Combined Set//EN//XML"
      "http://www.w3.org/2003/entities/2007/w3centities-f.ent">
  %w3centities-f;
]>
...
<xsl:text>&amp; &nbsp; &ndash;</xsl:text>

There is also certain difference in the result of this approach as compared to <xsl:text disable-output-escaping="yes"> one. The latter is going to produce string literals like &nbsp; for all kinds of output, even for <xsl:output method="text">, and this may happen to be different from what you might wish... On the contrary, getting entities defined for XSLT template via <!DOCTYPE ... <!ENTITY ... will always produce output consistent with your xsl:output settings.

And when including all character references, it may be wise to use a local entity resolver to keep the XSLT engine from fetching character entity definitions from the Internet. JAXP or explicit Xalan-J users may need a patch for Xalan-J to use the resolver correctly. See my blog XSLT, entities, Java, Xalan... for patch download and comments.

Difference between "and" and && in Ruby?

and has lower precedence, mostly we use it as a control-flow modifier such as if:

next if widget = widgets.pop

becomes

widget = widgets.pop and next

For or:

raise "Not ready!" unless ready_to_rock?

becomes

ready_to_rock? or raise "Not ready!"

I prefer to use if but not and, because if is more intelligible, so I just ignore and and or.

Refer to "Using “and” and “or” in Ruby" for more information.

How to convert date to timestamp?

The below code will convert the current date into the timestamp.

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

Truncating Text in PHP?

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

how to get right offset of an element? - jQuery

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));

TypeError: 'str' object cannot be interpreted as an integer

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)

This outputs:

i have uploaded the output with the code

C function that counts lines in file

Here is my function

char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);

void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
    ch = fgetc(myfile);
    if(ch == '\n')
        number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
    number_of_lines++;
fclose(myfile);
printf("number of lines in  %s   = %d",filename, number_of_lines);

}

Best way to compare 2 XML documents in Java

I'm using Altova DiffDog which has options to compare XML files structurally (ignoring string data).

This means that (if checking the 'ignore text' option):

<foo a="xxx" b="xxx">xxx</foo>

and

<foo b="yyy" a="yyy">yyy</foo> 

are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!

How to detect when a UIScrollView has finished scrolling

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    scrollingFinished(scrollView: scrollView)
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if decelerate {
        //didEndDecelerating will be called for sure
        return
    }
    scrollingFinished(scrollView: scrollView)        
}

func scrollingFinished(scrollView: UIScrollView) {
   // Your code
}

Find duplicate records in a table using SQL Server

Select * from dbo.sales group by shoppername having(count(Item) > 1)

What is the best way to ensure only one instance of a Bash script is running?

Advisory locking has been used for ages and it can be used in bash scripts. I prefer simple flock (from util-linux[-ng]) over lockfile (from procmail). And always remember about a trap on exit (sigspec == EXIT or 0, trapping specific signals is superfluous) in those scripts.

In 2009 I released my lockable script boilerplate (originally available at my wiki page, nowadays available as gist). Transforming that into one-instance-per-user is trivial. Using it you can also easily write scripts for other scenarios requiring some locking or synchronization.

Here is the mentioned boilerplate for your convenience.

#!/bin/bash
# SPDX-License-Identifier: MIT

## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
##
## This script is licensed under the terms of the MIT license.
## https://opensource.org/licenses/MIT
#
# Lockable script boilerplate

### HEADER ###

LOCKFILE="/var/lock/`basename $0`"
LOCKFD=99

# PRIVATE
_lock()             { flock -$1 $LOCKFD; }
_no_more_locking()  { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking()  { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }

# ON START
_prepare_locking

# PUBLIC
exlock_now()        { _lock xn; }  # obtain an exclusive lock immediately or fail
exlock()            { _lock x; }   # obtain an exclusive lock
shlock()            { _lock s; }   # obtain a shared lock
unlock()            { _lock u; }   # drop a lock

### BEGIN OF SCRIPT ###

# Simplest example is avoiding running multiple instances of script.
exlock_now || exit 1

# Remember! Lock file is removed when one of the scripts exits and it is
#           the only script holding the lock or lock is not acquired at all.

How to get first object out from List<Object> using Linq

Try:

var firstElement = lstComp.First();

You can also use FirstOrDefault() just in case lstComp does not contain any items.

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

Edit:

To get the Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");

This would assume there is an element in lstComp. An alternative and safer way would be...

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

I use this:

@var.respond_to?(:keys)

It works for Hash and ActiveSupport::HashWithIndifferentAccess.

Running a Python script from PHP

This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:

sh: blabla.py: command not found

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

$command = escapeshellcmd('python blabla.py');

Corrupt jar file

It can be something so silly as you are transferring the file via FTP to a target machine, you go and run the .JAR file but this was so big that it has not yet been finished transferred :) Yes it happened to me..

PHP array delete by value (not key)

One interesting way is by using array_keys():

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

In my case, I had to do this

 // Initialization in the dom
 // Consider the muted attribute
 <audio id="notification" src="path/to/sound.mp3" muted></audio>


 // in the js code unmute the audio once the event happened
 document.getElementById('notification').muted = false;
 document.getElementById('notification').play();

Connect Android Studio with SVN

In Android Studio we can get the repositories of svn using the VCS->Subversion and the extract the repository and work on the code

How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

Accessing certain pixel RGB value in openCV

Try the following:

cv::Mat image = ...do some stuff...;

image.at<cv::Vec3b>(y,x); gives you the RGB (it might be ordered as BGR) vector of type cv::Vec3b

image.at<cv::Vec3b>(y,x)[0] = newval[0];
image.at<cv::Vec3b>(y,x)[1] = newval[1];
image.at<cv::Vec3b>(y,x)[2] = newval[2];

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I was in the same boat. Installed Eclipse, realized need CDT.

sudo apt-get install eclipse eclipse-cdt g++

This just adds the CDT package on top of existing installation - no un-installation etc. required.

Are there such things as variables within an Excel formula?

Now you can use the function LET to declare variables within Excel formulas. This function is available since Jun 2020 for Microsoft 365 users.

Given your example, the formula will be:

=LET(MyFunc,VLOOKUP(A1,B:B,1,0), IF(MyFunc > 10, MyFunc - 10, MyFunc ) )

The 1st argument is the variable name and the 2nd argument is the function or range. You can add more pairs of arguments variable, function/range.

After adding the variables, the last argument will be your formula of interest -- calling the variables you just created.

For more information, please access the Microsoft webpage here.

How to round up a number to nearest 10?

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10;

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.

Are static class variables possible in Python?

The best way I found is to use another class. You can create an object and then use it on other objects.

class staticFlag:
    def __init__(self):
        self.__success = False
    def isSuccess(self):
        return self.__success
    def succeed(self):
        self.__success = True

class tryIt:
    def __init__(self, staticFlag):
        self.isSuccess = staticFlag.isSuccess
        self.succeed = staticFlag.succeed

tryArr = []
flag = staticFlag()
for i in range(10):
    tryArr.append(tryIt(flag))
    if i == 5:
        tryArr[i].succeed()
    print tryArr[i].isSuccess()

With the example above, I made a class named staticFlag.

This class should present the static var __success (Private Static Var).

tryIt class represented the regular class we need to use.

Now I made an object for one flag (staticFlag). This flag will be sent as reference to all the regular objects.

All these objects are being added to the list tryArr.


This Script Results:

False
False
False
False
False
True
True
True
True
True

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

elasticsearch bool query combine must with OR

$filterQuery = $this->queryFactory->create(QueryInterface::TYPE_BOOL, ['must' => $queries,'should'=>$queriesGeo]);

In must you need to add the query condition array which you want to work with AND and in should you need to add the query condition which you want to work with OR.

You can check this: https://github.com/Smile-SA/elasticsuite/issues/972

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

Best practices for SQL varchar column length

The best value is the one that is right for the data as defined in the underlying domain.

For some domains, VARCHAR(10) is right for the Name attribute, for other domains VARCHAR(255) might be the best choice.

HttpServletRequest to complete URL

You can use filter .

@Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
            HttpServletRequest test1=    (HttpServletRequest) arg0;

         test1.getRequestURL()); it gives  http://localhost:8081/applicationName/menu/index.action
         test1.getRequestURI()); it gives applicationName/menu/index.action
         String pathname = test1.getServletPath()); it gives //menu/index.action


        if(pathname.equals("//menu/index.action")){ 
            arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method


            // in resposne 
           HttpServletResponse httpResp = (HttpServletResponse) arg1;
           RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");     
           rd.forward(arg0, arg1);





    }

donot forget to put <dispatcher>FORWARD</dispatcher> in filter mapping in web.xml

Which .NET Dependency Injection frameworks are worth looking into?

It depends on what you are looking for, as they each have their pros and cons.

  1. Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
  2. Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
  3. Structure Map has very rich and fine grained configuration through an internal DSL.
  4. Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
  5. Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
  6. The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.

So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.

App not setup: This app is still in development mode

2021 UPDATE

I have done successfully Login with Facebook by doing below things. Now it is working fine.

As per described by George Mano

Visit Facebook Apps Page and select your application.

Go to Settings -> Basic.

Add a 1 Contact Email, 2 Privacy Policy URL, 3 User Data Deletion and choose 4 Category and Last 5. Live your application

The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

The General Data Protection Regulation (GDPR) requires developers to provide a way for people to request that their data be deleted. To be compliant with these requirements, you must provide either a data deletion request callback or instructions to inform people how to delete their data from your app or website

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

Ansible: copy a directory content to another directory

EDIT: This solution worked when the question was posted. Later Ansible deprecated recursive copying with remote_src

Ansible Copy module by default copies files/dirs from control machine to remote machine. If you want to copy files/dirs in remote machine and if you have Ansible 2.0, set remote_src to yes

- name: copy html file
  copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/ remote_src=yes directory_mode=yes

Getting all types that implement an interface

Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.

Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.

public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
    List<Type> list = new List<Type>();
    IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
    while (enumerator.MoveNext()) {
        try {
            Type[] types = ((Assembly) enumerator.Current).GetTypes();
            if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
                IEnumerator enumerator2 = types.GetEnumerator();
                while (enumerator2.MoveNext()) {
                    Type current = (Type) enumerator2.Current;
                    if (type.IsInterface) {
                        if (current.GetInterface(type.FullName) != null) {
                            list.Add(current);
                        }
                    } else if (current.IsSubclassOf(type)) {
                        list.Add(current);
                    }
                }
            }
        } catch {
        }
    }
    return list;
}

It's not pretty, I'll admit.

Why functional languages?

A point missed in the discussion is that the best type systems are found in contemporary FP languages. What's more, compilers can infer all (or at least most) types automatically.

It is interesting that one spends half the time writing type names when programming Java, yet Java is by far not type safe. While you may never write types in a Haskell programm (except as a kind of compiler checked documentation) and the code is 100% type safe.

What special characters must be escaped in regular expressions?

POSIX recognizes multiple variations on regular expressions - basic regular expressions (BRE) and extended regular expressions (ERE). And even then, there are quirks because of the historical implementations of the utilities standardized by POSIX.

There isn't a simple rule for when to use which notation, or even which notation a given command uses.

Check out Jeff Friedl's Mastering Regular Expressions book.

Create an instance of a class from a string

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Now if you want to call a parameterized constructor do the following

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of

Activator.CreateInstance(t);

Refresh Excel VBA Function Results

Public Sub UpdateMyFunctions()
    Dim myRange As Range
    Dim rng As Range

    'Considering The Functions are in Range A1:B10
    Set myRange = ActiveSheet.Range("A1:B10")

    For Each rng In myRange
        rng.Formula = rng.Formula
    Next
End Sub

MySQL parameterized queries

You have a few options available. You'll want to get comfortable with python's string iterpolation. Which is a term you might have more success searching for in the future when you want to know stuff like this.

Better for queries:

some_dictionary_with_the_data = {
    'name': 'awesome song',
    'artist': 'some band',
    etc...
}
cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%(name)s, %(artist)s, %(album)s, %(genre)s, %(length)s, %(location)s)

        """, some_dictionary_with_the_data)

Considering you probably have all of your data in an object or dictionary already, the second format will suit you better. Also it sucks to have to count "%s" appearances in a string when you have to come back and update this method in a year :)

Is there a TRY CATCH command in Bash

You can use trap:

try { block A } catch { block B } finally { block C }

translates to:

(
  set -Ee
  function _catch {
    block B
    exit 0  # optional; use if you don't want to propagate (rethrow) error to outer shell
  }
  function _finally {
    block C
  }
  trap _catch ERR
  trap _finally EXIT
  block A
)

Setting up redirect in web.config file

You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect. You could then make a rule like this:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Rewrite to Category">
        <match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
        <action type="Rewrite" url="category.aspx?cid={R:2}" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

You have 4 options:

Using a certificate as parameter

$ pip install --cert /path/to/mycertificate.crt linkchecker

Using a certificate in a pip.conf

Create this file:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

and add these lines:

[global]
cert = /path/to/mycertificate.crt

Ignoring certificate and using HTTP

$ pip install --trusted-host pypi.python.org linkchecker

Ignoring certificate and using HTTP in a pip.conf

Create this file:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

and add these lines:

[global]
trusted-host = pypi.python.org

Source

How do you determine a processing time in Python?

Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit's default_timer():

>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds

This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.

ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.

For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.

Get data from fs.readFile

The following is function would work for async wrap or promise then chains

const readFileAsync =  async (path) => fs.readFileSync(path, 'utf8');

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')