Programs & Examples On #Google gears

Gears, formerly Google Gears, was software offered by Google that "enables more powerful web applications, by adding new features to the web browser. It allows some online files to be used offline". Released under the BSD license, Gears is free and open source software.

Dynamically set value of a file input

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

Is there a good jQuery Drag-and-drop file upload plugin?

Check out the recently1 released upload handler from the guys that created the TinyMCE editor. It has a jQuery widget and looks like it has a nice set of features and fallbacks.

http://www.plupload.com/

How does Google calculate my location on a desktop?

I am currently in Tokyo, and I used to be in Switzerland. Yet, my location until some days ago was not pinpinted exactly, except in the broad Tokyo area. Today I tried, and I appear to be in Switzerland. How?

Well the secret is that I am now connected through wireless, and my wireless router has been identified (thanks to association to other wifis around me at that time) in a very accurate area in Switzerland. Now, my wifi moved to Tokyo, but the queried system still thinks the wifi router is in Switzerland, because either it has no information about the additional wifis surrounding me right now, or it cannot sort out the conflicting info (namely, the specific info about my wifi router against my ip geolocation, which pinpoints me in the far east).

So, to answer your question, google, or someone for him, did "wardriving" around, mapping the wifi presence. Every time a query is performed to the system (probably in compliance with the W3C draft for the geolocation API) your computer sends the wifi identifiers it sees, and the system does two things:

  1. queries its database if geolocation exists for some of the wifis you passed, and returns the "wardrived" position if found, eventually with triangulation if intensities are present. The more wifi networks around, the higher is the accuracy of the positioning.
  2. adds additional networks you see that are currently not in the database to their database, so they can be reused later.

As you see, the system builds up by itself. The only thing you need is good seeding. After that, it extends in "50 meters chunks" (the range of a newly found wifi connection).

Of course, if you really want the system go banana, you can start exchanging wifi routers around the globe with fellow revolutionaries of the no-global-positioning movement.

Seconds CountDown Timer

enter image description here .

Usage:

CountDownTimer timer = new CountDownTimer();


//set to 30 mins
timer.SetTime(30,0);     

timer.Start();

//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr; 

// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!"); 

//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch

and don't forget to Dispose(); when timer is useless for you;

Source code:

using System;
using System.Diagnostics;
using System.Windows.Forms;

public class CountDownTimer : IDisposable
{
    public Stopwatch _stpWatch = new Stopwatch();

    public Action TimeChanged;
    public Action CountDownFinished;

    public bool IsRunnign => timer.Enabled;

    public int StepMs
    {
        get => timer.Interval;
        set => timer.Interval = value;
    }

    private Timer timer = new Timer();

    private TimeSpan _max = TimeSpan.FromMilliseconds(30000);

    public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);

    private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;

    public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");

    public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");

    private void TimerTick(object sender, EventArgs e)
    {
        TimeChanged?.Invoke();

        if (_mustStop)
        {
            CountDownFinished?.Invoke();
            _stpWatch.Stop();
            timer.Enabled = false;
        }
    }

    public CountDownTimer(int min, int sec)
    {
        SetTime(min, sec);
        Init();
    }

    public CountDownTimer(TimeSpan ts)
    {
        SetTime(ts);
        Init();
    }

    public CountDownTimer()
    {
        Init();
    }

    private void Init()
    {
        StepMs = 1000;
        timer.Tick += new EventHandler(TimerTick);
    }

    public void SetTime(TimeSpan ts)
    {
        _max = ts;
        TimeChanged?.Invoke();
    }

    public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));

    public void Start() {
        timer.Start();
        _stpWatch.Start();
    }

    public void Pause()
    {
        timer.Stop();
        _stpWatch.Stop();
    }

    public void Stop()
    {
        Reset();
        Pause();
    }

    public void Reset()
    {
        _stpWatch.Reset();
    }

    public void Restart()
    {
        _stpWatch.Reset();
        timer.Start();
    }

    public void Dispose() => timer.Dispose();
}

(updated 6.6.2020, because of problems with time calculation)

How to access the services from RESTful API in my angularjs page?

Welcome to the wonderful world of Angular !!

I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you

There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.

First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.

So, you'll need to add a few lines to your web.config file:

<configuration>
  ... 
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <!-- We need the following 6 lines, to let AngularJS call our REST web services -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        </customHeaders>
    </httpProtocol>
  </system.webServer>
  ... 
</configuration>

Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:

// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Once you have these fixes in place, actually calling a RESTful API is really straightforward.

function YourAngularController($scope, $http) 
{
    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
        .success(function (data) {
        //  
        //  Do something with the data !
        //  
    });
}

You can find a really clear walkthrough of these steps on this webpage:

Using Angular, with JSON data

Good luck !

Mike

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

Store mysql query output into a shell variable

If you have particular database name and a host on which you want the query to be executed then follow below query:

outputofquery=$(mysql -u"$dbusername" -p"$dbpassword" -h"$dbhostname" -e "SELECT A, B, C FROM table_a;" $dbname)

So to run the mysql queries you need to install mysql client on linux

How to keep indent for second line in ordered lists via CSS?

You can set the margin and padding of either an ol or ul in CSS

ol {
margin-left: 0;
padding-left: 3em;
list-style-position: outside;
}

How to sort an array based on the length of each element?

If you want to preserve the order of the element with the same length as the original array, use bubble sort.

Input = ["ab","cdc","abcd","de"];

Output  = ["ab","cd","cdc","abcd"]

Function:

function bubbleSort(strArray){
  const arrayLength = Object.keys(strArray).length;
    var swapp;
    var newLen = arrayLength-1;
    var sortedStrArrByLenght=strArray;
    do {
        swapp = false;
        for (var i=0; i < newLen; i++)
        {
            if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
            {
               var temp = sortedStrArrByLenght[i];
               sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
               sortedStrArrByLenght[i+1] = temp;
               swapp = true;
            }
        }
        newLen--;
    } while (swap);
  return sortedStrArrByLenght;
}

GET and POST methods with the same Action name in the same Controller

Can not multi action same name and same parameter

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(int id)
    {
        return View();
    }

althought int id is not used

Wireshark vs Firebug vs Fiddler - pros and cons?

If you're developing an application that transfers data using AMF (fairly common in a particular set of GIS web APIs I use regularly), Fiddler does not currently provide an AMF decoder that will allow you to easily view the binary data in an easily-readable format. Charles provides this functionality.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

The corruption in this question is isolated to a single substring at the end of the serialized string with was probably manually replaced by someone who lazily wanted to update the image filename. This fact will be apparent in my demonstration link below using the OP's posted data -- in short, C:fakepath100.jpg does not have a length of 19, it should be 17.

Since the serialized string corruption is limited to an incorrect byte/character count number, the following will do a fine job of updating the corrupted string with the correct byte count value.

The following regex based replacement will only be effective in remedying byte counts, nothing more.

It looks like many of the earlier posts are just copy-pasting a regex pattern from someone else. There is no reason to capture the potentially corrupted byte count number if it isn't going to be used in the replacement. Also, adding the s pattern modifier is a reasonable inclusion in case a string value contains newlines/line returns.

*For those that are not aware of the treatment of multibyte characters with serializing, you must not use mb_strlen() in the custom callback because it is the byte count that is stored not the character count, see my output...

Code: (Demo with OP's data) (Demo with arbitrary sample data) (Demo with condition replacing)

$corrupted = <<<STRING
a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";}
STRING;

$repaired = preg_replace_callback(
        '/s:\d+:"(.*?)";/s',
        //  ^^^- matched/consumed but not captured because not used in replacement
        function ($m) {
            return "s:" . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted
    );

echo $corrupted , "\n" , $repaired;
echo "\n---\n";
var_export(unserialize($repaired));

Output:

a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
Newline2";i:3;s:6:"garçon";}
a:4:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
Newline2";i:3;s:7:"garçon";}
---
array (
  0 => 'three',
  1 => 'five',
  2 => 'newline1
Newline2',
  3 => 'garçon',
)

One leg down the rabbit hole... The above works fine even if double quotes occur in a string value, but if a string value contains "; or some other monkeywrenching sbustring, you'll need to go a little further and implement "lookarounds". My new pattern

checks that the leading s is:

  • the start of the entire input string or
  • preceded by ;

and checks that the "; is:

  • at the end of the entire input string or
  • followed by } or
  • followed by a string or integer declaration s: or i:

I haven't test each and every possibility; in fact, I am relatively unfamiliar with all of the possibilities in a serialized string because I never elect to work with serialized data -- always json in modern applications. If there are additional possible leading or trailing characters, leave a comment and I'll extend the lookarounds.

Extended snippet: (Demo)

$corrupted_byte_counts = <<<STRING
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
STRING;

$repaired = preg_replace_callback(
        '/(?<=^|;)s:\d+:"(.*?)";(?=$|}|[si]:)/s',
        //^^^^^^^^--------------^^^^^^^^^^^^^-- some additional validation
        function ($m) {
            return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
        },
        $corrupted_byte_counts
    );

echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired));

Output:

corrupted serialized array:
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
---
repaired serialized array:
a:12:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
newline2";i:3;s:7:"garçon";i:4;s:24:"double " quote \"escaped";i:5;s:7:"a,comma";i:6;s:7:"a:colon";i:7;s:13:"single 'quote";i:8;s:10:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:39:"monkey";wrenching doublequote-semicolon";s:2:"s:";s:10:"val s: val";}
---
Array
(
    [0] => three
    [1] => five
    [2] => newline1
newline2
    [3] => garçon
    [4] => double " quote \"escaped
    [5] => a,comma
    [6] => a:colon
    [7] => single 'quote
    [8] => semi;colon
    [assoc] => yes
    [9] => monkey";wrenching doublequote-semicolon
    [s:] => val s: val
)

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

New self vs. new static

If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    }
    public function create2() {
        return new static();
    }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

The results:

string(1) "B"
string(1) "B"

How do I parse a string with a decimal point to a double?

Here is a solution that handles any number string that many include commas and periods. This solution is particular for money amounts so only the tenths and hundredths place are expected. Anything more is treated as a whole number.

First remove anything that is not a number, comma, period, or negative sign.

string stringAmount = Regex.Replace(originalString, @"[^0-9\.\-,]", "");

Then we split up the number into the whole number and decimal number.

string[] decimalParsed = Regex.Split(stringAmount, @"(?:\.|,)(?=\d{2}$)");

(This Regex expression selects a comma or period that is two numbers from the end of the string.)

Now we take the whole number and strip it of any commas and periods.

string wholeAmount = decimalParsed[0].Replace(",", "").Replace(".", "");

if (wholeAmount.IsNullOrEmpty())
        wholeAmount = "0";

Now we handle the decimal part, if any.

string decimalAmount = "00";

if (decimalParsed.Length == 2)
    {
        decimalAmount = decimalParsed[1];
    }

Finally we can put the whole and decimal together and parse the Double.

double amount = $"{wholeAmount}.{decimalAmount}".ToDouble();

This will handle 200,00, 1 000,00 , 1,000 , 1.000,33 , 2,000.000,78 etc.

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

No connection could be made because the target machine actively refused it?

I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx

I implemented this function almost exactly as written, but what happened is I got this error:

2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080

This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)

private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        // Get host related information.
        hostEntry = Dns.GetHostEntry(server);

        // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
        // an exception that occurs when the host IP Address is not compatible with the address family
        // (typical in the IPv6 case).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!

    private Socket ConnectSocket(string server, int port)
    {
        Socket s = null;

        try
        {
            // Get host related information.
            IPAddress[] ips;
            ips = Dns.GetHostAddresses(server);

            Socket tempSocket = null;
            IPEndPoint ipe = null;

            ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
            tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
            tempSocket.Connect(ipe);

            if (tempSocket.Connected)
            {
                s = tempSocket;
                s.SendTimeout = Coordinate.HL7SendTimeout;
                s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
            }
            else
            {
                return null;
            }

            return s;
        }
        catch (Exception e)
        {
            Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
            Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
            if (g_NoOutputForThreading == false)
                rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
            return null;
        }
    }

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

Ansible: Store command's stdout in new variable?

There's no need to set a fact.

    - shell: cat "hello"
      register: cat_contents

    - shell: echo "I cat hello"
      when: cat_contents.stdout == "hello"

Run two async tasks in parallel and collect results in .NET 4.5

async Task<int> LongTask1() { 
  ...
  return 0; 
}

async Task<int> LongTask2() { 
  ...
  return 1; 
}

...
{
   Task<int> t1 = LongTask1();
   Task<int> t2 = LongTask2();
   await Task.WhenAll(t1,t2);
   //now we have t1.Result and t2.Result
}

Best way to parseDouble with comma as decimal separator?

Use java.text.NumberFormat:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Updated:

To support multi-language apps use:

NumberFormat format = NumberFormat.getInstance(Locale.getDefault());

Check if date is a valid one

How to check if a string is a valid date using Moment, when the date and date format are different

Sorry, but did any of the given solutions on this thread actually answer the question that was asked?

I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.

The following works for me...

const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();

// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.

But honestly, don't understand why moment.isDate()(as documented) only accepts an object. Should also support a string in my opinion.

Altering a column to be nullable

As others have observed, the precise syntax for the command varies across different flavours of DBMS. The syntax you use works in Oracle:

SQL> desc MACAddresses
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COMPUTER                                           NUMBER
 MACADDRESS                                         VARCHAR2(12)
 CORRECTED_MACADDRESS                      NOT NULL VARCHAR2(17)

SQL> alter table MACAddresses
  2       modify corrected_MACAddress null
  3  /

Table altered.

SQL> desc MACAddresses
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COMPUTER                                           NUMBER
 MACADDRESS                                         VARCHAR2(12)
 CORRECTED_MACADDRESS                               VARCHAR2(17)

SQL>

Reversing a String with Recursion in Java

run the following and you'll see what's going on:

public class RS {

    public static String reverse(String str) {
        System.out.println("--- reverse --- " + str);
        if ((null == str) || (str.length() <= 1)) {
            return str;
        }
        return add(reverse(str.substring(1)), charAt(str));
    }

    public static char charAt(String s) {
        System.out.println("--- charAt --- " + s);
        return s.charAt(0);
    }

    public static String add(String s, char c) {
        System.out.println("--- add --- " + s + " - " + c);
        return s + c;
    }

    public static void main(String[] args) {
        System.out.println("start");
        System.out.println("result: " + reverse("hello"));
        System.out.println("end");
    }

}

How to clone an InputStream?

Cloning an input stream might not be a good idea, because this requires deep knowledge about the details of the input stream being cloned. A workaround for this is to create a new input stream that reads from the same source again.

So using some Java 8 features this would look like this:

public class Foo {

    private Supplier<InputStream> inputStreamSupplier;

    public void bar() {
        procesDataThisWay(inputStreamSupplier.get());
        procesDataTheOtherWay(inputStreamSupplier.get());
    }

    private void procesDataThisWay(InputStream) {
        // ...
    }

    private void procesDataTheOtherWay(InputStream) {
        // ...
    }
}

This method has the positive effect that it will reuse code that is already in place - the creation of the input stream encapsulated in inputStreamSupplier. And there is no need to maintain a second code path for the cloning of the stream.

On the other hand, if reading from the stream is expensive (because a it's done over a low bandwith connection), then this method will double the costs. This could be circumvented by using a specific supplier that will store the stream content locally first and provide an InputStream for that now local resource.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Ajax call Into MVC Controller- Url Issue

In order for this to work that Javascript must be placed within a Razor view so that the line

@Url.Action("Action","Controller")

is parsed by Razor and the real value replaced.

If you don't want to move your Javascript into your View you could look at creating a settings object in the view and then referencing that from your Javascript file.

e.g.

var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'
}

and in your .js file

$.ajax({
 type: "POST",
 url: MyAppUrlSettings.MyUsefulUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());
});

or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.

Converting JavaScript object with numeric keys into array

You simply do it like

var data = {
    "0": "1",
    "1": "2",
    "2": "3",
    "3": "4"
};
var arr = [];
for (var prop in data) {
    arr.push(data[prop]);
}
console.log(arr);

DEMO

Stop form from submitting , Using Jquery

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

Here is an example of some added validation

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

FormData.append("key", "value") is not working

you can see it you need to use console.log(formData.getAll('your key')); watch the https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

Font-awesome, input type 'submit'

You can use button classes btn-link and btn-xs with type submit, which will make a small invisible button with an icon inside of it. Example:

<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
    <i class="fa fa-times text-danger"></i>
</button>

How to convert a DataTable to a string in C#?

You could use something like this:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
    Dim sw As System.IO.StringWriter
    Dim output As String

    Console.WriteLine(label)

    ' Loop through each row in the table. '
    For Each row As DataRow In table.Rows
        sw = New System.IO.StringWriter
        ' Loop through each column. '
        For Each col As DataColumn In table.Columns
            ' Output the value of each column's data.
            sw.Write(row(col).ToString() & ", ")
        Next
        output = sw.ToString
        ' Trim off the trailing ", ", so the output looks correct. '
        If output.Length > 2 Then
            output = output.Substring(0, output.Length - 2)
        End If
        ' Display the row in the console window. '
        Console.WriteLine(output)
    Next
    Console.WriteLine()
End Sub

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

Can we open pdf file using UIWebView on iOS?

Yes, this can be done with the UIWebView.

If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))

let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)

view.addSubview(webView)

Or if you have a PDF file bundled with your application (in this example named "document.pdf"):

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))

let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)

view.addSubview(webView)

You can find more information here: Technical QA1630: Using UIWebView to display select document types.

Programmatically change UITextField Keyboard type

There is a keyboardType property for a UITextField:

typedef enum {
    UIKeyboardTypeDefault,                // Default type for the current input method.
    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    UIKeyboardTypeDecimalPad,             // A number pad including a decimal point
    UIKeyboardTypeTwitter,                // Optimized for entering Twitter messages (shows # and @)
    UIKeyboardTypeWebSearch,              // Optimized for URL and search term entry (shows space and .)

    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated

} UIKeyboardType;

Your code should read

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

What is the behavior of integer division?

I know people have answered your question but in layman terms:

5 / 2 = 2 //since both 5 and 2 are integers and integers division always truncates decimals

5.0 / 2 or 5 / 2.0 or 5.0 /2.0 = 2.5 //here either 5 or 2 or both has decimal hence the quotient you will get will be in decimal.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

select2 - hiding the search box

If the select is show results one have to use this:

$('#yourSelect2ControlId').select2("close").parent().hide();

it closes the search results box and then set control unvisible

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

TypeError: 'dict' object is not callable

You need to use [] to access elements of a dictionary. Not ()

  number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 }
input_str = raw_input("Enter something: ")
strikes = [number_map[int(x)] for x in input_str ]

Add button to navigationbar programmatically

Use following code:

UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
[self.navigationItem setRightBarButtonItem:customBtn];

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student

SET (student.student_education_facility_id) = (

   SELECT teacher.education_facility_id

   FROM user_account teacher

   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

Sql Query to list all views in an SQL Server 2005 database

select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'

How do you fix the "element not interactable" exception?

I have found that using Thread.sleep(milliseconds) helps almost all the time for me. It takes time for the element to load hence it is not interactable. So i put Thread.sleep() after selecting each value. So far this has helped me avoid the error.

try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}

        Select nationalityDropdown=new Select(driver.findElement(By.id("ContentPlaceHolderMain_ddlNationality")));

        nationalityDropdown.selectByValue("Indian");

        try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}     

How to add an image in the title bar using html?

W3C says:

<!DOCTYPE html 
      PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" 
      type="image/png" 
      href="http://example.com/myicon.png">
[…]
</head>
[…]
</html>

See http://www.w3.org/2005/10/howto-favicon

But keep in mind: Some browser need a while to recognize that there is a favicon - try to delete the cookies and reopen your site! (And be sure the icon is at the path :) )

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

How to source virtualenv activate in a Bash script

Here is the script that I use often. Run it as $ source script_name

#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
    . $PWD/venv/bin/activate
}

activate

Java String array: is there a size of method?

Not really the answer to your question, but if you want to have something like an array that can grow and shrink you should not use an array in java. You are probably best of by using ArrayList or another List implementation.

You can then call size() on it to get it's size.

Iterating Through a Dictionary in Swift

Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarentee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    println("kind: \(kind)")
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

This prints:

kind: Square
kind: Prime
kind: Fibonacci

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

<application 
    android:theme="@android:style/Theme.Holo"/>

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

<application 
    android:theme="@android:style/Theme.Black"/>

<application 
    android:theme="@android:style/Theme.DeviceDefault"/>

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

If you are using Homestead like I do, do not forget to ssh into it before running artisan test for example.

How to install pywin32 module in windows 7

You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:

pip install pypiwin32

Currently I think this is "the easiest" way to get in working :) Hope this helps.

Adding minutes to date time in PHP

I don't know why the approach set as solution didn't work for me. So I'm posting here what worked for me in hope it can help anybody:

$startTime = date("Y-m-d H:i:s");

//display the starting time
echo '> '.$startTime . "<br>";

//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));

//display the converted time
echo '> '.$convertedTime;

Class 'DOMDocument' not found

This help for me (Ubuntu Linux) PHP 5.6.3

sudo apt-get install php5.6-dom

Thats work for me.

jQuery - setting the selected value of a select control via its text description

take a look at the jquery selectedbox plugin

selectOptions(value[, clear]): 

Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.

You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.

Also, there is a duplicate post here on Stack Overflow which has some other details.

sys.argv[1] meaning in script

Adding a few more points to Jason's Answer :

For taking all user provided arguments : user_args = sys.argv[1:]

Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.

The syntax is like this : list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.

Suppose you only want to take all the arguments after 3rd argument, then :

user_args = sys.argv[3:]

Suppose you only want the first two arguments, then :

user_args = sys.argv[0:2]  or  user_args = sys.argv[:2]

Suppose you want arguments 2 to 4 :

user_args = sys.argv[2:4]

Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step) :

user_args = sys.argv[-1]

Suppose you want the second last argument :

user_args = sys.argv[-2]

Suppose you want the last two arguments :

user_args = sys.argv[-2:]

Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by ":") :

user_args = sys.argv[-2:]

Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item :

user_args = sys.argv[:-2]

Suppose you want the arguments in reverse order :

user_args = sys.argv[::-1]

Hope this helps.

document.getElementById vs jQuery $()

One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.

Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.

<body id="content">
   <h1>Header!</h1>
   <form>
      <div id="content"> My Form </div>
   </form>
</body>

It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.

Show spinner GIF during an $http request in AngularJS?

Adding onto @Adam's answer,

Use ng-show as suggested, however, in your case you want the functionality to have multiple requests and await all of them before the loader is hidden.

<span ng-show="pendingRequests > 0">
    <img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>

And then in your controller:

$scope.pendingRequests++;

let url = '/whatever_Your_URL_Is'
$http.get(url)
  .then(function(response) {
      $scope.pendingRequests--;
})

How to open a txt file and read numbers in Java

Good news in Java 8 we can do it in one line:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());

How can foreign key constraints be temporarily disabled using T-SQL?

The SQL-92 standard allows for a constaint to be declared as DEFERRABLE so that it can be deferred (implicitly or explicitly) within the scope of a transaction. Sadly, SQL Server is still missing this SQL-92 functionality.

For me, changing a constraint to NOCHECK is akin to changing the database structure on the fly -- dropping constraints certainly is -- and something to be avoided (e.g. users require increased privileges).

Stopping a CSS3 Animation on last frame

The best way seems to put the final state at the main part of css. Like here, i put width to 220px, so that it finally becomes 220px. But starting to 0px;

div.menu-item1 {
  font-size: 20px;
  border: 2px solid #fff;
  width: 220px;
  animation: slide 1s;
  -webkit-animation: slide 1s; /* Safari and Chrome */
}
@-webkit-keyframes slide { /* Safari and Chrome */
  from {width:0px;}
  to {width:220px;}
}  

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Is the sizeof(some pointer) always equal to four?

A pointer is just a container for an address. On a 32 bit machine, your address range is 32 bits, so a pointer will always be 4 bytes. On a 64 bit machine were you have an address range of 64 bits, a pointer will be 8 bytes.

How can I open Java .class files in a human-readable way?

That's compiled code, you'll need to use a decompiler like JAD: http://www.kpdus.com/jad.html

How do I prevent mails sent through PHP mail() from going to spam?

Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM, return-path.

Laravel 5.1 API Enable Cors

just use this as a middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');

        return $response;
    }
}

and register the middleware in your kernel file on this path app/Http/Kernel.php in which group that you prefer and everything will be fine

How to get first N number of elements from an array

To get the first n elements of an array, use

array.slice(0, n);

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

CodeIgniter - how to catch DB errors?

If one uses PDO, additional to all the answers above.

I log my errors silently as below

        $q = $this->db->conn_id->prepare($query);

        if($q instanceof PDOStatement) {
           // go on with bind values and execute

        } else {

          $dbError = $this->db->error();
          $this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);

        }

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

How to leave/exit/deactivate a Python virtualenv

You can use virtualenvwrapper in order to ease the way you work with virtualenv.

Installing virtualenvwrapper:

pip install virtualenvwrapper

If you are using a standard shell, open your ~/.bashrc or ~/.zshrc if you use Oh My Zsh. Add these two lines:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

To activate an existing virtualenv, use command workon:

$ workon myenv
(myenv)$

In order to deactivate your virtualenv:

(myenv)$ deactivate

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.

What is the difference between a data flow diagram and a flow chart?

Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.

DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.

A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).

Round float to x decimals?

I coded a function (used in Django project for DecimalField) but it can be used in Python project :

This code :

  • Manage integers digits to avoid too high number
  • Manage decimals digits to avoid too low number
  • Manage signed and unsigned numbers

Code with tests :

def convert_decimal_to_right(value, max_digits, decimal_places, signed=True):

    integer_digits = max_digits - decimal_places
    max_value = float((10**integer_digits)-float(float(1)/float((10**decimal_places))))

    if signed:
        min_value = max_value*-1
    else:
        min_value = 0

    if value > max_value:
        value = max_value

    if value < min_value:
        value = min_value

    return round(value, decimal_places)


value = 12.12345
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.12

value = 12.126
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.13

value = 1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : 99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : -99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2, signed = False)
# nb : 0

value = 12.123
nb = convert_decimal_to_right(value, 8, 4)
# nb : 12.123

Convert Existing Eclipse Project to Maven Project

I was having the same issue and wanted to Mavenise entire eclipse workspace containing around 60 Eclipse projects. Doing so manually required a lot of time and alternate options were not that viable. To solve the issue I finally created a project called eclipse-to-maven on github. As eclipse doesn't have all necessary information about the dependencies, it does the following:

  • Based on <classpathentry/> XML elements in .classpath file, it creates the dependencies on another project, identifies the library jar file and based on its name (for instance jakarta-oro-2.0.8.jar) identifies its version. Currently artifactId and groupId are same as I couldn't find something which could return me the Maven groupId of the dependency based on artifactId. Though this is not a perfect solution it provides a good ground to speed up Mavenisation.

  • It moves all source folders according to Maven convention (like src/main/java)

  • As Eclipse projects having names with spaces are difficult to deal on Linux/Unix environment, it renames them as well with names without spaces.

  • Resultant pom.xml files contain the dependencies and basic pom structure. You have to add required Maven plugins manually.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

bootstrap-4 add class float-left or right for floating

location.host vs location.hostname and cross-browser compatibility?

If you are insisting to use the window.location.origin You can put this in top of your code before reading the origin

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

Solution

PS: For the record, it was actually the original question. It was already edited :)

python xlrd unsupported format, or corrupt file.

Sometimes help to add ?raw=true at the end of a file path. For example:

wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls?raw=true")

Adding HTML entities using CSS content

There is a way to paste an nbsp - open CharMap and copy character 160. However, in this case I'd probably space it out with padding, like this:

.breadcrumbs a:before { content: '>'; padding-right: .5em; }

You might need to set the breadcrumbs display:inline-block or something, though.

Changing datagridview cell color based on condition

foreach (DataGridViewRow row in dgvWebData.Rows)
{
    if (Convert.ToString(row.Cells["IssuerName"].Value) != Convert.ToString(row.Cells["SearchTermUsed"].Value))
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
    }
    else
    {
        row.DefaultCellStyle.BackColor = Color.White;
    }
}

This Perfectly worked for me . even if a row is changed, same event takes care.

How to make grep only match if the entire line matches?

Works for me:

grep "\bsearch_word\b" text_file > output.txt  

\b indicates/sets boundaries.

Seems to work pretty fast

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Handy for linux virtual machines; Use 75% of your total system memory for Tomcat. Yay AWK.

Put at start of "{tomcat}/bin/startup.sh"

export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k"

Why can't I center with margin: 0 auto?

We can set the width for ul tag then it will align center.

#header ul {
    display: block;
    margin: 0 auto;
    width: 420px;
    max-width: 100%;
}

Java ByteBuffer to String

Here is a simple function for converting a byte buffer to string:

public String byteBufferToString(ByteBuffer bufferData) {
    byte[] buffer = new byte[bufferData.readableByteCount()];
    // read bufferData and insert into buffer 
    data.read(buffer);
    // CharsetUtil supports UTF_16, ASCII, and many more
    String text = new String(buffer, CharsetUtil.UTF_8);
    System.out.println("Text: "+text);
    return text;
}

How to iterate object in JavaScript?

You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.

var data = dictionary.data;

for (var i in data)
{
     var id = data[i].id;
     var name = data[i].name;
}

You can follow similar approach to iterate the image array.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

1.Right click on your java project.

2.Select "RUN AS".

3.Select "RUN CONFIGURATIOS...".

4.Here select your server at left side of the page and then u would see "CLASS PATH" tab at riht side,just click on it.

5.Here clilck on "USER ENTRIES" and select "ADD EXTERNAL JARS".

6.Select "ojdbc14.jar" file.

7.Click on Apply.

8.Click on Run.

9.Finally Restart your server then it would be execute.

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

https://www.blackhat.com/docs/asia-16/materials/asia-16-Sivakorn-Im-Not-a-Human-Breaking-the-Google-reCAPTCHA-wp.pdf

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:

https://github.com/neuroradiology/InsideReCaptcha

UPDATE 2017

A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:

http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf

UPDATE 2018

Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

https://www.google.com/recaptcha/intro/v3beta.html

Pentaho Data Integration SQL connection

Missing driver file.

This error is really common for people just getting started with PDI.

Drivers go in \pentaho\design-tools\data-integration\libext\JDBC for PDI. If you are using other tools in the Pentaho suite, you may need to copy drivers to additional locations for those tools. For reference, here are the appropriate folders for some of the other design tools:

  • Aggregation Designer: \pentaho\design-tools\aggregation-designer\drivers
  • Metadata Editor: \pentaho\design-tools\metadata-editor\libext\JDBC
  • Report Designer: \pentaho\design-tools\report-designer\lib\jdbc
  • Schema Workbench: \pentaho\design-tools\schema-workbench\drivers

If this transformation or job will run on another box, such as a test or production server, don't forget to include copying the jar file and restarting PDI or the Data Integration Server in your deployment considerations.

Using number_format method in Laravel

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>

Extract XML Value in bash script

As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.

grep -oPm1 "(?<=<title>)[^<]+"

Test:

$ echo "$data"
<item> 
  <title>15:54:57 - George:</title>
  <description>Diane DeConn? You saw Diane DeConn!</description> 
</item> 
<item> 
  <title>15:55:17 - Jerry:</title> 
  <description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:

Delete all the records

I can see the that the others answers shown above are right, but I'll make your life easy.

I even created an example for you. I added some rows and want delete them.

You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:

enter image description here

Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.

enter image description here

To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I don't think that replacing "Require all denied" with "Require all granted" in this directive:

<Directory>

    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

as suggested by Jan Czarny and seonded by user3801675 is the most secure way of solving this problem.

According to the Apache configuration files, that line denies access to the entirety of your server's filesystem. Replacing it might indeed allow access to your virtual host folders but at the price of allowing access to your entire computer as well!

Gev Balyan's approach seems to be the most secure approach here. It was the answer to the "access denied problems" plaguing me after setting up my new Apache server this morning.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

How to initialize static variables

You can't make function calls in this part of the code. If you make an init() type method that gets executed before any other code does then you will be able to populate the variable then.

Declare and assign multiple string variables at the same time

An example of what I call Concatenated-declarations:

string Camnr = "",
        Klantnr = "",
        Ordernr = "",
        Bonnr = "",
        Volgnr = "",
        Omschrijving = "",
        Startdatum = "",
        Bonprioriteit = "",
        Matsoort = "",
        Dikte = "",
        Draaibaarheid = "",
        Draaiomschrijving = "",
        Orderleverdatum = "",
        Regeltaakkode = "",
        Gebruiksvoorkeur = "",
        Regelcamprog = "",
        Regeltijd = "",
        Orderrelease = "";

Just my 2 cents, hope it helps someone somewhere.

HTTP test server accepting GET/POST requests

Here is one Postman echo: https://docs.postman-echo.com/

example:

curl --request POST \
  --url https://postman-echo.com/post \
  --data 'This is expected to be sent back as part of response body.'

response:

{"args":{},"data":"","files":{},"form":{"This is expected to be sent back as part of response body.":""},"headers":{"host":"postman-echo.com","content-length":"58","accept":"*/*","content-type":"application/x-www-form-urlencoded","user-agent":"curl/7.54.0","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":{"...

How to make a <ul> display in a horizontal row

List items are normally block elements. Turn them into inline elements via the display property.

In the code you gave, you need to use a context selector to make the display: inline property apply to the list items, instead of the list itself (applying display: inline to the overall list will have no effect):

#ul_top_hypers li {
    display: inline;
}

Here is the working example:

_x000D_
_x000D_
#div_top_hypers {_x000D_
    background-color:#eeeeee;_x000D_
    display:inline;      _x000D_
}_x000D_
#ul_top_hypers li{_x000D_
    display: inline;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
    <ul id="ul_top_hypers">_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> logout</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Center HTML Input Text Field Placeholder

The HTML5 placeholder element can be styled for those browsers that accept the element, but in diferent ways, as you can see here: http://davidwalsh.name/html5-placeholder-css.

But I don't believe that text-align will be interpreted by the browsers. At least on Chrome, this attribute is ignored. But you can always change other things, like color, font-size, font-family etc. I suggest you rethinking your design whether possible to remove this center behavior.

EDIT

If you really want this text centered, you can always use some jQuery code or plugin to simulate the placeholder behavior. Here is a sample of it: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html.

This way the style will work:

input.placeholder {
    text-align: center;
}

How to change Elasticsearch max memory size

If you use the service wrapper provided in Elasticsearch's Github repository, found at https://github.com/elasticsearch/elasticsearch-servicewrapper, then the conf file at elasticsearch-servicewrapper / service / elasticsearch.conf controls memory settings. At the top of elasticsearch.conf is a parameter:

set.default.ES_HEAP_SIZE=1024

Just reduce this parameter, say to "set.default.ES_HEAP_SIZE=512", to reduce Elasticsearch's allotted memory.

Note that if you use the elasticsearch-wrapper, the ES_HEAP_SIZE provided in elasticsearch.conf OVERRIDES ALL OTHER SETTINGS. This took me a bit to figure out, since from the documentation, it seemed that heap memory could be set from elasticsearch.yml.

If your service wrapper settings are set somewhere else, such as at /etc/default/elasticsearch as in James's example, then set the ES_HEAP_SIZE there.

Git Checkout warning: unable to unlink files, permission denied

All you need to do is provide permissions, run the command below from the root of your project:

    chmod ug+w <directory path>

How to match "anything up until this sequence of characters" in a regular expression?

I ended in this stackoverflow question after looking for help to solve my problem but found no solution to it :(

So I had to improvise... after some time I managed to reach the regex I needed:

enter image description here

As you can see, I needed up to one folder ahead of "grp-bps" folder, without including last dash. And it was required to have at least one folder after "grp-bps" folder.

Edit

Text version for copy-paste (change 'grp-bps' for your text):

.*\/grp-bps\/[^\/]+

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

After struggling with git authentication and azure devops server and trying other answers this tip here worked for me.

Using Visual Studio? Team Explorer handles authentication with Azure Repos for you.

Once I connected to the repo using Team Explorer I could use command line to execute git commands.

Aren't Python strings immutable? Then why does a + " " + b work?

a = 'dog'
address = id(a)
print(id(a))

a = a + 'cat'
print(id(a))      #Address changes

import ctypes
ctypes.cast(address, ctypes.py_object).value    #value at old address is intact

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

failed to find target with hash string 'android-22'

Open project.properties file and change the line with target=android-22 to the desired value.
For example:

target=android-19

Use JAXB to create Object from XML String

If you already have the xml, and comes more than one attribute, you can handle it as follows:

String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {           
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);
    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);
    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

the method getCharacterDataFromElement is

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;

return cd.getData();
}
return "";
}

Commenting out a set of lines in a shell script

As per this site:

#!/bin/bash
foo=bar
: '
This is a test comment
Author foo bar
Released under GNU 
'

echo "Init..."
# rest of script

jQuery UI DatePicker to show year only

Try this piece of code, it worked for me:

$('#year').datepicker({
    format: "yyyy",
    viewMode: "years",
    minViewMode: "years"
});

I hope it will do magic also for you.

CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;

Demo

https://jsfiddle.net/simonmysun/2h61Ljbn/4/

Tested under Chrome 75 under Windows 10.

Supported platforms:

Watermark / hint text / placeholder TextBox

Set up the text box with placeholder text in a soft color...

public MainWindow ( )
{
    InitializeComponent ( );
    txtInput.Text = "Type something here...";
    txtInput.Foreground = Brushes.DimGray;
}

When the text box gets the focus, clear it and change the text color

private void txtInput_GotFocus ( object sender, EventArgs e )
{
    MessageBox.Show ( "got focus" );
    txtInput.Text = "";
    txtInput.Foreground = Brushes.Red;
}

How do I format a date as ISO 8601 in moment.js?

Answer in 2020 (Includes Timezone Support)

The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:

_x000D_
_x000D_
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()

//** Returns now in ISO format in Central Time */
export function getNowISO() {
  return `${moment().toISOString(true).substring(0, 23)}Z`
}
_x000D_
_x000D_
_x000D_

This will leave you with an exact ISO-formatted, localized string.

Important note: Moment now suggests using other packages for new projects.

TNS Protocol adapter error while starting Oracle SQL*Plus

Another possibility (esp. with multiple Oracle homes)

set ORACLE_SID=$SID

sqlplus /nolog

conn / as sysdba;

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

How to attach a file using mail command on Linux?

mail on every version of modern Linux that I've tried can do it. No need for other software:

matiu@matiu-laptop:~$ mail -a doc.jpg [email protected]
Subject: testing

This is a test
EOT

ctrl+d when you're done typing.

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry you're not using PostgreSQL...

SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity

http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT

Oh wait. You only want values with exactly one...

SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1

Git diff says subproject is dirty

Update Jan. 2021, ten years later:

"git diff"(man) showed a submodule working tree with untracked cruft as Submodule commit <objectname>-dirty, but a natural expectation is that the "-dirty" indicator would align with "git describe --dirty"(man), which does not consider having untracked files in the working tree as source of dirtiness.
The inconsistency has been fixed with Git 2.31 (Q1 2021).

See commit 8ef9312 (10 Nov 2020) by Sangeeta Jain (sangu09).
(Merged by Junio C Hamano -- gitster -- in commit 0806279, 25 Jan 2021)

diff: do not show submodule with untracked files as "-dirty"

Signed-off-by: Sangeeta Jain

Git diff reports a submodule directory as -dirty even when there are only untracked files in the submodule directory.
This is inconsistent with what git describe --dirty(man) says when run in the submodule directory in that state.

Make --ignore-submodules=untracked the default for git diff(man) when there is no configuration variable or command line option, so that the command would not give '-dirty' suffix to a submodule whose working tree has untracked files, to make it consistent with git describe --dirty that is run in the submodule working tree.

And also make --ignore-submodules=none the default for git status(man) so that the user doesn't end up deleting a submodule that has uncommitted (untracked) files.

git config now includes in its man page:

By default this is set to untracked so that any untracked submodules are ignored.


Original answer (2011)

As mentioned in Mark Longair's blog post Git Submodules Explained,

Versions 1.7.0 and later of git contain an annoying change in the behavior of git submodule.
Submodules are now regarded as dirty if they have any modified files or untracked files, whereas previously it would only be the case if HEAD in the submodule pointed to the wrong commit.

The meaning of the plus sign (+) in the output of git submodule has changed, and the first time that you come across this it takes a little while to figure out what’s going wrong, for example by looking through changelogs or using git bisect on git.git to find the change. It would have been much kinder to users to introduce a different symbol for “at the specified version, but dirty”.

You can fix it by:

  • either committing or undoing the changes/evolutions within each of your submodules, before going back to the parent repo (where the diff shouldn't report "dirty" files anymore). To undo all changes to your submodule just cd into the root directory of your submodule and do git checkout .

dotnetCarpenter comments that you can do a: git submodule foreach --recursive git checkout .

  • or add --ignore-submodules to your git diff, to temporarily ignore those "dirty" submodules.

New in Git version 1.7.2

As Noam comments below, this question mentions that, since git version 1.7.2, you can ignore the dirty submodules with:

git status --ignore-submodules=dirty

Modifying local variable from inside lambda

Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.

You should either find a solution without side effects or use a traditional for loop.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.

My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.

  1. Switches - (very unlikely but sometimes they get in a sick state)
  2. Routers - more likely than switches, but not much
  3. Firewall - More likely than routers. Things to look for here are resource exhaustion (license, cpu, etc)
  4. Client side filtering software - antivirus, malware detection etc.

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

How to wait in a batch script?

You can ping an address that doesn't exist and specify the desired timeout:

ping 192.0.2.2 -n 1 -w 10000 > nul

And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.

  • The -w 10000 part specifies the desired timeout in milliseconds.
  • The -n 1 part tells ping that it should only try once (normally it'd try 4 times).
  • The > nul part is appended so the ping command doesn't output anything to screen.

You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:

rem SLEEP.BAT - sleeps by the supplied number of seconds

@ping 192.0.2.2 -n 1 -w %1000 > nul

NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:

192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

Things possible in IntelliJ that aren't possible in Eclipse?

The IntelliJ debugger has a very handy feature called "Evaluate Expression", that is by far better than eclipses pendant. It has full code-completion and i concider it to be generally "more useful".

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

  • Goto => Tools >> Options >> Text Editor >> C/C++ >> Advanced >> IntelliSense
  • Change => Member List Commit Aggressive to True

Disable Laravel's Eloquent timestamps

Add this line into your model:

Overwrite existing variable $timestamps true to false

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */

public $timestamps = false;

What is href="#" and why is it used?

Unordered lists are often created with the intent of using them as a menu, but an li list item is text. Because the list li item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a inside of the li tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.

<ul id="menu">
   <li><a href="#">Menu Item 1</a></li>
   <li><a href="#">Menu Item 2</a></li>
   <li><a href="#">Menu Item 3</a></li>
   <li><a href="#">Menu Item 4</a></li>
</ul>

If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href attribute, text in the <a> tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href, but you don't need a link to anywhere.

You could use lots of div or p tags for a menu list, but the mouse pointer would be an I-cursor for them also.

You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#" that points to nowhere is used in anchor tags inside of list tags.

You can set the pointer style in CSS, so that is another option. The href="#" to nowhere might just be the lazy way to set some styling.

How to set caret(cursor) position in contenteditable element (div)?

Based on Tim Down's answer, but it checks for the last known "good" text row. It places the cursor at the very end.

Furthermore, I could also recursively/iteratively check the last child of each consecutive last child to find the absolute last "good" text node in the DOM.

_x000D_
_x000D_
function onClickHandler() {_x000D_
  setCaret(document.getElementById("editable"));_x000D_
}_x000D_
_x000D_
function setCaret(el) {_x000D_
  let range = document.createRange(),_x000D_
      sel = window.getSelection(),_x000D_
      lastKnownIndex = -1;_x000D_
  for (let i = 0; i < el.childNodes.length; i++) {_x000D_
    if (isTextNodeAndContentNoEmpty(el.childNodes[i])) {_x000D_
      lastKnownIndex = i;_x000D_
    }_x000D_
  }_x000D_
  if (lastKnownIndex === -1) {_x000D_
    throw new Error('Could not find valid text content');_x000D_
  }_x000D_
  let row = el.childNodes[lastKnownIndex],_x000D_
      col = row.textContent.length;_x000D_
  range.setStart(row, col);_x000D_
  range.collapse(true);_x000D_
  sel.removeAllRanges();_x000D_
  sel.addRange(range);_x000D_
  el.focus();_x000D_
}_x000D_
_x000D_
function isTextNodeAndContentNoEmpty(node) {_x000D_
  return node.nodeType == Node.TEXT_NODE && node.textContent.trim().length > 0_x000D_
}
_x000D_
<div id="editable" contenteditable="true">_x000D_
  text text text<br>text text text<br>text text text<br>_x000D_
</div>_x000D_
<button id="button" onclick="onClickHandler()">focus</button>
_x000D_
_x000D_
_x000D_

Wait until a process ends

Referring to the Microsoft example: [https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.enableraisingevents?view=netframework-4.8]

Best would be to set:

myProcess.EnableRaisingEvents = true;

otherwiese the Code will be blocked. Also no additional properties needed.

// Start a process and raise an event when done.
myProcess.StartInfo.FileName = fileName;
// Allows to raise event when the process is finished
myProcess.EnableRaisingEvents = true;
// Eventhandler wich fires when exited
myProcess.Exited += new EventHandler(myProcess_Exited);
// Starts the process
myProcess.Start();

// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
Console.WriteLine(
                  $"Exit time    : {myProcess.ExitTime}\n" +
                  $"Exit code    : {myProcess.ExitCode}\n" +
                  $"Elapsed time : {elapsedTime}");
}

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

Jquery - How to get the style display attribute "none / block"

My answer

/**
 * Display form to reply comment
 */
function displayReplyForm(commentId) {
    var replyForm = $('#reply-form-' + commentId);
    if (replyForm.css('display') == 'block') { // Current display
        replyForm.css('display', 'none');
    } else { // Hide reply form
        replyForm.css('display', 'block');
    }
}

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

How do you convert a byte array to a hexadecimal string in C?

There's no primitive for this in C. I'd probably malloc (or perhaps alloca) a long enough buffer and loop over the input. I've also seen it done with a dynamic string library with semantics (but not syntax!) similar to C++'s ostringstream, which is a plausibly more generic solution but it may not be worth the extra complexity just for a single case.

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

Are the days of passing const std::string & as a parameter over?

Are the days of passing const std::string & as a parameter over?

No. Many people take this advice (including Dave Abrahams) beyond the domain it applies to, and simplify it to apply to all std::string parameters -- Always passing std::string by value is not a "best practice" for any and all arbitrary parameters and applications because the optimizations these talks/articles focus on apply only to a restricted set of cases.

If you're returning a value, mutating the parameter, or taking the value, then passing by value could save expensive copying and offer syntactical convenience.

As ever, passing by const reference saves much copying when you don't need a copy.

Now to the specific example:

However inval is still quite a lot larger than the size of a reference (which is usually implemented as a pointer). This is because a std::string has various components including a pointer into the heap and a member char[] for short string optimization. So it seems to me that passing by reference is still a good idea. Can anyone explain why Herb might have said this?

If stack size is a concern (and assuming this is not inlined/optimized), return_val + inval > return_val -- IOW, peak stack usage can be reduced by passing by value here (note: oversimplification of ABIs). Meanwhile, passing by const reference can disable the optimizations. The primary reason here is not to avoid stack growth, but to ensure the optimization can be performed where it is applicable.

The days of passing by const reference aren't over -- the rules just more complicated than they once were. If performance is important, you'll be wise to consider how you pass these types, based on the details you use in your implementations.

add string to String array

you would have to write down some method to create a temporary array and then copy it like

public String[] increaseArray(String[] theArray, int increaseBy)  
{  
    int i = theArray.length;  
    int n = ++i;  
    String[] newArray = new String[n];  
    for(int cnt=0;cnt<theArray.length;cnt++)
    {  
        newArray[cnt] = theArray[cnt];  
    }  
    return newArray;  
}  

or The ArrayList would be helpful to resolve your problem.

How to set up Android emulator proxy settings

I tried after removing http in the server name and it worked for me.

emulator -avd myavd -http-proxy 168.192.1.2:3300

Get week day name from a given month, day and year individually in SQL Server

select to_char(sysdate,'DAY') from dual; It's work try it

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Inspired by Johann's table, I've decided to extend the table. I wanted to see which ASCII characters get encoded.

screenshot of console.table

_x000D_
_x000D_
var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";_x000D_
_x000D_
var encoded = [];_x000D_
_x000D_
ascii.split("").forEach(function (char) {_x000D_
    var obj = { char };_x000D_
    if (char != encodeURI(char))_x000D_
        obj.encodeURI = encodeURI(char);_x000D_
    if (char != encodeURIComponent(char))_x000D_
        obj.encodeURIComponent = encodeURIComponent(char);_x000D_
    if (obj.encodeURI || obj.encodeURIComponent)_x000D_
        encoded.push(obj);_x000D_
});_x000D_
_x000D_
console.table(encoded);
_x000D_
_x000D_
_x000D_

Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.


Just to be extra, I'm adding another table for urlencode() vs rawurlencode(). The only difference seems to be the encoding of space character.

screenshot of console.table

<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
    $obj = ["char" => $char];
    if ($char != urlencode($char))
        $obj["urlencode"] = urlencode($char);
    if ($char != rawurlencode($char))
        $obj["rawurlencode"] = rawurlencode($char);
    if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
        $encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

show loading icon until the page is load?

HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.

So in CSS consider adding

pointer-events: none;
cursor: default;

Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html

<i class="fa fa-spinner fa-spin">

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

check if a number already exist in a list in python

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: -

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSet recipe, which is referred to in Python Documentation

Determine function name from within that function (without using traceback)

I keep this handy utility nearby:

import inspect
myself = lambda: inspect.stack()[1][3]

Usage:

myself()

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

how to print json data in console.log

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}

console.dir() will do what you need. It will give you a hierarchical structure of the data.

success:function(data){
     console.dir(data);
}

like so

> Object
  > input_data: Object
      price-row_122: " 35.1 "
      quantity-row_122: "1"
    success: true

I don't think you need console.log(JSON.stringify(data)).

To get the data you can do this without stringify:

console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "

Note

The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:

 typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
 parseFloat(data.input_data['price-row_122'], 10) // 35.1

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

It's because of lack of privilege for the user you are running the report builder, just give that user or a group a privilege to run report builder. Please visit this article

Or for shortcut:

  1. Start Internet Explorer using "Run as Administrator"
  2. Open http://localhost/reports
  3. Go to properties tab (SSRS 2008)
  4. Security->New Role Assignment
  5. Add DOMAIN/USERNAME or DOMAIN/USERGROUP
  6. Check Report builder

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Generating a UUID in Postgres for Insert statement?

PostgreSQL 13 supports natively gen_random_uuid ():

PostgreSQL includes one function to generate a UUID:

gen_random_uuid () ? uuid

This function returns a version 4 (random) UUID. This is the most commonly used type of UUID and is appropriate for most applications.

db<>fiddle demo

What are forward declarations in C++?

The term "forward declaration" in C++ is mostly only used for class declarations. See (the end of) this answer for why a "forward declaration" of a class really is just a simple class declaration with a fancy name.

In other words, the "forward" just adds ballast to the term, as any declaration can be seen as being forward in so far as it declares some identifier before it is used.

(As to what is a declaration as opposed to a definition, again see What is the difference between a definition and a declaration?)

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

What does "use strict" do in JavaScript, and what is the reasoning behind it?

"use strict" makes JavaScript code to run in strict mode, which basically means everything needs to be defined before use. The main reason for using strict mode is to avoid accidental global uses of undefined methods.

Also in strict mode, things run faster, some warnings or silent warnings throw fatal errors, it's better to always use it to make a neater code.

"use strict" is widely needed to be used in ECMA5, in ECMA6 it's part of JavaScript by default, so it doesn't need to be added if you're using ES6.

Look at these statements and examples from MDN:

The "use strict" Directive
The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5). It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.

Examples of using "use strict":
Strict mode for functions: Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

1) strict mode in functions

 function strict() {
     // Function-level strict mode syntax
     'use strict';
     function nested() { return 'And so am I!'; }
     return "Hi!  I'm a strict mode function!  " + nested();
 }
 function notStrict() { return "I'm not strict."; }

 console.log(strict(), notStrict());

2) whole-script strict mode

'use strict';
var v = "Hi! I'm a strict mode script!";
console.log(v);

3) Assignment to a non-writable global

'use strict';

// Assignment to a non-writable global
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError

// Assignment to a non-writable property
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
obj1.x = 9; // throws a TypeError

// Assignment to a getter-only property
var obj2 = { get x() { return 17; } };
obj2.x = 5; // throws a TypeError

// Assignment to a new property on a non-extensible object.
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = 'ohai'; // throws a TypeError

You can read more on MDN.

JavaScript - populate drop down list with array

You can also do it with jQuery:

var options = ["1", "2", "3", "4", "5"];
$('#select').empty();
$.each(options, function(i, p) {
    $('#select').append($('<option></option>').val(p).html(p));
});

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

How can I clear the content of a file?

The easiest way is:

File.WriteAllText(path, string.Empty)

However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException

using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
     lock(fs)
     {
          fs.SetLength(0);
     }
}

command/usr/bin/codesign failed with exit code 1- code sign error

I Followed all the things mentioned in this thread but still facing same issue-

/usr/bin/codesign --force --sign A7F8FCD694D7923A3E57826398C3380E2E5A5446 --entitlements  unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

I have configured Automatic signing with my code base which will work with xcode run as well as xcodebuild run from terminal from my machine but it gives above error when I run it on jenkins pipeline or try to run on terminal from remotely connected machine

In my case Automatic signing is not working if access remotely. because I need to open keychain before archive using

security unlock-keychain -p "newpassword" "/Users/xyz/Library/Keychains/login.keychain"

keychain passwords & login password for macOS X user was different I change it to new same password and it works for me.

Object Library Not Registered When Adding Windows Common Controls 6.0

You Just execute the following commands in your command prompt,

For 32 bit machine,

cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

For 64 bit machine,

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

Python unittest passing arguments

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

that will let you run with:

python mytests.py ausername apassword

You need the argv.pops so your command line params don't mess with unittest's own...

[update] The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)            
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

That will let you run with:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

Set default time in bootstrap-datetimepicker

i tried to set default time for a picker and it worked:

$('#date2').datetimepicker({
 format: 'DD-MM-YYYY 12:00:00'
});

this will save in database as : 2015-03-01 12:00:00

used for smalldatetime type in sql server

How do I change the hover over color for a hover over table in Bootstrap?

For me @pvskisteak5 answer has caused a "flicker-effect". To fix this, add the following:

            .table-hover tbody tr:hover,
            .table-hover tbody tr:hover td,
            .table-hover tbody tr:hover th{
                background:#22313F !important;
                color:#fff !important;
            }

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

How to create a list of objects?

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass

objs = [MyClass() for i in range(10)]

print(objs)

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

Angular2 get clicked element id

You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:

<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>


toggle( event: Event ) {
  const eventTarget: Element = event.target as Element;
  const elementId: string = eventTarget.id;
  const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}

java.lang.NoClassDefFoundError in junit

The org/hamcrest/SelfDescribing class is not on the run-time classpath.

How to change line width in ggplot?

Whilst @Didzis has the correct answer, I will expand on a few points

Aesthetics can be set or mapped within a ggplot call.

  • An aesthetic defined within aes(...) is mapped from the data, and a legend created.

  • An aesthetic may also be set to a single value, by defining it outside aes().

As far as I can tell, what you want is to set size to a single value, not map within the call to aes()

When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).

Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)

Figure29 +
    geom_line(aes(group=factor(tradlib)),size=1) +
    facet_grid(regionsFull~., scales="free_y") +
    scale_colour_brewer(type = "div") +
    theme(axis.text.x = element_text(
          colour = 'black', angle = 90, size = 13,
          hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
    ylab("FSI (%Change)") +
    theme(axis.text.y = element_text(colour = 'black', size = 12), 
          axis.title.y = element_text(size = 12, 
          hjust = 0.5, vjust = 0.2)) + 
    theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust =    0.5, face = 'bold'))

enter image description here

and with size = 2

 Figure29 + 
     geom_line(aes(group=factor(tradlib)),size=2) +
     facet_grid(regionsFull~., scales="free_y") + 
     scale_colour_brewer(type = "div") +
     theme(axis.text.x = element_text(colour = 'black', angle = 90,
          size = 13, hjust = 0.5, vjust = 
          0.5),axis.title.x=element_blank()) + 
     ylab("FSI (%Change)") +
     theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) + 
      theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust = 0.5, face = 'bold'))

enter image description here

You can now define the size to work appropriately with the final image size and device type.

Check if certain value is contained in a dataframe column in pandas

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

How to set JFrame to appear centered, regardless of monitor resolution?

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Does the class org.apache.maven.shared.filtering.MavenFilteringException exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar?

The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.

I'm also wondering where the version 1.0-beta-2 comes from; I have 1.0 on my disk. Try version 2.3 of the WAR plugin.

How do I check if a column is empty or null in MySQL?

SELECT * FROM tbl WHERE trim(IFNULL(col,'')) <> '';

Get the client's IP address in socket.io

Using the latest 1.0.6 version of Socket.IO and have my app deployed on Heroku, I get the client IP and port using the headers into the socket handshake:

var socketio = require('socket.io').listen(server);

socketio.on('connection', function(socket) {

  var sHeaders = socket.handshake.headers;
  console.info('[%s:%s] CONNECT', sHeaders['x-forwarded-for'], sHeaders['x-forwarded-port']);

}

How to initialize a two-dimensional array in Python?

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any 'x' value use :

twoD = np.array([[x]*m]*n

How do I improve ASP.NET MVC application performance?

One super easy thing to do is to think asynchronously when accessing the data you want for the page. Whether reading from a web service, file, data base or something else, use the async model as much as possible. While it won't necessarily help any one page be faster it will help your server perform better overall.

Installing a local module using npm?

Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.

For example:

/local/mymodule/package.json:
  "name": "mymodule",
  "peerDependencies":
  {
    "foo": "^2.5"
  }

/dev/myproject/package.json:
  "dependencies":
  {
    "mymodule": "file:/local/mymodule",
    "foo": "^2.5"
  }

In this scenario, npm sets up myproject's node_modules/ like this:

/dev/myproject/node_modules/
  foo/
  mymodule -> /local/mymodule

When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.

So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(

Curl error: Operation timed out

$curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "", // Server Path
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000, // increase this
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"email\":\"[email protected]\",\"password\":\"markus William\",\"username\":\"Daryl Brown\",\"mobile\":\"013132131112\","msg":"No more SSRIs." }",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "Postman-Token: 4867c7a3-2b3d-4e9a-9791-ed6dedb046b1",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

initialize array index "CURLOPT_TIMEOUT" with a value in seconds according to time required for response .

Git Server Like GitHub?

Try GitLab

The best git GUI tool i have ever used. It is very similar to GitHub.

It is open source (MIT License) and is the most installed git management software with over 25.000 installation. It has monthly releases and an active community with over 375 contributors. You can have unlimited private, internal and public repositories on your own server. It is a Ruby on Rails app that runs on most Unix platforms.

socket.shutdown vs socket.close

Shutdown(1) , forces the socket no to send any more data

This is usefull in

1- Buffer flushing

2- Strange error detection

3- Safe guarding

Let me explain more , when you send a data from A to B , it's not guaranteed to be sent to B , it's only guaranteed to be sent to the A os buffer , which in turn sends it to the B os buffer

So by calling shutdown(1) on A , you flush A's buffer and an error is raised if the buffer is not empty ie: data has not been sent to the peer yet

Howoever this is irrevesable , so you can do that after you completely sent all your data and you want to be sure that it's atleast at the peer os buffer

Get the records of last month in SQL server

I don't think the accepted solution is very index friendly I use the following lines instead

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date <= dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

Or simply (this is the best).

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date < SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);

Some help

-- Get the first of last month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
-- Get the first of current month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
--Get the last of last month except the last 3milli seconds. (3miliseconds being used as SQL express otherwise round it up to the full second (SERIUSLY MS)
SELECT dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

AngularJS - Animate ng-view transitions

I'm not sure about a way to do it directly with AngularJS but you could set the display to none for both welcome and login and animate the opacity with an directive once they are loaded.

I would do it some way like so. 2 Directives for fading in the content and fading it out when a link is clicked. The directive for fadeouts could simply animate a element with an unique ID or call a service which broadcasts the fadeout

Template:

<div class="tmplWrapper" onLoadFadeIn>
    <a href="somewhere/else" fadeOut>
</div>

Directives:

angular
  .directive('onLoadFadeIn', ['Fading', function('Fading') {
    return function(scope, element, attrs) {
      $(element).animate(...);
      scope.$on('fading', function() {
    $(element).animate(...);
      });
    }
  }])
  .directive('fadeOut', function() {
    return function(scope, element, attrs) {
      element.bind('fadeOut', function(e) {
    Fading.fadeOut(e.target);
  });
    }
  });

Service:

angular.factory('Fading', function() {
  var news;
  news.setActiveUnit = function() {
    $rootScope.$broadcast('fadeOut');
  };
  return news;
})

I just have put together this code quickly so there may be some bugs :)

What is considered a good response time for a dynamic, personalized web application?

Our company has a 5 second response time standard limit, and we aim for 2-3 seconds in general. This accounts for 98% of page loads. A few particular tasks are allowed to go up to 15 seconds, but we then mitigate that time by putting up a page and refreshing every 5 seconds telling the user that we are still trying to process the request. That way the user sees that something is happening and doesn't just leave. Although, considering that I work on a website whose users are forced to use for business reasons, they aren't going to leave, but they are capable of complaining quite loudly.

In general, if the processing is going to take more than 5 seconds, put up a temporary page so that the user doesn't lose interest.

Show just the current branch in Git

In Git 1.8.1 you can use the git symbolic-ref command with the "--short" option:

$ git symbolic-ref HEAD
refs/heads/develop
$ git symbolic-ref --short HEAD
develop

Android custom Row Item for ListView

Use a custom Listview.

You can also customize how row looks by having a custom background. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" 
 android:background="#0095FF"> //background color

<ListView android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="0dip"
 android:focusableInTouchMode="false"
 android:listSelector="@android:color/transparent"
 android:layout_weight="2"
 android:headerDividersEnabled="false"
 android:footerDividersEnabled="false"
 android:dividerHeight="8dp" 
 android:divider="#000000" 
 android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>  

MainActivity

Define populateString() in MainActivity

 public class MainActivity extends Activity {

   String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            data_array = populateString(); 
    ListView ll = (ListView) findViewById(R.id.list);
    CustomAdapter cus = new CustomAdapter();
    ll.setAdapter(cus);
}

class CustomAdapter extends BaseAdapter
{
    LayoutInflater mInflater;


    public CustomAdapter()
    {
        mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data_array.length;//listview item count. 
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position; 
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder vh;
        vh= new ViewHolder();

        if(convertView==null )
         {
            convertView=mInflater.inflate(R.layout.row, parent,false);
                    //inflate custom layour
            vh.tv2= (TextView)convertView.findViewById(R.id.textView2);

         }
        else
        {
         convertView.setTag(vh);
        }
               //vh.tv2.setText("Position = "+position);
            vh.tv2.setText(data_array[position]);   
                           //set text of second textview based on position

        return convertView;
    }

 class ViewHolder
 {
    TextView tv1,tv2;
 }

   }  
}

row.xml. Custom layout for each row.

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

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Header" />

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TextView" />

 </LinearLayout>

Inflate a custom layout. Use a view holder for smooth scrolling and performance.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.

enter image description here

How do I solve this error, "error while trying to deserialize parameter"

Are you sure your web service is deployed correctly to the enviornment that is NOT working. Looks like the type is out of date.

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

How to set custom header in Volley Request

Here is setting headers from github sample:

StringRequest myReq = new StringRequest(Method.POST,
                       "http://ave.bolyartech.com/params.php",
                        createMyReqSuccessListener(),
                        createMyReqErrorListener()) {

 protected Map<String, String> getParams() throws 
         com.android.volley.AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("param1", num1);
                        params.put("param2", num2);
                        return params;
                    };
                };
                queue.add(myReq);

How to calculate cumulative normal distribution?

Here's an example:

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

In other words, approximately 95% of the standard normal interval lies within two standard deviations, centered on a standard mean of zero.

If you need the inverse CDF:

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)

A valid provisioning profile for this executable was not found... (again)

It happened to me when I accidentally left the build in release mode.

Checkout Jenkins Pipeline Git SCM with credentials?

To explicitly checkout using a specific credentials

    stage('Checkout external proj') {
        steps {
            git branch: 'my_specific_branch',
                credentialsId: 'my_cred_id',
                url: 'ssh://[email protected]/proj/test_proj.git'

            sh "ls -lat"
        }
    }

To checkout based on the configred credentials in the current Jenkins Job

    stage('Checkout code') {
        steps {
            checkout scm
        }
    }

You can use both of the stages within a single Jenkins file.