Programs & Examples On #Xslkey

How to set image in imageview in android?

// take variable of imageview

private ImageView mImageView;

//bind imageview with your xml's id

mImageView = (ImageView)findViewById(R.id.mImageView);

//set resource for imageview

mImageView.setImageResource(R.drawable.your_image_name);

How to display pie chart data values of each slice in chart.js

From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:

function drawSegmentValues()
{
    for(var i=0; i<myPieChart.segments.length; i++) 
    {
        // Default properties for text (size is scaled)
        ctx.fillStyle="white";
        var textSize = canvas.width/10;
        ctx.font= textSize+"px Verdana";

        // Get needed variables
        var value = myPieChart.segments[i].value;
        var startAngle = myPieChart.segments[i].startAngle;
        var endAngle = myPieChart.segments[i].endAngle;
        var middleAngle = startAngle + ((endAngle - startAngle)/2);

        // Compute text location
        var posX = (radius/2) * Math.cos(middleAngle) + midX;
        var posY = (radius/2) * Math.sin(middleAngle) + midY;

        // Text offside to middle of text
        var w_offset = ctx.measureText(value).width/2;
        var h_offset = textSize/4;

        ctx.fillText(value, posX - w_offset, posY + h_offset);
    }
}

A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.

In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.

Fiddle Example


With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:

Math.round(myPieChart.segments[i].value/totalValue*100)+'%';

The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:

var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
    value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';

Fiddle Example of percentile with decimals

Fiddle Example of percentile with integers

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Check if an element contains a class in JavaScript?

in which element is currently the class '.bar' ? Here is another solution but it's up to you.

var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string

if (query.match(reg)) { // checks if it matches
  alert('the class .bar is attached to the following Element:\n' + query);
}

jsfiddle demo

Of course this is only a lookup for 1 simple element <img>(/Image/g) but you can put all in an array like <li> is /LI/g, <ul> = /UL/g etc.

Does Eclipse have line-wrap

Ahti Kitsik's plugin is mentioned above, but there's a newer plugin by another author that works with newer versions of Eclipse (up to Juno, at least), and also fixed the line numbering issue in the older plugin.

enter image description here

Full installation instructions are at Eclipse version to download the word wrap plug-in

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

Is there a better way to do optional function parameters in JavaScript?

If you're using the Underscore library (you should, it's an awesome library):

_.defaults(optionalArg, 'defaultValue');

Prevent textbox autofill with previously entered values

Autocomplete need to set off from textbox

<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>

How to secure MongoDB with username and password

after you create new user, please don't forget to grant read/write/root permission to the user. you can try the

cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])

How to convert <font size="10"> to px?

<font size=1>- font size 1</font><br>
<span style="font-size:0.63em">- font size: 0.63em</span><br>

<font size=2>- font size 2</font><br>
<span style="font-size: 0.82em">- font size: 0.82em</span><br>

<font size=3>- font size 3</font><br>
<span style="font-size: 1.0em">- font size: 1.0em</span><br>

<font size=4>- font size 4</font><br>
<span style="font-size: 1.13em">- font size: 1.13em</span><br>

<font size=5>- font size 5</font><br>
<span style="font-size: 1.5em">- font size: 1.5em</span><br>

<font size=6>- font size 6</font><br>
<span style="font-size: 2em">- font size: 2em</span><br>

<font size=7>- font size 7</font><br>
<span style="font-size: 3em">- font size: 3em</span><br>

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

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

How do I get rid of the "cannot empty the clipboard" error?

If you can't find the clipboard, then close that excel sheet and reopen it again. This will solve your problem.

Log4net does not write the log in the log file

Insert:

 [assembly: log4net.Config.XmlConfigurator(Watch = true)]

at the end of AssemblyInfo.cs file

Get specific objects from ArrayList when objects were added anonymously?

As per your question requirement , I would like to suggest that Map will solve your problem very efficient and without any hassle.

In Map you can give the name as key and your original object as value.

  Map<String,Cave> myMap=new HashMap<String,Cave>();

How to limit the maximum value of a numeric field in a Django model?

There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.

If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save method to throw an exception or limit the data going into the field.

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

How to get the entire document HTML as a string?

You have to iterate through the document childNodes and getting the outerHTML content.

in VBA it looks like this

For Each e In document.ChildNodes
    Put ff, , e.outerHTML & vbCrLf
Next e

using this, allows you to get all elements of the web page including < !DOCTYPE > node if it exists

MySQL - UPDATE query based on SELECT Query

You can update values from another table using inner join like this

UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];

Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/

or you can use select as subquery to do this

UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];

query explained in details here http://www.voidtricks.com/mysql-update-from-select/

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

Can I embed a .png image into an html page?

Quick google search says you can embed it like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

But you need a different implementation in Internet Explorer.

http://www.websiteoptimization.com/speed/tweak/inline-images/

Cannot install signed apk to device manually, got error "App not installed"

For Current Updated Android Studio 2.3 users this answer is for you as hardly people use eclipse nowadays for Android development as Android studio has huge advancements.

So, Follow this way to create your Signed apk file.

  1. Build > Generate Signed apk.
  2. Create Keystore path.
  3. Put Password, alias, key password.
  4. Build type select accordingly(eg to release in playstore use release).
  5. Signature Version select both V1 and V2 checkboxes.
  6. Finsih.
  7. Go to from explorer where you selected for the apk to store and you will see your .apk file name as app-release.apk use it.

TNS Protocol adapter error while starting Oracle SQL*Plus

You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.

Launch Pycharm from command line (terminal)

The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE

Python: can't assign to literal

You are trying to assign to literal integer values. 1, 2, etc. are not valid names; they are only valid integers:

>>> 1
1
>>> 1 = 'something'
  File "<stdin>", line 1
SyntaxError: can't assign to literal

You probably want to use a list or dictionary instead:

names = []
for i in range(1, 6):
    name = input("Please enter name {}:".format(i))
    names.append(name)

Using a list makes it much easier to pick a random value too:

winner = random.choice(names)
print('Well done {}. You are the winner!'.format(winner))

Is Safari on iOS 6 caching $.ajax results?

We found that older iPhones and iPads, running iOS versions 9 & 10, occasionally return bogus blank AJAX results, perhaps due to Apple's turning down CPU speed. When returning the blank result, iOS does not call the server, as if returning a result from cache. Frequency varies widely, from roughly 10% to 30% of AJAX calls return blank.

The solution is hard to believe. Just wait 1s and call again. In our testing, only one repeat was all that was ever needed, but we wrote the code to call up to 4 times. We're not sure if the 1s wait is required, but we didn't want to risk burdening our server with bursts of repeated calls.

We found the problem happened with two different AJAX calls, calling on different API files with different data. But I'm concerned it could happen on any AJAX call. We just don't know because we don't inspect every AJAX result and we don't test every call multiple times on old devices.

Both problem AJAX calls were using: POST, Asynchronously = true, setRequestHeader = ('Content-Type', 'application/x-www-form-urlencoded')

When the problem happens, there's usually only one AJAX call going on. So it's not due to overlapping AJAX calls. Sometimes the problem happens when the device is busy, but sometimes not, and without DevTools we don't really know what's happening at the time.

iOS 13 doesn't do this, nor Chrome or Firefox. We don't have any test devices running iOS 11 or 12. Perhaps someone else could test those?

I'm noting this here because this question is the top Google result when searching for this problem.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I solved this issue by removing all the NuGet packages from solution and reinstalling them. One of the NuGet Packages was dependent upon NewtonSoft and it was not showing in references

How can I specify a [DllImport] path at runtime?

If all fails, simply put the DLL in the windows\system32 folder . The compiler will find it. Specify the DLL to load from with: DllImport("user32.dll"..., set EntryPoint = "my_unmanaged_function" to import your desired unmanaged function to your C# app:

 using System;
using System.Runtime.InteropServices;

class Example
{
   // Use DllImport to import the Win32 MessageBox function.

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]
   public static extern int MessageBox 
      (IntPtr hWnd, String text, String caption, uint type);

   static void Main()
   {
      // Call the MessageBox function using platform invoke.
      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);    
   }
}

Source and even more DllImport examples : http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

nginx 502 bad gateway

If you're on Ubuntu, and all of the above has failed you, AppArmor is most likely to blame.

Here is a good guide how to fix it: https://www.digitalocean.com/community/tutorials/how-to-create-an-apparmor-profile-for-nginx-on-ubuntu-14-04

Long story short:

vi /etc/apparmor.d/nginx

Or

sudo aa-complain nginx
sudo service nginx restart

See everything working nicely... then

sudo aa-logprof

I still had problems with Nginx not being able to read error.log, even though it had all the permissions possible, including in Apparomor. I'm guessing it's got something to do with the order of the entries, or some interaction with Passenger or PHP-Fpm... I've run out of time to troubleshoot this and have gone back to Apache for now. (Apache performs much better too FYI.)

AppArmor just lets Nginx do whatever it wants if you just remove the profile:

 rm /etc/apparmor.d/nginx
 service apparmor reload

Shockingly, but hardly surprising, a lot of posts on fixing Nginx errors resorts to completely disabling SELinux or removing AppArmor. That's a bad idea because you lose protection from a whole lot of software. Just removing the Nginx profile is a better way to troubleshoot your config files. Once you know that the problem isn't in your Nginx config files, you can take the time to create a proper AppArmor profile.

Without an AppArmor profile, especially if you run something like Passenger too, I give your server about a month to get backdoored.

Sending mail from Python using SMTP

The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

I rely on my ISP to add the date time header.

My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.

=======================================

#! /usr/local/bin/python


SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'


content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except:
    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

Image inside div has extra space below the image

All you have to do is assign this property:

img {
    display: block;
}

The images by default have this property:

img {
    display: inline;
}

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

Postgres integer arrays as parameters?

I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,

SELECT * FROM some_table WHERE id_column = ANY(@id_list)

where @id_list is bound to an int[] parameter by way of

command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;

where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).

Sort objects in ArrayList by date?

Future viewers, I think this is the simplest solution, if your model contains a string type date ("2020-01-01 10:00:00" for example), then just write the following line to sort the data by date descending from newest to the oldest:

Collections.sort(messages, (o1, o2) -> o2.getMessageDate().compareTo(o1.getMessageDate()));

There is already an object named in the database

In my case, the issue was in Seeder. I was calling _ctx.Database.EnsureCreated() inside of it and as far as I understood, the update database command has successfully executed, but then seeder tried to create database "second" time.

How to address:

  1. Do nut run update, just start application and call EnsureCreated(). Database will be created/updated
  2. Comment out or remove seeder.

Asynchronous vs synchronous execution, what does it really mean?

Synchronous means that the caller waits for the response or completion, asynchronous that the caller continues and a response comes later (if applicable).

As an example:

static void Main(string[] args)
{
    Console.WriteLine("Before call");
    doSomething();
    Console.WriteLine("After call");
}

private static void doSomething()
{
    Console.WriteLine("In call");
}

This will always ouput:

Before call
In call
After call

But if we were to make doSomething asynchronous (multiple ways to do it), then the output could become:

Before call
After call
In call

Because the method making the asynchronous call would immediately continue with the next line of code. I say "could", because order of execution can't be guaranteed with asynch operations. It could also execute as the original, depending on thread timings, etc.

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi from 'node-v0.10.33-x86.msi' and it is working well for me!

http://blog.nodejs.org/2014/06/16/node-v0-10-29-stable/

Can I hide/show asp:Menu items based on role?

Try this:

protected void Menu1_DataBound(object sender, EventArgs e)
{
   recursiveMenuVisit(Menu1.Items);
}

private void recursiveMenuVisit(MenuItemCollection items)
        {
            MenuItem[] itemsToRemove = new MenuItem[items.Count];
            int i = 0;

            foreach (MenuItem item in items)
            {
                if (item.NavigateUrl.Contains("Contact.aspx"))
                {
                    itemsToRemove[i] = item;
                    i++;
                }
                else
                {
                    if (item.ChildItems.Count > 0) recursiveMenuVisit(item.ChildItems);
                }
            }

            for(int j=0; j < i; j++)
            {
                items.Remove(itemsToRemove[j]);
            }
        }

Convert an object to an XML string

This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.

public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(keyFather);
            foreach (var objeto in anyObject)
            {
                writer.WriteStartElement(keySon);
                foreach (PropertyDescriptor item in props)
                {
                    writer.WriteStartElement(item.DisplayName);
                    writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return builder.ToString();
        }
    }

Where is the itoa function in Linux?

direct copy to buffer : 64 bit integer itoa hex :

    char* itoah(long num, char* s, int len)
    {
            long n, m = 16;
            int i = 16+2;
            int shift = 'a'- ('9'+1);


            if(!s || len < 1)
                    return 0;

            n = num < 0 ? -1 : 1;
            n = n * num;

            len = len > i ? i : len;
            i = len < i ? len : i;

            s[i-1] = 0;
            i--;

            if(!num)
            {
                    if(len < 2)
                            return &s[i];

                    s[i-1]='0';
                    return &s[i-1];
            }

            while(i && n)
            {
                    s[i-1] = n % m + '0';

                    if (s[i-1] > '9')
                            s[i-1] += shift ;

                    n = n/m;
                    i--;
            }

            if(num < 0)
            {
                    if(i)
                    {
                            s[i-1] = '-';
                            i--;
                    }
            }

            return &s[i];
    }

note: change long to long long for 32 bit machine. long to int in case for 32 bit integer. m is the radix. When decreasing radix, increase number of characters (variable i). When increasing radix, decrease number of characters (better). In case of unsigned data type, i just becomes 16 + 1.

Upgrade python without breaking yum

I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.

Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.

If that is not possible, the above is entirely workable and tested.

Change:

#!/usr/bin/python

to whatever the path is of your old version until you can make the above yum improvement.

Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.

FCM getting MismatchSenderId

Just an FYI. I was running into this error, even though I swear the android app I was testing was built with the latest/greatest google-services.json file and I could send from the FCM console to the app. I rebuilt the app after doing a Clean Project and now I can send to the app with the FCM token it registers. So, maybe try a clean rebuild before beating your head against the wall for too long.

Java - Search for files in a directory

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Deepankar Sinha
 */
public class GetList {
    public List<String> stack;
    static List<String> lnkFile;
    static List<String> progName;

    int index=-1;
    public static void main(String args[]) throws IOException
    {

        //var-- progFile:Location of the file to be search. 
        String progFile="C:\\";
        GetList obj=new GetList();
        String temp=progFile;
        int i;
        while(!"&%@#".equals(temp))
        {
            File dir=new File(temp);
            String[] directory=dir.list();
            if(directory!=null){
            for(String name: directory)
            {
                if(new File(temp+name).isDirectory())
                    obj.push(temp+name+"\\");
                else
                    if(new File(temp+name).isFile())
                    {
                        try{
                            //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                        if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                        {
                            //obj.addFile(temp+name,name);
                            System.out.println(temp+name);
                        }
                        }catch(StringIndexOutOfBoundsException e)
                        {
                            //debug purpose
                            System.out.println("ERROR******"+temp+name);
                        }

                    }
            }}
            temp=obj.pop();
        }
        obj.display();

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

    public GetList() {
        this.stack = new ArrayList<>();
        this.lnkFile=new ArrayList<>();
        this.progName=new ArrayList<>();
    }
    public void push(String dir)
    {
        index++;
        //System.out.println("PUSH : "+dir+" "+index);
        this.stack.add(index,dir);

    }
    public String pop()
    {
        String dir="";
        if(index==-1)
            return "&%@#";
        else
        {
            dir=this.stack.get(index);
            //System.out.println("POP : "+dir+" "+index);
            index--;

        }
        return dir;
    }

    public void addFile(String name,String name2)
    {
        lnkFile.add(name);
        progName.add(name2);
    }

    public void display()
    {
        GetList.lnkFile.stream().forEach((lnkFile1) -> {
            System.out.println(lnkFile1);
        });
    }

}

How to search JSON tree with jQuery

Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:

var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
    var person_i = persons[i];
    if(person_i["name"] == mySearchForName) {
        // found ! do something with 'person_i'.
        break;
    }
}
// not found !

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How to add data to DataGridView

first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.

this.dataGridView1.Rows.Add("1", "XX");

how to change onclick event with jquery?

You can easily change the onclick event of an element with jQuery without running the new function with:

$("#id").attr("onclick","new_function_name()");

By writing this line you actually change the onclick attribute of #id.

You can also use:

document.getElementById("id").attribute("onclick","new_function_name()");

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Strings and character with printf

You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:

  • In a type, * means a pointer. int is an integer type, int* is a pointer to integer type
  • As a prefix operator, * means 'dereference'. name is a pointer, *name is the result of dereferencing it (i.e. getting the value that the pointer points to)
  • Of course, as an infix operator, * means 'multiply'.

Are PHP Variables passed by value or by reference?

It's by value according to the PHP Documentation.

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

How to check the input is an integer or not in Java?

Using Integer.parseIn(String), you can parse string value into integer. Also you need to catch exception in case if input string is not a proper number.

int x = 0;

try {       
    x = Integer.parseInt("100"); // Parse string into number
} catch (NumberFormatException e) {
    e.printStackTrace();
}

The 'json' native gem requires installed build tools

Follow the Instructions from the Ruby Installer Developer Kit Wiki:

  1. Download Ruby 1.9.3 from rubyinstaller.org
  2. Download DevKit file from rubyinstaller.org
  3. Extract DevKit to path C:\Ruby193\DevKit
  4. Run cd C:\Ruby193\DevKit
  5. Run ruby dk.rb init
  6. Run ruby dk.rb review
  7. Run ruby dk.rb install

To return to the problem at hand, you should be able to install JSON (or otherwise test that your DevKit successfully installed) by running the following commands which will perform an install of the JSON gem and then use it:

gem install json --platform=ruby
ruby -rubygems -e "require 'json'; puts JSON.load('[42]').inspect"

JavaScript - Get Portion of URL Path

In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse

const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');

According to the documentation, it extracts the following parts:

The returned url instance contains the following properties:

protocol: The protocol scheme of the URL (e.g. http:). slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//). auth: Authentication information portion (e.g. username:password). username: Username of basic authentication. password: Password of basic authentication. host: Host name with port number. hostname: Host name without port number. port: Optional port number. pathname: URL path. query: Parsed object containing query string, unless parsing is set to false. hash: The "fragment" portion of the URL including the pound-sign (#). href: The full URL. origin: The origin of the URL.

Executing multiple SQL queries in one statement with PHP

Pass 65536 to mysql_connect as 5th parameter.

Example:

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) 
    or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.

For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);
    SELECT * FROM table2;
");

Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    SELECT * FROM table2;
    INSERT INTO table1 (field1,field2) VALUES(1,2);
");

How do I dynamically set HTML5 data- attributes using react?

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

Python find elements in one list that are not in the other

You can use sets:

main_list = list(set(list_2) - set(list_1))

Output:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> set(list_2) - set(list_1)
set(['m', 'f'])
>>> list(set(list_2) - set(list_1))
['m', 'f']

Per @JonClements' comment, here is a tidier version:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> list(set(list_2).difference(list_1))
['m', 'f']

Importing a long list of constants to a Python file

If you really want constants, not just variables looking like constants, the standard way to do it is to use immutable dictionaries. Unfortunately it's not built-in yet, so you have to use third party recipes (like this one or that one).

Isn't the size of character in Java 2 bytes?

Java stores all it's "chars" internally as two bytes. However, when they become strings etc, the number of bytes will depend on your encoding.

Some characters (ASCII) are single byte, but many others are multi-byte.

Java supports Unicode, thus according to:

Java Character Docs

The max value supported is "\uFFFF" (hex FFFF, dec 65535), or 11111111 11111111 binary (two bytes).

MySQL duplicate entry error even though there is no duplicate entry

In case this helps anyone besides the OP, I had a similar problem using InnoDB.

For me, what was really going on was a foreign key constraint failure. I was referencing a foreign key that did not exist.

In other words, the error was completely off. The primary key was fine, and inserting the foreign key first fixed the problem. No idea why MySQL got this wrong suddenly.

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I ran into this issue after updating the Java JDK, but had not yet restarted my command prompt. After restarting the command prompt, everything worked fine. Presumably, because the PATH variable need to be reset after the JDK update.

Representing null in JSON

null is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.

There is only one way to represent null in JSON. Per the specs (RFC 4627 and json.org):

2.1.  Values

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

  false null true

enter image description here

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

In my case, my maven variable environment was M2_HOME, so I've changed to MAVEN_HOME and worked.

TortoiseSVN icons overlay not showing after updating to Windows 10

Had same issue, and was solved by running regedit, erasing some entries in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers and restarting. Deleting OneDrive1... enties was not permited, but I had some from Google Drive. You can also make a bakup by double-clicking in the registry directory and doing an "Export" to a file.

On Windows 10, most of the entries are used by OneDrive and you won't have permission to remove them. In order to do so, right click on the entry (Example: "OneDrive1", then click "Advanced", then click the link labled "Change" at the very top next to "Owner". This lets you change the owner. Type in your username and hit OK. Now give yourself "Full Control" and then apply it. Now you should be able to delete or rename it.

Pandas KeyError: value not in index

I had the same issue.

During the 1st development I used a .csv file (comma as separator) that I've modified a bit before saving it. After saving the commas became semicolon.

On Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

When testing from a brand new file I encountered that issue.

I've removed the 'sep' argument in read_csv method before:

df1 = pd.read_csv('myfile.csv', sep=',');

after:

df1 = pd.read_csv('myfile.csv');

That way, the issue disappeared.

Android: Bitmaps loaded from gallery are rotated in ImageView

Have you looked at the EXIF data of the images? It may know the orientation of the camera when the picture was taken.

Correct Semantic tag for copyright info - html5

In a link, if you put rel=license it: Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Source: http://www.w3.org/wiki/HTML/Elements/link

So, for example, <a rel="license" href="https://creativecommons.org/licenses/by/4.0/">Copyrighted but you can use what's here as long as you credit me</a> gives a human something to read and lets computers know that the rest of the page is licensed under the CC BY 4.0 license.

How to loop through an associative array and get the key?

You can do:

foreach ($arr as $key => $value) {
 echo $key;
}

As described in PHP docs.

Delaying function in swift

Swift 3 and Above Version(s) for a delay of 10 seconds

    DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
        self.functionToCall()
    }

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.

enter image description here

Issue with background color and Google Chrome

My Cascading Style Sheet used:

body {background-color: #FAF0E6; font-family: arial, sans-serif }

It worked in Internet Explorer but failed in Firefox and Chrome. I changed it to:

body {background: #FAF0E6; font-family: arial, sans-serif }

(i.e. I removed -color.)

It works in all three browsers. (I had to restart Chrome.)

How to programmatically clear application data

From API version 19 it is possible to call ActivityManager.clearApplicationUserData().

((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();

transparent navigation bar ios

Swift Solution

This is the best way that I've found. You can just paste it into your appDelegate's didFinishLaunchingWithOptions method:

Swift 3 / 4

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    // Sets background to a blank/empty image
    UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
    // Sets shadow (line below the bar) to a blank image
    UINavigationBar.appearance().shadowImage = UIImage()
    // Sets the translucent background color
    UINavigationBar.appearance().backgroundColor = .clear
    // Set translucent. (Default value is already true, so this can be removed if desired.)
    UINavigationBar.appearance().isTranslucent = true
    return true
}

Swift 2.0

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    // Sets background to a blank/empty image
    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default)
    // Sets shadow (line below the bar) to a blank image
    UINavigationBar.appearance().shadowImage = UIImage()
    // Sets the translucent background color
    UINavigationBar.appearance().backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
    // Set translucent. (Default value is already true, so this can be removed if desired.)
    UINavigationBar.appearance().translucent = true

    return true
}

source: Make navigation bar transparent regarding below image in iOS 8.1

Reading a key from the Web.Config using ConfigurationManager

Full Path for it is

System.Configuration.ConfigurationManager.AppSettings["KeyName"]

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

How to use SortedMap interface in Java?

TreeMap, which is an implementation of the SortedMap interface, would work.

How do I use it ?

Map<Float, MyObject> map = new TreeMap<Float, MyObject>();

How to access Spring MVC model object in javascript file?

Here is an example of how i made a list object available for javascript:

var listForJavascript = [];
<c:forEach items="${MyListFromJava}" var="listItem">
  var arr = [];

  arr.push("<c:out value="${listItem.param1}" />");
  arr.push("<c:out value="${listItem.param2}" />");

  listForJavascript.push(arr);
</c:forEach>

Making a cURL call in C#

Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.

or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.

How to parse a string to an int in C++?

The good 'old C way still works. I recommend strtol or strtoul. Between the return status and the 'endPtr', you can give good diagnostic output. It also handles multiple bases nicely.

How do I clear/delete the current line in terminal?

or if your using vi mode, hit Esc followed by cc

to get back what you just erased, Esc and then p :)

When to use an interface instead of an abstract class and vice versa?

in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality

How to style a JSON block in Github Wiki?

```javascript
{ "some": "json" }
```

I tried using json but didn't like the way it looked. javascript looks a bit more pleasing to my eye.

Compiling simple Hello World program on OS X via command line

Use the following for multiple .cpp files

g++ *.cpp
./a.out

html5 - canvas element - Multiple layers

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.

running multiple bash commands with subprocess

I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen, but it wasn't possible in my situation.

What I ended up doing is something like:

commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out

So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen constructor.

How to clear Flutter's Build cache?

I tried flutter clean and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

How to skip a iteration/loop in while-loop

while(rs.next())
  {
    if(f.exists() && !f.isDirectory())
      continue;  //then skip the iteration

     else
     {
     //proceed
     }
  }

How to open a website when a Button is clicked in Android application?

If you are talking about an RCP app, then what you need is the SWT link widget.

Here is the official link event handler snippet.

Update

Here is minimalist android application to connect to either superuser or stackoverflow with 2 buttons.

package ap.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class LinkButtons extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void goToSo (View view) {
        goToUrl ( "http://stackoverflow.com/");
    }

    public void goToSu (View view) {
        goToUrl ( "http://superuser.com/");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

}

And here is the layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/select" />
    <Button android:layout_height="wrap_content" android:clickable="true" android:autoLink="web" android:cursorVisible="true" android:layout_width="match_parent" android:id="@+id/button_so" android:text="StackOverflow" android:linksClickable="true" android:onClick="goToSo"></Button>
    <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"></Button>
</LinearLayout>

CakePHP 3.0 installation: intl extension missing from system

I'm using Mac OS High Sierra and none of these worked for me. But after searching a lot I found one that worked!

This may seem trivial, but in fact about 2 months ago some clever guys made changes in brew repository, so doing just: brew install php71-intl will show you error with message that such recipe doesn’t exists.

Fortunately, there is. There is temporary fix in another brew repo, so all you have to do is:

brew tap kyslik/homebrew-php
brew install kyslik/php/php71-intl

SOURCE: http://blastar.biz/2018/04/14/how-to-enable-php-intl-extension-for-php-7-1-using-xampp-on-macos-high-sierra/

Unit testing click event in Angular

I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52) by using the tick function with the same (or greater) amount of milliseconds as in original setTimeout call.

For example, if I had a setTimeout(() => {...}, 2500); (so it will trigger after 2500 ms), I would call tick(2500), and that would solve the problem.

What I had in my component, as a reaction on a Delete button click:

delete() {
    this.myService.delete(this.id)
      .subscribe(
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
            this.router.navigate(['/home']);
          }, 2500); // I wait for 2.5 seconds before redirect
        });
  }

Her is my working test:

it('should delete the entity', fakeAsync(() => {
    component.id = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    expect(myService.getMyThing).toHaveBeenCalledWith(1);
    // more expects here..
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
    deleteButton.click(); // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    expect(myService.delete).toHaveBeenCalledWith(1);
    // more expects here..
  }));

P.S. Great explanation on fakeAsync and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Well this worked for me

rvm pkg install openssl
rvm reinstall 1.9.2 --with-openssl-dir=$rvm_path/usr

Something is wrong with openssl implementation of my ubuntu 12.04

How to join two tables by multiple columns in SQL?

Yes: You can use Inner Join to join on multiple columns.

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

Create table

CREATE TABLE MyNewTab(CaseNum int, FileNum int,
    ActivityNum int, Grade int, Score varchar(100))

Insert values

INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score)
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

What is SOA "in plain english"?

from ittoolbox blogs.

The following outlines the similarities and differences to past design techniques:

• SOA versus Structured Programming o Similarities: Most similar to subroutine calls where parameters are passed and the operation of the function is abstracted from the caller - e.g. CICS link and execute and the COBOL CALL reserved word. Copybooks are used to define data structure which is typically defined as an XML schema for services. o Differences: SOA is loosely coupled implying changes to a service have less impact to the consumer (the "calling" program) and services are interoperable across languages and platforms.

• SOA versus OOA/OOD o Similarities: Encapsulation, Abstraction and Defined Interfaces o Differences: SOA is loosely coupled with no class hierarchy or inheritance, Low-level abstractions - class level versus business service

• SOA versus legacy Component Based Development (CBD) - e.g. CORBA, DCOM, EJB o Similarities: Reuse through assembling components, Interfaces, Remote calls o Differences: Wide adoption of standards, XML Schemas vs. Marshaled Objects, Service Orchestration, Designing for reuse is easier, services are business focused vs. IT focused, business services are course grained (broad in scope)

• SOA (for integration) versus Enterprise Application Integration (EAI) o Similarities: Best practices (well defined interfaces, standardized schemas, event driven architecture), reusable interfaces, common schemas o Differences: Standards, adoption, and improved tools

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

MySQL: how to get the difference between two timestamps in seconds

Note that the TIMEDIFF() solution only works when the datetimes are less than 35 days apart! TIMEDIFF() returns a TIME datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)

Python SQL query string formatting

Using 'sqlparse' library we can format the sqls.

>>> import sqlparse
>>> raw = 'select * from foo; select * from bar;'
>>> print(sqlparse.format(raw, reindent=True, keyword_case='upper'))
SELECT *
FROM foo;

SELECT *
FROM bar;

Ref: https://pypi.org/project/sqlparse/

How to install mechanize for Python 2.7?

You need to follow the installation instructions and not just download the files into your Python27 directory. It has to be installed in the site-packages directory properly, which the directions tell you how to do.

What is the hamburger menu icon called and the three vertical dots icon called?

Look at this photo, it says "Kebab Menu" is a correct answer:

enter image description here

per comment below, sourced from Luke Wroblewski: https://twitter.com/lukew/status/591296890030915585/photo/1

Simple PHP Pagination script

Some of the tutorials I found that are easy to understand are:

It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.

A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff

The script:

// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db 
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
   // echo data
   echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>

This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.

Remove a prefix from a string

I don't know about "standard way".

def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    return text  # or whatever

As noted by @Boris and @Stefan, on Python 3.9+ you can use

text.removeprefix(prefix)

with the same behavior.

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

Switch on ranges of integers in JavaScript

This does not require a switch statement. It is clearer, more concise, faster, and optimises better, to use if else statements...

var d = this.dealer;
if (1 <= d && d <= 11) { // making sure in range 1..11
    if (d <= 4) {
        alert("1 to 4");
    } else if (d <= 8) {
        alert("5 to 8");
    } else {
        alert("9 to 11");
    }
} else {
    alert("not in range");
}

Speed test

I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/

  • Chrome: switch was around 70% slower than if else

  • Firefox: switch was around 5% slower than if else

  • IE: switch was around 5% slower than if else

  • Safari: switch was around 95% slower than if else

Notes:

Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.

For numeric ranges, I like to use this kind of construction...

if (1 <= d && d <= 11) {...}

... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".

Clearer

A few people don't think this is clearer. I'd say it is not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense.

My concern, with "switch (true)", is that it can appear to be a meaningless line of code. Many coders, reading that will not know what to make of it.

For my own code, I'm more willing to use obscure structures from time to time, but if anyone else will look at it, I try to use clearer constructs. I think it is better to use the constructs for what they are intended.

Optimisation

In a modern environment, code is often going to be minified for production, so you can write clear concise code, with readable variable names and helpful comments. There's no clear reason to use switch in this way.

I also tried putting both constructs through a minifier. The if/else structure compresses well, becoming a single short expression using nested ternary operators. The switch statement when minified remains a switch, complete with "switch", "case" and "break" tokens, and as a result is considerably longer in code.

How switch(true) works

I think "switch(true) is obscure, but it seems some people just want to use it, so here's an explanation of why it works...

A switch/case statement works by matching the part in the switch with each case, and then executing the code on the first match. In most use cases, we have a variable or non-constant expression in the switch, and then match it.

With "switch(true), we will find the first expression in the case statements that is true. If you read "switch (true)" as "find the first expression that is true", the code feels more readable.

Difference between static and shared libraries?

On top of all the other answers, one thing not mentionned yet is decoupling :

Let me speak about a real world production code,that I have been dealing with :

A very big software, made of >300 projects (with visual studio), mostly build as static lib and finally all link together in one huge executable , you end up with the following problems :

-Link time is extremely long. You might end up by more than 15min of link, for let's say 10s of compilation time -Some tools are on their knee with such a big executable , like memory check tools that must instrument the code. You might fall into reaching limits that had been seen as fools.

More problematic is the decoupling of your software : on this real world example, headers files of every project were reacheable from any others projects. As a consequence it was extremely easy for one developer to add dependencies; it was just about including the header, because link at the end will allwaws find symbols. It ends up by horrible cycling dependencies and complete mess.

With shared library, it's a bit of extra work because developer must edit the project build system to add the dependent library. I observed that shared library code tends to offer a cleaner code API.

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Div Size Automatically size of content

The best way to do this is to set display: inline;. Note, however, that in inline display, you lose access to some layout properties, such as manual height and vertical margins, but this doesn't appear to be a problem for your page.

Android Drawing Separator/Divider Line in Layout?

I usually use this code to add horizontal line:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

To add vertical separator, switch the layout_width and layout_height values

If else embedding inside html

I recommend the following syntax for readability.

<? if ($condition): ?>
  <p>Content</p>
<? elseif ($other_condition): ?>
  <p>Other Content</p>
<? else: ?>
  <p>Default Content</p>
<? endif; ?>

Note, omitting php on the open tags does require that short_open_tags is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

How to get line count of a large file cheaply in Python?

what about this?

import sys
sys.stdin=open('fname','r')
data=sys.stdin.readlines()
print "counted",len(data),"lines"

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Setting up and using Meld as your git difftool and mergetool

It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:

[merge]
    tool = mymeld
    conflictstyle = diff3

[mergetool "mymeld"]
    cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED

It looks strange but offers a very convenient work-flow, using three tabs:

  1. in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.

  2. in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).

  3. in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.

Notes:

  • don't edit anything in tab 1
  • don't save anything in tab 2 because that will produce annoying popups in tab 3

When to use React "componentDidUpdate" method?

Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.

Debug/run standard java in Visual Studio Code IDE and OS X?

I can tell you for Windows.

  1. Install Java Extension Pack and Code Runner Extension from VS Code Extensions.

  2. Edit your java home location in VS Code settings, "java.home": "C:\\Program Files\\Java\\jdk-9.0.4".

  3. Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.

  4. Create a simple Java program in Main.java file as:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");     
    }
}

Note: Do not add package in your main class.

  1. Right click anywhere on the java file and select run code.

  2. Check the output in the console.

Done, hope this helps.

Unresolved Import Issues with PyDev and Eclipse

Following, in my opinion will solve the problem

  1. Adding the init.py to your "~/Desktop/Python_Tutorials/diveintopython/py" folder
  2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any updates made to any System PythonPath)
  3. Add in the Interpreter with the same details as before (this will refresh your Python Interpreter setting with updates made to your PythonPath)
  4. Finally since your "~/Desktop/Python_Tutorials/diveintopython/py" folder not a standard PythonPath, you will need to add it in. There are two ways to do it

a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in "~/Desktop/Python_Tutorials/diveintopython/py" into a new PythonPath under Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter --> Libraries subtab --> NewFolder

Hope it helps.

check if a number already exist in a list in python

You could do

if item not in mylist:
     mylist.append(item)

But you should really use a set, like this :

myset = set()
myset.add(item)

EDIT: If order is important but your list is very big, you should probably use both a list and a set, like so:

mylist = []
myset = set()
for item in ...:
    if item not in myset:
        mylist.append(item)
        myset.add(item)

This way, you get fast lookup for element existence, but you keep your ordering. If you use the naive solution, you will get O(n) performance for the lookup, and that can be bad if your list is big

Or, as @larsman pointed out, you can use OrderedDict to the same effect:

from collections import OrderedDict

mydict = OrderedDict()
for item in ...:
    mydict[item] = True

How to discard all changes made to a branch?

Note: You CANNOT UNDO this.

Try git checkout -f this will discard any local changes which are not committed in ALL branches and master.

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

Print commit message of a given commit in git

git show is more a plumbing command than git log, and has the same formatting options:

git show -s --format=%B SHA1

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

Ignore mapping one property with Automapper

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

to be used as follow :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

thanks to Can Gencer for the tip :)

source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

i have tried this one for more projects and it worked for me. note that solution can configure your app for multidex:

android {
     compileSdkVersion 25
     buildToolsVersion "25.0.1"

     defaultConfig {
           ...
           minSdkVersion 9
           targetSdkVersion 25
     }

     buildTypes {
          release {
              shrinkResources true
              minifyEnabled true
              proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
          }
     }}

 dependencies {
       compile 'com.android.support:support-v4:25.1.0'
       compile 'com.google.android.gms:play-services:8.3.0'
       ...
 }

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

Good Free Alternative To MS Access

I'd the same problem of you. I had a MS access application but I wanted to go to a web application accessible to everybody and without paying money to MS. So I decided to use MySql and Wavemaker (open source) to get the scope..I'm very happy of this decision. and that's the result http://www.mara-database.org/

How to reset AUTO_INCREMENT in MySQL?

I suggest you to go to Query Browser and do the following:

  1. Go to schemata and find the table you want to alter.

  2. Right click and select copy create statement.

  3. Open a result tab and paste the create statement their.

  4. Go to the last line of the create statement and look for the Auto_Increment=N, (Where N is a current number for auto_increment field.)

  5. Replace N with 1.

  6. Press ctrl+enter.

Auto_increment should reset to one once you enter new row int the table.

I don't know what will happen if you try to add a row where an auto_increment field value already exist.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How to upload & Save Files with Desired name

 <html>
<head>
<title>PHP Reanme image example</title>
</head>
<body>

<form action="fileupload.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
Enter image name :<input type="text" name="filename"><br/>
<input type="submit" value="Upload" name="Submit1">

</form>

<?php

if(isset($_POST['Submit1']))
{ 


$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$name = $_POST["filename"];

move_uploaded_file($_FILES["file"]["tmp_name"], $name.".".$extension);
echo "Old Image Name = ". $_FILES["file"]["name"]."<br/>";
echo "New Image Name = " . $name.".".$extension;

}


?>
</body>
</html>

Click [here] (https://meeraacademy.com/php-rename-image-while-image-uploading/

Maven project.build.directory

You can find those maven properties in the super pom.

You find the jar here:

${M2_HOME}/lib/maven-model-builder-3.0.3.jar

Open the jar with 7-zip or some other archiver (or use the jar tool).

Navigate to

org/apache/maven/model

There you'll find the pom-4.0.0.xml.

It contains all those "short cuts":

<project>
    ...
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        ...
    </build>
    ...
</project>

Update

After some lobbying I am adding a link to the pom-4.0.0.xml. This allows you to see the properties without opening up the local jar file.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

As an extension to @LennartRegebro's answer:

If you can't tell what encoding your file uses and the solution above does not work (it's not utf8) and you found yourself merely guessing - there are online tools that you could use to identify what encoding that is. They aren't perfect but usually work just fine. After you figure out the encoding you should be able to use solution above.

EDIT: (Copied from comment)

A quite popular text editor Sublime Text has a command to display encoding if it has been set...

  1. Go to View -> Show Console (or Ctrl+`)

enter image description here

  1. Type into field at the bottom view.encoding() and hope for the best (I was unable to get anything but Undefined but maybe you will have better luck...)

enter image description here

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

This error message does not indicate a problem with Ionic, but rather with node-sass, which is specified to execute in your Gulp file.

The node-sass error:

Node Sass does not yet support your current environment

indicates that the version of node-sass you are trying to run is not compatible with the version of node installed.

Check the Node Sass release notes for the version of node-sass you have, to see which version of node is required.

If the version of node is wrong, you must downgrade node, or upgrade node-sass, until you have a compatible pair. If the node version is supported, you may just need to run:

npm rebuild node-sass

(with -g if node-sass was installed globally).

If that doesn't work, you can:

npm uninstall node-sass && npm install node-sass

(again, with -g if necessary).

This github issue has lots of more info on this.

Select multiple rows with the same value(s)

One way of doing this is via an exists clause:

select * from genes g
where exists
(select null from genes g1
 where g.locus = g1.locus and g.chromosome = g1.chromosome and g.id <> g1.id)

Alternatively, in MySQL you can get a summary of all matching ids with a single table access, using group_concat:

select group_concat(id) matching_ids, chromosome, locus 
from genes
group by chromosome, locus
having count(*) > 1

How can I copy a file on Unix using C?

#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#define    print_err(format, args...)   printf("[%s:%d][error]" format "\n", __func__, __LINE__, ##args)
#define    DATA_BUF_SIZE                (64 * 1024)    //limit to read maximum 64 KB data per time

int32_t get_file_size(const char *fname){
    struct stat sbuf;

    if (NULL == fname || strlen(fname) < 1){
        return 0;
    }

    if (stat(fname, &sbuf) < 0){
        print_err("%s, %s", fname, strerror(errno));
        return 0;
    }

    return sbuf.st_size; /* off_t shall be signed interge types, used for file size */
}

bool copyFile(CHAR *pszPathIn, CHAR *pszPathOut)
{
    INT32 fdIn, fdOut;
    UINT32 ulFileSize_in = 0;
    UINT32 ulFileSize_out = 0;
    CHAR *szDataBuf;

    if (!pszPathIn || !pszPathOut)
    {
        print_err(" Invalid param!");
        return false;
    }

    if ((1 > strlen(pszPathIn)) || (1 > strlen(pszPathOut)))
    {
        print_err(" Invalid param!");
        return false;
    }

    if (0 != access(pszPathIn, F_OK))
    {
        print_err(" %s, %s!", pszPathIn, strerror(errno));
        return false;
    }

    if (0 > (fdIn = open(pszPathIn, O_RDONLY)))
    {
        print_err("open(%s, ) failed, %s", pszPathIn, strerror(errno));
        return false;
    }

    if (0 > (fdOut = open(pszPathOut, O_CREAT | O_WRONLY | O_TRUNC, 0777)))
    {
        print_err("open(%s, ) failed, %s", pszPathOut, strerror(errno));
        close(fdIn);
        return false;
    }

    szDataBuf = malloc(DATA_BUF_SIZE);
    if (NULL == szDataBuf)
    {
        print_err("malloc() failed!");
        return false;
    }

    while (1)
    {
        INT32 slSizeRead = read(fdIn, szDataBuf, sizeof(szDataBuf));
        INT32 slSizeWrite;
        if (slSizeRead <= 0)
        {
            break;
        }

        slSizeWrite = write(fdOut, szDataBuf, slSizeRead);
        if (slSizeWrite < 0)
        {
            print_err("write(, , slSizeRead) failed, %s", slSizeRead, strerror(errno));
            break;
        }

        if (slSizeWrite != slSizeRead) /* verify wheter write all byte data successfully */
        {
            print_err(" write(, , %d) failed!", slSizeRead);
            break;
        }
    }

    close(fdIn);
    fsync(fdOut); /* causes all modified data and attributes to be moved to a permanent storage device */
    close(fdOut);

    ulFileSize_in = get_file_size(pszPathIn);
    ulFileSize_out = get_file_size(pszPathOut);
    if (ulFileSize_in == ulFileSize_out) /* verify again wheter write all byte data successfully */
    {
        free(szDataBuf);
        return true;
    }
    free(szDataBuf);
    return false;
}

Using switch statement with a range of value in each case?

No you can't do that. The best you can do is that

case 1:
case 2:
case 3:
case 4:
case 5: 
  System.Out.Println("testing case 1 to 5");
break;

How to invoke the super constructor in Python?

I use the following formula that extends previous answers:

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(self.__class__, self).__init__()

B()

This way you don't have to repeat the name of the class in the call to super. It can come handy if you are coding a large number of classes, and want to make your code in the initialiser methods independent of the class name.

sh: 0: getcwd() failed: No such file or directory on cited drive

Please check the directory path whether exists or not. This error comes up if the folder doesn't exists from where you are running the command. Probably you have executed a remove command from same path in command line.

What is the difference between char s[] and char *s?

As an addition, consider that, as for read-only purposes the use of both is identical, you can access a char by indexing either with [] or *(<var> + <index>) format:

printf("%c", x[1]);     //Prints r

And:

printf("%c", *(x + 1)); //Prints r

Obviously, if you attempt to do

*(x + 1) = 'a';

You will probably get a Segmentation Fault, as you are trying to access read-only memory.

Use RSA private key to generate public key?

Firstly a quick recap on RSA key generation.

  1. Randomly pick two random probable primes of the appropriate size (p and q).
  2. Multiply the two primes together to produce the modulus (n).
  3. Pick a public exponent (e).
  4. Do some math with the primes and the public exponent to produce the private exponent (d).

The public key consists of the modulus and the public exponent.

A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.

However:

  1. Practical private key formats nearly always store more than n and d.
  2. e is normally not picked randomly, one of a handful of well-known values is used. If e is one of the well-known values and you know d then it would be easy to figure out e by trial and error.

So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.

Sublime Text 2: How to delete blank/empty lines

Their is a more easily way to do that without regex. you have just to select the whole text. then go to: Edit--> Permute Lines --> Unique.

That's all. and all blank lines will be deleted.

Styling input radio with css

You should use some background image to your radio buttons and flip it with another image on change

.radio {
    background: url(customButton.png) no-repeat;
}

SQL Server 2000: How to exit a stored procedure?

This works over here.

ALTER PROCEDURE dbo.Archive_Session
    @SessionGUID int
AS 
    BEGIN
        SET NOCOUNT ON
        PRINT 'before raiserror'
        RAISERROR('this is a raised error', 18, 1)
        IF @@Error != 0 
            RETURN
        PRINT 'before return'
        RETURN -1
        PRINT 'after return'
    END
go

EXECUTE dbo.Archive_Session @SessionGUID = 1

Returns

before raiserror
Msg 50000, Level 18, State 1, Procedure Archive_Session, Line 7
this is a raised error

How to use Spring Boot with MySQL database and JPA?

In the spring boot reference,it said:

When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

In your cases. You must add scanBasePackages in the @SpringBootApplication annotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})

What is the default Jenkins password?

I was running Jenkins executing java -jar jenkins.war.

In my case Jenkins wrote webroot in an stdout: webroot: $user.home/.jenkins. So admin secret key was placed in a ~/.jenkins/secrets/initialAdminPassword.

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Paste text on Android Emulator

In a terminal, type adb shell input text 'my string here. With some characters escaped like \$ that'

Note that an alternative method for including spaces in the text is to substitute %s for each space character.

MSSQL Error 'The underlying provider failed on Open'

In IIS set the App Pool Identity As Service Account user or Administrator Account or ant account which has permission to do the operation on that DataBase.

Foreign key referencing a 2 columns primary key in SQL Server

Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Table Naming Dilemma: Singular vs. Plural Names

The system tables/views of the server itself (SYSCAT.TABLES, dbo.sysindexes, ALL_TABLES, information_schema.columns, etc.) are almost always plural. I guess for the sake of consistency I'd follow their lead.

Inline IF Statement in C#

You may define your enum like so and use cast where needed

public enum MyEnum
{
    VariablePeriods = 1,
    FixedPeriods = 2
}

Usage

public class Entity
{
    public MyEnum Property { get; set; }
}

var returnedFromDB = 1;
var entity = new Entity();
entity.Property = (MyEnum)returnedFromDB;

How to Store Historical Data

In SQL Server 2016 and above, there is a new feature called Temporal Tables that aims to solve this challenge with minimal effort from developer. The concept of temporal table is similar to Change Data Capture (CDC), with the difference that temporal table has abstracted most of the things that you had to do manually if you were using CDC.

Linux shell sort file according to the second column?

FWIW, here is a sort method for showing which processes are using the most virt memory.

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

offsetting an html anchor to adjust for fixed header

how about hidden span tags with linkable IDs that provide the height of the navbar:

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

heres the fiddle: http://jsfiddle.net/N6f2f/7

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

Disable hover effects on mobile browsers

What I've done to solve the same problem is to have a feature detection (I use something like this code), seeing if onTouchMove is defined, and if so I add the css class "touchMode" to the body, else i add "desktopMode".

Then every time some style effect only applies to a touch device, or only to a desktop the css rule is prepended with the appropriate class:

.desktopMode .someClass:hover{ color: red }
.touchMode .mainDiv { width: 100%; margin: 0; /*etc.*/ }

Edit: This strategy of course adds a few extra characters to your css, so If you're concerned about css size, you could search for the touchMode and desktopMode definitons and put them into different files, so you can serve optimized css for each device type; or you could change the class names to something much shorter before going to prod.

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

unexpected T_VARIABLE, expecting T_FUNCTION

check that you entered a variable as argument with the '$' symbol

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

nodejs get file name from absolute path?

var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
// returns
'python'

Above code returns the name of the file without extension, if you need the name with extention use

var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.basename(filepath);
// returns
'python.exe'

asp.net mvc @Html.CheckBoxFor

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
              new { id = string.Format("employmentType_{0}", i) })
}

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

tSQL - Conversion from varchar to numeric works for all but integer

Try this

declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end

and

declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I tried all of these and could not get my break-point working...

What i did to fix this issue was

In the page where my break-point was not hitting, i selected the folder > add an existing item and then select the page from its save path. This allowed the break point to start working.

How to use an array list in Java?

A three line solution, but works quite well:

int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
    target_list.add(random_array[i]);
}

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

It's because the name column on the bar table does not have the UNIQUE constraint.

So imagine you have 2 rows on the bar table that contain the name 'ams' and you insert a row on baz with 'ams' on bar_fk, which row on bar would it be referring since there are two rows matching?

How to loop through all the properties of a class?

Note that if the object you are talking about has a custom property model (such as DataRowView etc for DataTable), then you need to use TypeDescriptor; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}

This also provides easy access to things like TypeConverter for formatting:

    string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));

What is the difference between const and readonly in C#?

Apart from the apparent difference of

  • having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen.
  • 'const's are implicitly static. You use a ClassName.ConstantName notation to access them.

There is a subtle difference. Consider a class defined in AssemblyA.

public class Const_V_Readonly
{
  public const int I_CONST_VALUE = 2;
  public readonly int I_RO_VALUE;
  public Const_V_Readonly()
  {
     I_RO_VALUE = 3;
  }
}

AssemblyB references AssemblyA and uses these values in code. When this is compiled,

  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if tomorrow I'll update I_CONST_VALUE to 20 in the future. AssemblyB would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

So if you are confident that the value of the constant won't change use a const.

public const int CM_IN_A_METER = 100;

But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a readonly.

public readonly float PI = 3.14;

Update: Aku needs to get a mention coz he pointed this out first. Also I need to plug where I learned this.. Effective C# - Bill Wagner

Finding the mode of a list

For a number to be a mode, it must occur more number of times than at least one other number in the list, and it must not be the only number in the list. So, I refactored @mathwizurd's answer (to use the difference method) as follows:

def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list 
      - when no number occurs in the list 
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!" 

These tests pass successfully:

mode([]) == None 
mode([1]) == None
mode([1, 1]) == None 
mode([1, 1, 2, 2]) == None 

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

MySQL connection not working: 2002 No such file or directory

I had a similar problem and was able to solve it by addressing my mysql with 127.0.0.1 instead of localhost.

This probably means I've got something wrong in my hosts setup, but this quick fix get's me going for right now.

Reflection - get attribute name and value on property

If you just want one specific Attribute value For instance Display Attribute you can use the following code:

var pInfo = typeof(Book).GetProperty("Name")
                             .GetCustomAttribute<DisplayAttribute>();
var name = pInfo.Name;

Enable vertical scrolling on textarea

Maybe a fixed height and overflow-y: scroll;

How do I select elements of an array given condition?

For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

Pythonic way to create a long multi-line string

Try something like this. Like in this format it will return you a continuous line like you have successfully enquired about this property:

"message": f'You have successfully inquired about '
           f'{enquiring_property.title} Property owned by '
           f'{enquiring_property.client}'

How do I get the HTTP status code with jQuery?

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

Force browser to download image files on click

Update Spring 2018

<a href="/path/to/image.jpg" download="FileName.jpg">

While this is still supported, as of February 2018 chrome disabled this feature for cross-origin downloading meaning this will only work if the file is located on the same domain name.

I figured out a workaround for downloading cross domain images after Chrome's new update which disabled cross domain downloading. You could modify this into a function to suit your needs. You might be able to get the image mime-type (jpeg,png,gif,etc) with some more research if you needed to. There may be a way to do something similar to this with videos as well. Hope this helps someone!

Leeroy & Richard Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

_x000D_
_x000D_
var image = new Image();_x000D_
image.crossOrigin = "anonymous";_x000D_
image.src = "https://is3-ssl.mzstatic.com/image/thumb/Music62/v4/4b/f6/a2/4bf6a267-5a59-be4f-6947-d803849c6a7d/source/200x200bb.jpg";_x000D_
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually_x000D_
var fileName = image.src.split(/(\\|\/)/g).pop();_x000D_
image.onload = function () {_x000D_
    var canvas = document.createElement('canvas');_x000D_
    canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size_x000D_
    canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size_x000D_
    canvas.getContext('2d').drawImage(this, 0, 0);_x000D_
    var blob;_x000D_
    // ... get as Data URI_x000D_
    if (image.src.indexOf(".jpg") > -1) {_x000D_
    blob = canvas.toDataURL("image/jpeg");_x000D_
    } else if (image.src.indexOf(".png") > -1) {_x000D_
    blob = canvas.toDataURL("image/png");_x000D_
    } else if (image.src.indexOf(".gif") > -1) {_x000D_
    blob = canvas.toDataURL("image/gif");_x000D_
    } else {_x000D_
    blob = canvas.toDataURL("image/png");_x000D_
    }_x000D_
    $("body").html("<b>Click image to download.</b><br><a download='" + fileName + "' href='" + blob + "'><img src='" + blob + "'/></a>");_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Bin size in Matplotlib (Histogram)

This answer support the @ macrocosme suggestion.

I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.

Describe statistics. enter image description here

# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');

plt.colorbar();

enter image description here

How do I exit a while loop in Java?

To exit a while loop, use Break; This will not allow to loop to process any conditions that are placed inside, make sure to have this inside the loop, as you cannot place it outside the loop

How to efficiently remove duplicates from an array without using Set

public static void main(String args[]) {
    int[] intarray = {1,2,3,4,5,1,2,3,4,5,1,2,3,4,5};

    Set<Integer> set = new HashSet<Integer>();
    for(int i : intarray) {
        set.add(i);
    }

    Iterator<Integer> setitr = set.iterator();
    for(int pos=0; pos < intarray.length; pos ++) {
        if(pos < set.size()) {
            intarray[pos] =setitr.next();
        } else {
            intarray[pos]= 0;
        }
    }

    for(int i: intarray)
    System.out.println(i);
}

Constructor overload in TypeScript

In the case where an optional, typed parameter is good enough, consider the following code which accomplishes the same without repeating the properties or defining an interface:

export class Track {
   public title: string;
   public artist: string;
   public lyrics: string;

   constructor(track?: Track) {
     Object.assign(this, track);
   }
}

Keep in mind this will assign all properties passed in track, eve if they're not defined on Track.

How to install MySQLdb package? (ImportError: No module named setuptools)

#!/usr/bin/env python

import os
import sys
from **distutils.core** import setup, Extension

if sys.version_info < (2, 3):
    raise Error("Python-2.3 or newer is required")

if os.name == "posix":
    from setup_posix import get_config
else: # assume windows
    from setup_windows import get_config

metadata, options = get_config()
metadata['ext_modules'] = [Extension(sources=['_mysql.c'], **options)]
metadata['long_description'] = metadata['long_description'].replace(r'\n', '')
setup(**metadata)

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

Drop rows containing empty cells from a pandas DataFrame

Pandas will recognise a value as null if it is a np.nan object, which will print as NaN in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan objects using replace(), and then call dropna()on your DataFrame to delete rows with null tenants.

To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants column:

>>> import pandas as pd
>>> import numpy as np
>>> 
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239         
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214         
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640         

Now we replace any empty strings in the Tenants column with np.nan objects, like so:

>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239      NaN
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214      NaN
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640      NaN

Now we can drop the null values:

>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

How to find a string inside a entire database?

I usually use information_Schema.columns and information_schema.tables, although like @yuck said, sys.tables and sys.columns are shorter to type.

In a loop, concatenate these

@sql = @sql + 'select' + column_name + 
' from ' + table_name + 
' where ' + column_name ' like ''%''+value+''%' UNION

Then execute the resulting sql.

How do I create a readable diff of two spreadsheets using git diff?

If you're using Java, you could try simple-excel.

It'll diff spreadsheets using Hamcrest matchers and output something like this.

java.lang.AssertionError:
Expected: entire workbook to be equal
     but: cell at "C14" contained <"bananas"> expected <nothing>,
          cell at "C15" contained <"1,850,000 EUR"> expected <"1,850,000.00 EUR">,
          cell at "D16" contained <nothing> expected <"Tue Sep 04 06:30:00">
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)

I should qualify that we wrote that tool (like the ticked answer rolled their own).

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

Error: Execution failed for task ':app:clean'. Unable to delete file

I have tried to remove all the Java services but still it is failing while executing the gradlew clean build command from IntelliJ terminal. I even verified the other applications I have opened somewhere the same path which I am trying the delete. But could not find any of such. So, finally restarted the IntelliJ IDE and able to proceed build smoothly.

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

Replace transparency in PNG images with white background

Welp it looks like my decision to install "graphics magick" over "image magick" has some rough edges - when I reinstall genuine crufty old "image magick", then the above command works perfectly well.

edit, a long time later — One of these days I'll check to see if "graphics magick" has fixed this issue.