Programs & Examples On #Enterprise integration

Enterprise application integration (EAI) is the use of software and computer systems architectural principles to integrate a set of enterprise computer applications.

What exactly is Apache Camel?

Most "new" things in computing aren't really new at all, they're just a mystifying wrapper around something that already well-understood. When they're hard to understand, it's usually because someone decided to invent new language terms or colonise existing terms for a different purpose (a good example of that is the X developers' reversal of what "client" and "server" mean.)

Camel is a Java-based wrapper/API for inter-application middleware.

Middleware is a general term for software that provides interpretation services between entities that don't share a common language or data types.

That's what Camel is, at bottom. We can flesh out the description by noting that it provides for EIP-type middleware.

It doesn't provide the middleware itself, since it can't know the details of what the applications need to communicate. But it provides the API for creating the invariant parts of that middleware (create a start point, create an end point, create conditions for starting and ending, etc)

Hope that helps.

do { ... } while (0) — what is it good for?

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');

How to remove RVM (Ruby Version Manager) from my system

When using implode and you see:

Psychologist intervened, cancelling implosion, crisis avoided :)

Then you may want to use --force

rvm implode --force

Then remove RVM from the following locations:

rm -rf /usr/local/rvm
sudo rm /etc/profile.d/rvm.sh
sudo rm /etc/rvmrc
sudo rm ~/.rvmrc

Check the following files and remove or comment out references to RVM:

~/.bashrc 
~/.bash_profile 
~/.profile 
~/.zshrc
~/.zlogin

Comment-out/remove the following lines from /etc/profile:

 source /etc/profile.d/sm.sh
 source /etc/profile.d/rvm.sh

/etc/profile is a read-only file so use:

sudo vim /etc/profile

And after making the change write using a bang!

:w!

Finally re-login/restart your terminal.

Number input type that takes only integers?

Yes, HTML5 does. Try this code (w3school):

<!DOCTYPE html>
<html>
<body>

<form action="">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
  <input type="submit" />
</form>

</body>
</html>

See the min and max paremeter? I tried it using Chrome 19 (worked) and Firefox 12 (did not work).

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

I'm guessing that you are running Eclipse Mars, or an even earlier release. You need to upgrade to Eclipse Neon or later

Difference between Console.Read() and Console.ReadLine()?

The basic difference is:

int i = Console.Read();
Console.WriteLine(i);

paste above code and give input 'c', and the output will be 99. That is Console.Read give int value but that value will be the ASCII value of that..

On the other side..

string s = Console.ReadLine();
Console.WriteLine(s);

It gives the string as it is given in the input stream.

How to make return key on iPhone make keyboard disappear?

First you need to conform to the UITextFieldDelegate Protocol in your View/ViewController's header file like this:

@interface YourViewController : UIViewController <UITextFieldDelegate>

Then in your .m file you need to implement the following UITextFieldDelegate protocol method:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

[textField resignFirstResponder]; makes sure the keyboard is dismissed.

Make sure you're setting your view/viewcontroller to be the UITextField's delegate after you init the textfield in the .m:

yourTextField = [[UITextField alloc] initWithFrame:yourFrame];
//....
//....
//Setting the textField's properties
//....    
//The next line is important!!
yourTextField.delegate = self; //self references the viewcontroller or view your textField is on

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

This is all that is needed:

<!doctype html>
<script src="/path.js"></script>

design a stack such that getMinimum( ) should be O(1)

To getMin elements from Stack. We have to use Two stack .i.e Stack s1 and Stack s2.

  1. Initially, both stacks are empty, so add elements to both stacks

---------------------Recursively call Step 2 to 4-----------------------

  1. if New element added to stack s1.Then pop elements from stack s2

  2. compare new elments with s2. which one is smaller , push to s2.

  3. pop from stack s2(which contains min element)

Code looks like:

package Stack;
import java.util.Stack;
public class  getMin 
{  

        Stack<Integer> s1= new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();

        void push(int x)
        {
            if(s1.isEmpty() || s2.isEmpty())

            {
                 s1.push(x);
                 s2.push(x);
            }
            else
            {

               s1. push(x);
                int y = (Integer) s2.pop();
                s2.push(y);
                if(x < y)
                    s2.push(x);
                        }
        }
        public Integer pop()
        {
            int x;
            x=(Integer) s1.pop();
            s2.pop();
            return x;

        }
    public  int getmin()
        {
            int x1;
            x1= (Integer)s2.pop();
            s2.push(x1);
            return x1;
        }

    public static void main(String[] args) {
        getMin s = new getMin();
            s.push(10);
            s.push(20);
            s.push(30);
            System.out.println(s.getmin());
            s.push(1);
            System.out.println(s.getmin());
        }

}

Help with packages in java - import does not work

Okay, just to clarify things that have already been posted.

You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.

From the folder containing com, run:

$ javac com\company\example\MyClass.java

Then:

$ java com.company.example.MyClass
Hello from MyClass!

These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).

A short example

I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:

package testpackage;

import testpackage2.MyClass;

public class TestPackageClass {
    public static void main(String[] args) {
        System.out.println("Hello from testpackage.TestPackageClass!");
        System.out.println("Now accessing " + MyClass.NAME);
    }
}

Inside testpackage2, I created MyClass.java containing the following code:

package testpackage2;
public class MyClass {
    public static String NAME = "testpackage2.MyClass";
}

From the directory containing the two new folders, I ran:

C:\examples>javac testpackage\*.java

C:\examples>javac testpackage2\*.java

Then:

C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass

Does that make things any clearer?

Change CSS class properties with jQuery

Didn't find the answer I wanted, so I solved it myself:
modify a container div!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example

c#: getter/setter

With the release of C# 6, you can now do something like this for private properties.

public constructor()
{
   myProp = "some value";
}

public string myProp { get; }

C# - Insert a variable number of spaces into a string? (Formatting an output file)

I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:

string.Empty.PadRight(totalLength, (char)32);

An alternative approach: Create all spaces manually within a custom method and call it:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

And call it in your code to create white spaces: GetSpaces(14);

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How do I access call log for android?

use this method from everywhere with a context

private static String getCallDetails(Context context) {
    StringBuffer stringBuffer = new StringBuffer();
    Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
            null, null, null, CallLog.Calls.DATE + " DESC");
    int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = cursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);       
    while (cursor.moveToNext()) {
        String phNumber = cursor.getString(number);
        String callType = cursor.getString(type);
        String callDate = cursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = cursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {
        case CallLog.Calls.OUTGOING_TYPE:
            dir = "OUTGOING";
            break;
        case CallLog.Calls.INCOMING_TYPE:
            dir = "INCOMING";
            break;

        case CallLog.Calls.MISSED_TYPE:
            dir = "MISSED";
            break;
        }
        stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                + dir + " \nCall Date:--- " + callDayTime
                + " \nCall duration in sec :--- " + callDuration);
        stringBuffer.append("\n----------------------------------");
    }
    cursor.close();
    return stringBuffer.toString();
}

How can I drop all the tables in a PostgreSQL database?

As per Pablo above, to just drop from a specific schema, with respect to case:

select 'drop table "' || tablename || '" cascade;' 
from pg_tables where schemaname = 'public';

Apache default VirtualHost

I found the answer: I remembered that Apache uses the first block if no other matching block is found, so I've added a block without a serveralias at the top of the blocks:

NameVirtualHost *

<VirtualHost *>
    DocumentRoot /defaultdir/
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someOtherDir/
    ServerAlias ip.of.the.server
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someroot/
    ServerAlias domain.com *.domain.com
</VirtualHost>

Get the distance between two geo points

Just use the following method, pass it lat and long and get distance in meter:

private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
    double R = 6371000f; // Radius of the earth in m
    double dLat = (lat1 - lat2) * Math.PI / 180f;
    double dLon = (lon1 - lon2) * Math.PI / 180f;
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c;
    return d;
}

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In my case SSL certificate was invalid for iframe domain, so make sure that iframe URL you're trying to send messages to is opening w/o any issues (in case you load your iframe over https).

Convert String to System.IO.Stream

Try this:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);

and

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

Angular JS update input field after change

Create a directive and put a watch on it.

app.directive("myApp", function(){
link:function(scope){

    function:getTotal(){
    ..do your maths here

    }
    scope.$watch('one', getTotals());
    scope.$watch('two', getTotals());
   }

})

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

Simple, Call this methods in your Splash Screen: hash() and getCertificateSHA1Fingerprint(), and then then keys would be visible in log

private void hash() {


            PackageInfo info;
            try {

                info = getPackageManager().getPackageInfo(
                        this.getPackageName(), PackageManager.GET_SIGNATURES);

                for (android.content.pm.Signature signature : info.signatures) {
                    MessageDigest md;
                    md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    Log.e("sagar sha key", md.toString());
                    String something = new String(Base64.encode(md.digest(), 0));
                    Log.e("sagar Hash key", something);
                    System.out.println("Hash key" + something);
                }

            } catch (PackageManager.NameNotFoundException e1) {
                Log.e("name not found", e1.toString());
            } catch (NoSuchAlgorithmException e) {
                Log.e("no such an algorithm", e.toString());
            } catch (Exception e) {
                Log.e("exception", e.toString());
            }
        }

        private void getCertificateSHA1Fingerprint() {
            PackageManager pm = this.getPackageManager();
            String packageName = this.getPackageName();
            int flags = PackageManager.GET_SIGNATURES;
            PackageInfo packageInfo = null;
            try {
                packageInfo = pm.getPackageInfo(packageName, flags);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            Signature[] signatures = packageInfo.signatures;
            byte[] cert = signatures[0].toByteArray();
            InputStream input = new ByteArrayInputStream(cert);
            CertificateFactory cf = null;
            try {
                cf = CertificateFactory.getInstance("X509");
            } catch (CertificateException e) {
                e.printStackTrace();
            }
            X509Certificate c = null;
            try {
                c = (X509Certificate) cf.generateCertificate(input);
            } catch (CertificateException e) {
                e.printStackTrace();
            }
            String hexString = "";
            try {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                byte[] publicKey = md.digest(c.getEncoded());
                Log.e("sagar SHA",byte2HexFormatted(publicKey));
            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
            }
        }

        public static String byte2HexFormatted(byte[] arr) {
            StringBuilder str = new StringBuilder(arr.length * 2);
            for (int i = 0; i < arr.length; i++) {
                String h = Integer.toHexString(arr[i]);
                int l = h.length();
                if (l == 1) h = "0" + h;
                if (l > 2) h = h.substring(l - 2, l);
                str.append(h.toUpperCase());
                if (i < (arr.length - 1)) str.append(':');
            }
            return str.toString();
        }

Thank You.

How display only years in input Bootstrap Datepicker?

For bootstrap 3 datepicker. (Note the capital letters)

$("#datetimepicker").datetimepicker( {
  format: "YYYY",
  viewMode: "years"
});

How do I clear all options in a dropdown box?

Probably, not the cleanest solution, but it is definitely simpler than removing one-by-one:

document.getElementById("DropList").innerHTML = "";

Why does an image captured using camera intent gets rotated on some devices on Android?

The simplest solution for this problem:

captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,
                   characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION));

I am saving the image in jpg format.

How to Select Top 100 rows in Oracle?

Assuming that create_time contains the time the order was created, and you want the 100 clients with the latest orders, you can:

  • add the create_time in your innermost query
  • order the results of your outer query by the create_time desc
  • add an outermost query that filters the first 100 rows using ROWNUM

Query:

  SELECT * FROM (
     SELECT * FROM (
        SELECT 
          id, 
          client_id, 
          create_time,
          ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
        FROM order
      ) 
      WHERE rn=1
      ORDER BY create_time desc
  ) WHERE rownum <= 100

UPDATE for Oracle 12c

With release 12.1, Oracle introduced "real" Top-N queries. Using the new FETCH FIRST... syntax, you can also use:

  SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn = 1
  ORDER BY create_time desc
  FETCH FIRST 100 ROWS ONLY)

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

onchange event for html.dropdownlist

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

How to read data of an Excel file using C#?

Using OlebDB, we can read excel file in C#, easily, here is the code while working with Web-Form, where FileUpload1 is file uploading tool

   string path = Server.MapPath("~/Uploads/");
  if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
//get file path
filePath = path + Path.GetFileName(FileUpload1.FileName);
//get file extenstion
string extension = Path.GetExtension(FileUpload1.FileName);
//save file on "Uploads" folder of project
FileUpload1.SaveAs(filePath);

string conString = string.Empty;
//check file extension
switch (extension)
{
    case ".xls": //Excel 97-03.
        conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Excel03ConString;Extended Properties='Excel 8.0;HDR=YES'";
        break;
    case ".xlsx": //Excel 07 and above.
        conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel07ConString;Extended Properties='Excel 8.0;HDR=YES'";
        break;
}

//create datatable object
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);

//Use OldDb to read excel
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
    using (OleDbCommand cmdExcel = new OleDbCommand())
    {
        using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
        {
            cmdExcel.Connection = connExcel;

            //Get the name of First Sheet.
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();

            //Read Data from First Sheet.
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
            odaExcel.SelectCommand = cmdExcel;
            odaExcel.Fill(dt);
            connExcel.Close();
        }
    }
}

//bind datatable with GridView
GridView1.DataSource = dt;
GridView1.DataBind();

Source : https://qawithexperts.com/article/asp-net/read-excel-file-and-import-data-into-gridview-using-datatabl/209

Console application similar code example https://qawithexperts.com/article/c-sharp/read-excel-file-in-c-console-application-example-using-oledb/168

If you need don't want to use OleDB, you can try https://github.com/ExcelDataReader/ExcelDataReader which seems to have the ability to handle both formats (.xls and .xslx)

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

What methods of ‘clearfix’ can I use?

The overflow property can be used to clear floats with no additional mark-up:

.container { overflow: hidden; }

This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):

.container { zoom: 1; }

http://www.quirksmode.org/css/clearing.html

Should a function have only one return statement?

There are times when it is necessary for performance reasons (I don't want to fetch a different cache line kind of the same need as a continue; sometimes).

If you allocate resources (memory, file descriptors, locks, etc.) without using RAII then muliple returns can be error prone and are certainly duplicative as the releases need to be done manually multiple times and you must keep careful track.

In the example:

function()
{
    HRESULT error = S_OK;

    if(SUCCEEDED(Operation1()))
    {
        if(SUCCEEDED(Operation2()))
        {
            if(SUCCEEDED(Operation3()))
            {
                if(SUCCEEDED(Operation4()))
                {
                }
                else
                {
                    error = OPERATION4FAILED;
                }
            }
            else
            {
                error = OPERATION3FAILED;
            }
        }
        else
        {
            error = OPERATION2FAILED;
        }
    }
    else
    {
        error = OPERATION1FAILED;
    }

    return error;
}

I would have written it as:

function() {
    HRESULT error = OPERATION1FAILED;//assume failure
    if(SUCCEEDED(Operation1())) {

        error = OPERATION2FAILED;//assume failure
        if(SUCCEEDED(Operation3())) {

            error = OPERATION3FAILED;//assume failure
            if(SUCCEEDED(Operation3())) {

                error = OPERATION4FAILED; //assume failure
                if(SUCCEEDED(Operation4())) {

                    error = S_OK;
                }
            }
        }
    }
    return error;
}

Which certainly seems better.

This tends to be especially helpful in the manual resource release case as where and which releases are necessary is pretty straightforward. As in the following example:

function() {
    HRESULT error = OPERATION1FAILED;//assume failure
    if(SUCCEEDED(Operation1())) {

        //allocate resource for op2;
        char* const p2 = new char[1024];
        error = OPERATION2FAILED;//assume failure
        if(SUCCEEDED(Operation2(p2))) {

            //allocate resource for op3;
            char* const p3 = new char[1024];
            error = OPERATION3FAILED;//assume failure
            if(SUCCEEDED(Operation3(p3))) {

                error = OPERATION4FAILED; //assume failure
                if(SUCCEEDED(Operation4(p2,p3))) {

                    error = S_OK;
                }
            }
            //free resource for op3;
            delete [] p3;
        }
        //free resource for op2;
        delete [] p2;
    }
    return error;
}

If you write this code without RAII (forgetting the issue of exceptions!) with multiple exits then the deletes have to be written multiple times. If you write it with }else{ then it gets a little ugly.

But RAII makes the multiple exit resource issue moot.

ALTER TABLE to add a composite primary key

alter table table_name add primary key (col_name1, col_name2);

Playing .mp3 and .wav in Java?

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.

Maven: Non-resolvable parent POM

Inside relative path tag do as follows

<relative>{project_name}/pom.xml</relative>

and then RunAs-> Maven build

It worked for me.

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

How to filter a RecyclerView with a SearchView

I recommend modify the solution of @Xaver Kapeller with 2 things below to avoid a problem after you cleared the searched text (the filter didn't work anymore) due to the list back of adapter has smaller size than filter list and the IndexOutOfBoundsException happened. So the code need to modify as below

public void addItem(int position, ExampleModel model) {
    if(position >= mModel.size()) {
        mModel.add(model);
        notifyItemInserted(mModel.size()-1);
    } else {
        mModels.add(position, model);
        notifyItemInserted(position);
    }
}

And modify also in moveItem functionality

public void moveItem(int fromPosition, int toPosition) {
    final ExampleModel model = mModels.remove(fromPosition);
    if(toPosition >= mModels.size()) {
        mModels.add(model);
        notifyItemMoved(fromPosition, mModels.size()-1);
    } else {
        mModels.add(toPosition, model);
        notifyItemMoved(fromPosition, toPosition); 
    }
}

Hope that It could help you!

Understanding Python super() with __init__() methods

I'm trying to understand super()

The reason we use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).

In Python 3, we can call it like this:

class ChildB(Base):
    def __init__(self):
        super().__init__()

In Python 2, we were required to use it like this, but we'll avoid this here:

        super(ChildB, self).__init__()

Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:

        Base.__init__(self) # Avoid this.

I further explain below.

"What difference is there actually in this code?:"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super().__init__()

The primary difference in this code is that in ChildB you get a layer of indirection in the __init__ with super, which uses the class in which it is defined to determine the next class's __init__ to look up in the MRO.

I illustrate this difference in an answer at the canonical question, How to use 'super' in Python?, which demonstrates dependency injection and cooperative multiple inheritance.

If Python didn't have super

Here's code that's actually closely equivalent to super (how it's implemented in C, minus some checking and fallback behavior, and translated to Python):

class ChildB(Base):
    def __init__(self):
        mro = type(self).mro()
        check_next = mro.index(ChildB) + 1 # next after *this* class.
        while check_next < len(mro):
            next_class = mro[check_next]
            if '__init__' in next_class.__dict__:
                next_class.__init__(self)
                break
            check_next += 1

Written a little more like native Python:

class ChildB(Base):
    def __init__(self):
        mro = type(self).mro()
        for next_class in mro[mro.index(ChildB) + 1:]: # slice to end
            if hasattr(next_class, '__init__'):
                next_class.__init__(self)
                break

If we didn't have the super object, we'd have to write this manual code everywhere (or recreate it!) to ensure that we call the proper next method in the Method Resolution Order!

How does super do this in Python 3 without being told explicitly which class and instance from the method it was called from?

It gets the calling stack frame, and finds the class (implicitly stored as a local free variable, __class__, making the calling function a closure over the class) and the first argument to that function, which should be the instance or class that informs it which Method Resolution Order (MRO) to use.

Since it requires that first argument for the MRO, using super with static methods is impossible as they do not have access to the MRO of the class from which they are called.

Criticisms of other answers:

super() lets you avoid referring to the base class explicitly, which can be nice. . But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

It's rather hand-wavey and doesn't tell us much, but the point of super is not to avoid writing the parent class. The point is to ensure that the next method in line in the method resolution order (MRO) is called. This becomes important in multiple inheritance.

I'll explain here.

class Base(object):
    def __init__(self):
        print("Base init'ed")

class ChildA(Base):
    def __init__(self):
        print("ChildA init'ed")
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        print("ChildB init'ed")
        super().__init__()

And let's create a dependency that we want to be called after the Child:

class UserDependency(Base):
    def __init__(self):
        print("UserDependency init'ed")
        super().__init__()

Now remember, ChildB uses super, ChildA does not:

class UserA(ChildA, UserDependency):
    def __init__(self):
        print("UserA init'ed")
        super().__init__()

class UserB(ChildB, UserDependency):
    def __init__(self):
        print("UserB init'ed")
        super().__init__()

And UserA does not call the UserDependency method:

>>> UserA()
UserA init'ed
ChildA init'ed
Base init'ed
<__main__.UserA object at 0x0000000003403BA8>

But UserB does in-fact call UserDependency because ChildB invokes super:

>>> UserB()
UserB init'ed
ChildB init'ed
UserDependency init'ed
Base init'ed
<__main__.UserB object at 0x0000000003403438>

Criticism for another answer

In no circumstance should you do the following, which another answer suggests, as you'll definitely get errors when you subclass ChildB:

super(self.__class__, self).__init__()  # DON'T DO THIS! EVER.

(That answer is not clever or particularly interesting, but in spite of direct criticism in the comments and over 17 downvotes, the answerer persisted in suggesting it until a kind editor fixed his problem.)

Explanation: Using self.__class__ as a substitute for the class name in super() will lead to recursion. super lets us look up the next parent in the MRO (see the first section of this answer) for child classes. If you tell super we're in the child instance's method, it will then lookup the next method in line (probably this one) resulting in recursion, probably causing a logical failure (in the answerer's example, it does) or a RuntimeError when the recursion depth is exceeded.

>>> class Polygon(object):
...     def __init__(self, id):
...         self.id = id
...
>>> class Rectangle(Polygon):
...     def __init__(self, id, width, height):
...         super(self.__class__, self).__init__(id)
...         self.shape = (width, height)
...
>>> class Square(Rectangle):
...     pass
...
>>> Square('a', 10, 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: __init__() missing 2 required positional arguments: 'width' and 'height'

Python 3's new super() calling method with no arguments fortunately allows us to sidestep this issue.

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

Executing command line programs from within python

If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.

Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.

PostgreSQL: How to make "case-insensitive" query

You could also use POSIX regular expressions, like

SELECT id FROM groups where name ~* 'administrator'

SELECT 'asd' ~* 'AsD' returns t

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

Simplest code for array intersection in javascript

.reduce to build a map, and .filter to find the intersection. delete within the .filter allows us to treat the second array as though it's a unique set.

function intersection (a, b) {
  var seen = a.reduce(function (h, k) {
    h[k] = true;
    return h;
  }, {});

  return b.filter(function (k) {
    var exists = seen[k];
    delete seen[k];
    return exists;
  });
}

I find this approach pretty easy to reason about. It performs in constant time.

How get an apostrophe in a string in javascript

You can try the following:

theAnchorText = "I'm home";

OR

theAnchorText = 'I\'m home';

Difference between private, public, and protected inheritance

1) Public Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class remain public in Derived class.

So, other classes can use public members of Base class through Derived class object.

2) Protected Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class too become protected members of Derived class.

So, other classes can't use public members of Base class through Derived class object; but they are available to subclass of Derived.

3) Private Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected & public members of Base class become private members of Derived class.

So, no members of Base class can be accessed by other classes through Derived class object as they are private in Derived class. So, even subclass of Derived class can't access them.

Create a date from day month and year with T-SQL

Try CONVERT instead of CAST.

CONVERT allows a third parameter indicating the date format.

List of formats is here: http://msdn.microsoft.com/en-us/library/ms187928.aspx

Update after another answer has been selected as the "correct" answer:

I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.

How to pass a list from Python, by Jinja2 to JavaScript

To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.

You can achieve this by doing something like that:

The view

import json

@app.route('/')
def my_view():
    data = [1, 'foo']
    return render_template('index.html', data=json.dumps(data))

The template

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

Edit - exact answer

So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:

The view

import json

@app.route('/')
def my_view():
    data = [1, "foo"]
    return render_template('index.html', data=map(json.dumps, data))

The template

{% for item in data %}
    <span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}

Edit 2

In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.

Edit 3 (Security warning)

NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!

Otherwise, you would expose your application to XSS vulnerabilities!

How to round up with excel VBA round()?

I find the following function sufficient:

'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double

    If x = Round(x, digits) Then
        RoundUp = x
    Else
        RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
    End If

End Function

How to exclude file only from root folder in Git

Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]

/config.php
!/*/config.php

Later versions only require the following [tested on version 2.2.1]

/config.php

How to use concerns in Rails 4

I felt most of the examples here demonstrated the power of module rather than how ActiveSupport::Concern adds value to module.

Example 1: More readable modules.

So without concerns this how a typical module will be.

module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  def instance_method
    ...
  end

  module ClassMethods
    ...
  end
end

After refactoring with ActiveSupport::Concern.

require 'active_support/concern'

module M
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end

  class_methods do
    ...
  end

  def instance_method
    ...
  end
end

You see instance methods, class methods and included block are less messy. Concerns will inject them appropriately for you. That's one advantage of using ActiveSupport::Concern.


Example 2: Handle module dependencies gracefully.

module Foo
  def self.included(base)
    base.class_eval do
      def self.method_injected_by_foo_to_host_klass
        ...
      end
    end
  end
end

module Bar
  def self.included(base)
    base.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Foo # We need to include this dependency for Bar
  include Bar # Bar is the module that Host really needs
end

In this example Bar is the module that Host really needs. But since Bar has dependency with Foo the Host class have to include Foo (but wait why does Host want to know about Foo? Can it be avoided?).

So Bar adds dependency everywhere it goes. And order of inclusion also matters here. This adds lot of complexity/dependency to huge code base.

After refactoring with ActiveSupport::Concern

require 'active_support/concern'

module Foo
  extend ActiveSupport::Concern
  included do
    def self.method_injected_by_foo_to_host_klass
      ...
    end
  end
end

module Bar
  extend ActiveSupport::Concern
  include Foo

  included do
    self.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Bar # It works, now Bar takes care of its dependencies
end

Now it looks simple.

If you are thinking why can't we add Foo dependency in Bar module itself? That won't work since method_injected_by_foo_to_host_klass have to be injected in a class that's including Bar not on Bar module itself.

Source: Rails ActiveSupport::Concern

Bootstrap: how do I change the width of the container?

Add these piece of CSS in your css styling. Its better to add this after the bootstrap css file is added in order to overwrite the same.

html, body {
 height: 100%;
 max-width: 100%;
 overflow-x: hidden;
}`

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.

This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.

If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:

s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T

On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE

attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY 

Filter data.frame rows by a logical condition

This worked like magic for me.

celltype_hesc_bool = expr['cell_type'] == 'hesc'

expr_celltype_hesc = expr[celltype_hesc]

Check this blog post

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

If you have an NSRange, bridging to NSString works seamlessly. For example, I was doing some work with UITextFieldDelegate and I quickly wanted to compute the new string value when it asked if it should replace the range.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
    println("Got new string: ", newString)
}

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

LINQ Join with Multiple Conditions in On Clause

You can't do it like that. The join clause (and the Join() extension method) supports only equijoins. That's also the reason, why it uses equals and not ==. And even if you could do something like that, it wouldn't work, because join is an inner join, not outer join.

Unsupported major.minor version 52.0 when rendering in Android Studio

Android Studio behaves weird in the case. Even though you set the JDK version in File -> Project Structure -> SDK Location, Android Studio only uses this for compiling the files. When it runs these files it, for some reason, looks at the PATH variable to find where java is installed.

If you have an older version of java installed on your system, then your PATH variable will be pointing to that older version of java.

So you have to set your PATH to point to the same version of java that have set in your Android studio project settings.

In your ~/.bashrc or corresponding profile file add this:

export PATH="/Applications/studio.app/Contents/jre/jdk/Contents/Home/bin:$PATH"

In my case my project was configured to use java 1.8, but my system wide installation of java was java 1.7. This was causing the issue.

Output array to CSV in Ruby

Building on @boulder_ruby's answer, this is what I'm looking for, assuming us_eco contains the CSV table as from my gist.

CSV.open('outfile.txt','wb', col_sep: "\t") do |csvfile|
  csvfile << us_eco.first.keys
  us_eco.each do |row|
    csvfile << row.values
  end
end

Updated the gist at https://gist.github.com/tamouse/4647196

"The public type <<classname>> must be defined in its own file" error in Eclipse

Save this class in the file StaticDemo.java. Also you cant have more than one public classes in one file.

Difference between Math.Floor() and Math.Truncate()

Going by the Mathematical Definition of Floor, that is, "Greatest integer less than or equal to a number", This is completely unambiguous, whereas, Truncate just removes the fractional part, which is equivalent to round towards 0.

Are the shift operators (<<, >>) arithmetic or logical in C?

When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.

(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)

When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.

For example, assuming a 32 bit machine:

signed int x1 = 5;
assert((x1 >> 1) == 2);
signed int x2 = -5;
assert((x2 >> 1) == -3);
unsigned int x3 = (unsigned int)-5;
assert((x3 >> 1) == 0x7FFFFFFD);

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

With Swift 3, according to your needs, you may choose one of the two following ways to solve your problem.


1. Display the difference between two dates to the user

You can use a DateComponentsFormatter to create strings for your app’s interface. DateComponentsFormatter has a maximumUnitCount property with the following declaration:

var maximumUnitCount: Int { get set }

Use this property to limit the number of units displayed in the resulting string. For example, with this property set to 2, instead of “1h 10m, 30s”, the resulting string would be “1h 10m”. Use this property when you are constrained for space or want to round up values to the nearest large unit.

By setting maximumUnitCount's value to 1, you are guaranteed to display the difference in only one DateComponentsFormatter's unit (years, months, days, hours or minutes).

The Playground code below shows how to display the difference between two dates:

import Foundation

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
let timeDifference = dateComponentsFormatter.string(from: oldDate, to: newDate)

print(String(reflecting: timeDifference)) // prints Optional("5 hours")

Note that DateComponentsFormatter rounds up the result. Therefore, a difference of 4 hours and 30 minutes will be displayed as 5 hours.

If you need to repeat this operation, you can refactor your code:

import Foundation

struct Formatters {

    static let dateComponentsFormatter: DateComponentsFormatter = {
        let dateComponentsFormatter = DateComponentsFormatter()
        dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
        dateComponentsFormatter.maximumUnitCount = 1
        dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
        return dateComponentsFormatter
    }()

}

extension Date {
    
    func offset(from: Date) -> String? {
        return Formatters.dateComponentsFormatter.string(from: oldDate, to: self)
    }
    
}

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let timeDifference = newDate.offset(from: oldDate)
print(String(reflecting: timeDifference)) // prints Optional("5 hours")

2. Get the difference between two dates without formatting

If you don't need to display with formatting the difference between two dates to the user, you can use Calendar. Calendar has a method dateComponents(_:from:to:) that has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents

Returns the difference between two dates.

The Playground code below that uses dateComponents(_:from:to:) shows how to retrieve the difference between two dates by returning the difference in only one type of Calendar.Component (years, months, days, hours or minutes).

import Foundation

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: oldDate, to: newDate)
let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }

for (component, value) in arrayOfTuples {
    if let value = value, value > 0 {
        print(component, value) // prints hour 4
        break
    }
}

If you need to repeat this operation, you can refactor your code:

import Foundation

extension Date {
    
    func offset(from: Date) -> (Calendar.Component, Int)? {
        let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
        let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: from, to: self)
        let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }
        
        for (component, value) in arrayOfTuples {
            if let value = value, value > 0 {
                return (component, value)
            }
        }
        
        return nil
    }

}

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

if let (component, value) = newDate.offset(from: oldDate) {
    print(component, value) // prints hour 4
}

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

Simple way to copy or clone a DataRow?

It seems you don't want to keep the whole DataTable as a copy, because you only need some rows, right? If you got a creteria you can specify with a select on the table, you could copy just those rows to an extra backup array of DataRow like

DataRow[] rows = sourceTable.Select("searchColumn = value");

The .Select() function got several options and this one e.g. can be read as a SQL

SELECT * FROM sourceTable WHERE searchColumn = value;

Then you can import the rows you want as described above.

targetTable.ImportRows(rows[n])

...for any valid n you like, but the columns need to be the same in each table.

Some things you should know about ImportRow is that there will be errors during runtime when using primary keys!

First I wanted to check whether a row already existed which also failed due to a missing primary key, but then the check always failed. In the end I decided to clear the existing rows completely and import the rows I wanted again.

The second issue did help to understand what happens. The way I'm using the import function is to duplicate rows with an exchanged entry in one column. I realized that it always changed and it still was a reference to the row in the array. I first had to import the original and then change the entry I wanted.

The reference also explains the primary key errors that appeared when I first tried to import the row as it really was doubled up.

Outline effect to text

Text Shadow Generator

There are lots of great answers here. It would appear the text-shadow is probably the most reliable way to do this. I won't go into detail about how to do this with text-shadow since others have already done that, but the basic idea is that you create multiple text shadows around the text element. The larger the text outline, the more text shadows you need.

All of the answers submitted (as of this posting) provide static solutions for the text-shadow. I have taken a different approach and have written this JSFiddle that accepts outline color, blur, and width values as inputs and generates the appropriate text-shadow property for your element. Just fill in the blanks, check the preview, and click to copy the css and paste it into your stylesheet.


Needless Appendix

Apparently, answers that include a link to a JSFiddle cannot be posted unless they also contain code. You can completely ignore this appendix if you want to. This is the JavaScript from my fiddle that generates the text-shadow property. Please note that you do not need to implement this code in your own works:

function computeStyle() {
    var width = document.querySelector('#outline-width').value;
  width = (width === '') ? 0 : Number.parseFloat(width);
  var blur = document.querySelector('#outline-blur').value;
  blur = (blur === '') ? 0 : Number.parseFloat(blur);
  var color = document.querySelector('#outline-color').value;
  if (width < 1 || color === '') {
    document.querySelector('.css-property').innerText = '';
    return;
  }
    var style = 'text-shadow: ';
  var indent = false;
    for (var i = -1 * width; i <= width; ++i) {
    for (var j = -1 * width; j <= width; ++j) {
        if (! (i === 0 && j === 0 && blur === 0)) {
        var indentation = (indent) ? '\u00a0\u00a0\u00a0\u00a0' : '';
            style += indentation + i + "px " + j + "px " + blur + "px " + color + ',\n';
        indent = true;
      }
    }
  }
  style = style.substring(0, style.length - 2) + '\n;';
  document.querySelector('.css-property').innerText = style;

  var exampleBackground = document.querySelector('#example-bg');
  var exampleText = document.querySelector('#example-text');
  exampleBackground.style.backgroundColor = getOppositeColor(color);
  exampleText.style.color = getOppositeColor(color);
  var textShadow = style.replace(/text-shadow: /, '').replace(/\n/g, '').replace(/.$/, '').replace(/\u00a0\u00a0\u00a0\u00a0/g, '');
  exampleText.style.textShadow = textShadow;
}

Java HTML Parsing

You might be interested by TagSoup, a Java HTML parser able to handle malformed HTML. XML parsers would work only on well formed XHTML.

Why use getters and setters/accessors?

One relatively modern advantage of getters/setters is that is makes it easier to browse code in tagged (indexed) code editors. E.g. If you want to see who sets a member, you can open the call hierarchy of the setter.

On the other hand, if the member is public, the tools don't make it possible to filter read/write access to the member. So you have to trudge though all uses of the member.

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

Easiest way to read/write a file's content in Python

Simple like that:

    f=open('myfile.txt')
    s=f.read()
    f.close()

And do whatever you want with the content "s"

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

Get value of c# dynamic property via string

In .Net core 3.1 you can try like this

d?.value2 , d?.value3

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

What worked for me was simply to do the following:

open the php.ini file.

Under the DYNAMIC EXTENSIONS heading, comment out the following line as

;extension=php_java.dll

Restarted Apache and all was fine

Mercurial stuck "waiting for lock"

If it only happens on mapped drives it might be bug https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share. Using UNC path instead of drive letter seems to sidestep the issue.

How can I see if a Perl hash already has a certain key?

I would counsel against using if ($hash{$key}) since it will not do what you expect if the key exists but its value is zero or empty.

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

How do I timestamp every ping result?

The simpler option is just using ts(1) from moreutils (fairly standard on most distros).

$ ping 1.1.1.1 | ts 

Feb 13 12:49:17 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. 
Feb 13 12:49:17 64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=5.92 ms
Feb 13 12:49:18 64 bytes from 1.1.1.1: icmp_seq=2 ttl=57 time=5.30 ms
Feb 13 12:49:19 64 bytes from 1.1.1.1: icmp_seq=3 ttl=57 time=5.71 ms
Feb 13 12:49:20 64 bytes from 1.1.1.1: icmp_seq=4 ttl=57 time=5.86 ms

or

 ping 1.1.1.1 -I eth0 | ts "[%FT%X]"

Allows for the same strftime format strings as the shell/date workaround.

Installation of SQL Server Business Intelligence Development Studio

This worked for me:

Start /wait setup.exe /qb  ADDLOCAL=SQL_DTS,Client_Components,Connectivity,SQL_Tools90,SQL_WarehouseDevWorkbench,SQLXML,Tools_Legacy,SQL_Documentation,SQL_BooksOnline

Based off this TechNet Article:

https://technet.microsoft.com/en-us/library/ms144259(v=sql.90).aspx

Updating .class file in jar

A JAR file is just a .zip in disguise. The zipped folder contains .class files.

If you're on macOS:

  1. Rename the file to possess the '.zip' extension. e.g. myJar.jar -> myJar.zip.
  2. Decompress the '.zip' (double click on it). A new folder called 'myJar' will appear
  3. Find and replace the .class file with your new .class file.
  4. Select all the contents of the folder 'myJar' and choose 'Compress x items'. DO NOT ZIP THE FOLDER ITSELF, ONLY ITS CONTENTS

Miscellaneous - Compiling a single .class file, with reference to a original jar, on macOS

  1. Make a file myClass.java, containing your code.
  2. Open terminal from Spotlight.
  3. javac -classpath originalJar.jar myClass.java This will create your compiled class called myClass.class.

From here, follow the steps above. You can also use Eclipse to compile it, simply reference the original jar by right clicking on the project, 'Build Path' -> 'Add External Archives'. From here you should be able to compile it as a jar, and use the zip technique above to retrieve the class from the jar.

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

Clear text from textarea with selenium

In the most recent Selenium version, use:

driver.find_element_by_id('foo').clear()

What does MissingManifestResourceException mean and how to fix it?

I had the with a newly created F# project. The solution was to uncheck "Use standard resource names" in the project properties -> Application -> Resources / Specify how application resources will be managed. If you do not see the checkbox then update your Visual Studio! I have 15.6.7 installed. In 15.3.2 this checkbox is not there.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

You can use .on() to capture multiple events and then test for touch on the screen, e.g.:

$('#selector')
.on('touchstart mousedown', function(e){
  e.preventDefault();
  var touch = e.touches[0];
  if(touch){
    // Do some stuff
  }
  else {
    // Do some other stuff
  }
});

How do you test your Request.QueryString[] variables?

Eeee this is a karma risk...

I have a DRY unit-testable abstraction because, well, because there were too many querystring variables to keep on in a legacy conversion.

The code below is from a utility class whose constructor requires a NameValueCollection input (this.source) and the string array "keys" is because the legacy app was rather organic and had developed the possibility for several different strings to be a potential input key. However I kind of like the extensibility. This method inspects the collection for the key and returns it in the datatype required.

private T GetValue<T>(string[] keys)
{
    return GetValue<T>(keys, default(T));
}

private T GetValue<T>(string[] keys, T vDefault)
{
    T x = vDefault;

    string v = null;

    for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++)
    {
        v = this.source[keys[i]];
    }

    if (!String.IsNullOrEmpty(v))
    {
        try
        {
            x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T));
        }
        catch(Exception e)
        {
            //do whatever you want here
        }
    }

    return x;
}

How to read a single character at a time from a file in Python?

f = open('hi.txt', 'w')
f.write('0123456789abcdef')
f.close()
f = open('hej.txt', 'r')
f.seek(12)
print f.read(1) # This will read just "c"

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

angular.module('app')
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){
          element.html(html);
          $compile(element.contents())(scope);
        });
      }
    };
  });

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

Deprecated Java HttpClient - How hard can it be?

Relevant imports:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;

Usage:

HttpClient httpClient = HttpClientBuilder.create().build();

EDIT (after Jules' suggestion):

As the build() method returns a CloseableHttpClient which is-a AutoClosable, you can place the declaration in a try-with-resources statement (Java 7+):

try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

    // use httpClient (no need to close it explicitly)

} catch (IOException e) {

    // handle

}

How to split one string into multiple variables in bash shell?

read with IFS are perfect for this:

$ IFS=- read var1 var2 <<< ABCDE-123456
$ echo "$var1"
ABCDE
$ echo "$var2"
123456

Edit:

Here is how you can read each individual character into array elements:

$ read -a foo <<<"$(echo "ABCDE-123456" | sed 's/./& /g')"

Dump the array:

$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]="-" [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

If there are spaces in the string:

$ IFS=$'\v' read -a foo <<<"$(echo "ABCDE 123456" | sed 's/./&\v/g')"
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]=" " [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

How to check if a double value has no decimal part

You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.

double d = 10.0;
d /= 3.0; // d should be something like 3.3333333333333333333333...
d *= 3.0; // d is probably something like 9.9999999999999999999999...

// d should be 10.0 again but it is not, so you have to use rounding before comparing

d = myRound(d, 5); // d is something like 10.00000
if (fmod(d, 1.0) == 0)
  // No decimals
else
  // Decimals

If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/

Find package name for Android apps to use Intent to launch Market app from web

If you want this information in your phone, then best is to use an app like 'APKit' that shows the full package name of each app in you phone. This information can then be used in your phone.

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

just run these command

sudo apt-get install phpmyadmin php-mbstring php-gettext

sudo service apache2 restart

Or you can follow this post...

Check This Post

Seconds CountDown Timer

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

Removing index column in pandas when reading a csv

df.reset_index(drop=True, inplace=True)

How to clear a chart from a canvas so that hover events cannot be triggered?

for those who like me use a function to create several graphics and want to update them a block too, only the function .destroy() worked for me, I would have liked to make an .update(), which seems cleaner but ... here is a code snippet that may help.

var SNS_Chart = {};

// IF LABELS IS EMPTY (after update my datas)
if( labels.length != 0 ){

      if( Object.entries(SNS_Chart).length != 0 ){

            array_items_datas.forEach(function(for_item, k_arr){
                SNS_Chart[''+for_item+''].destroy();
            });

       }

       // LOOP OVER ARRAY_ITEMS
       array_items_datas.forEach(function(for_item, k_arr){

             // chart
             OPTIONS.title.text = array_str[k_arr];
             var elem = document.getElementById(for_item);
             SNS_Chart[''+for_item+''] = new Chart(elem, {
                 type: 'doughnut',
                 data: {
                     labels: labels[''+for_item+''],
                     datasets: [{
                        // label: '',
                        backgroundColor: [
                            '#5b9aa0',
                            '#c6bcb6',
                            '#eeac99',
                            '#a79e84',
                            '#dbceb0',
                            '#8ca3a3',
                            '#82b74b',
                            '#454140',
                            '#c1502e',
                            '#bd5734'
                        ],
                        borderColor: '#757575',
                        borderWidth : 2,
                        // hoverBackgroundColor : '#616161',
                        data: datas[''+for_item+''],
                     }]
                 },
                 options: OPTIONS

             });
             // chart
       });
       // END LOOP ARRAY_ITEMS

  }
 // END IF LABELS IS EMPTY ...

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Source

This is mine:

USE databasename; 
SHOW TABLES; 
SELECT FOUND_ROWS();

How to iterate over associative arrays in Bash

Welcome to input associative array 2.0!

    clear
    echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            echo -n "(pair $(( $i+1 )))"
            read -p ' Enter key: ' k
            read -p '         Enter value: ' v
            echo " "
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array 2.0!"

Output:

Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
         Enter value: Value#1

(pair 2) Enter key: Key Two
         Enter value: Value2

(pair 3) Enter key: Key3
         Enter value: Val3

(pair 4) Enter key: Key4
         Enter value: Value4


The keys are:  Key4 Key3 Key Number 1 Key Two
The values are:  Value4 Val3 Value#1 Value2

Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2

Thanks for using input associative array 2.0!

Input associative array 1.0

(keys and values that contain spaces are not supported)

    clear
    echo "Welcome to input associative array! (written by mO extraordinaire!)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            read -p 'Enter key and value separated by a space: ' k v
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array!"

Output:

Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100

The keys are:  h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are:  80 10 100 70 60 50 40 30 90 20

Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20

Thanks for using input associative array!

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

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

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

How to len(generator())

You can use reduce.

For Python 3:

>>> import functools
>>> def gen():
...     yield 1
...     yield 2
...     yield 3
...
>>> functools.reduce(lambda x,y: x + 1, gen(), 0)

In Python 2, reduce is in the global namespace so the import is unnecessary.

AndroidStudio SDK directory does not exists

  1. Open your project folder
  2. open local.properties in notepad++
  3. change sdk.dir to C:\Users\xxxx\AppData\Local\Android\Sdk
  4. save

After edit, resync again android studio.

How to replace four spaces with a tab in Sublime Text 2?

On main menu;

View -> Indentation -> Convert Indentation to Tabs / Spaces

Converting String to Int using try/except in Python

Firstly, try / except are not functions, but statements.

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

In Python 2.x:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

In Python 3.x

the syntax has changed slightly:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

How to find good looking font color if background color is known?

Okay, this is still not the best possible solution, but a nice point to start. I wrote a little Java app that calculates the contrast ratio of two colors and only processes colors with a ratio of 5:1 or better - this ratio and the formula I use has been released by the W3C and will probably replace the current recommendation (which I consider very limited). It creates a file in the current working dir named "chosen-font-colors.html", with the background color of your choice and a line of text in every color that passed this W3C test. It expects a single argument, being the background color.

E.g. you can call it like this

java FontColorChooser 33FFB4

then just open the generated HTML file in a browser of your choice and choose a color from the list. All colors given passed the W3C test for this background color. You can change the cut off by replacing 5 with a number of your choice (lower numbers allow weaker contrasts, e.g. 3 will only make sure contrast is 3:1, 10 will make sure it is at least 10:1) and you can also cut off to avoid too high contrasts (by making sure it is smaller than a certain number), e.g. adding

|| cDiff > 18.0

to the if clause will make sure contrast won't be too extreme, as too extreme contrasts can stress your eyes. Here's the code and have fun playing around with it a bit :-)

import java.io.*;

/* For text being readable, it must have a good contrast difference. Why?
 * Your eye has receptors for brightness and receptors for each of the colors
 * red, green and blue. However, it has much more receptors for brightness
 * than for color. If you only change the color, but both colors have the
 * same contrast, your eye must distinguish fore- and background by the
 * color only and this stresses the brain a lot over the time, because it
 * can only use the very small amount of signals it gets from the color
 * receptors, since the breightness receptors won't note a difference.
 * Actually contrast is so much more important than color that you don't
 * have to change the color at all. E.g. light red on dark red reads nicely
 * even though both are the same color, red.
 */


public class FontColorChooser {
    int bred;
    int bgreen;
    int bblue;

    public FontColorChooser(String hexColor) throws NumberFormatException {
        int i;

        i = Integer.parseInt(hexColor, 16);
        bred = (i >> 16);
        bgreen = (i >> 8) & 0xFF;
        bblue = i & 0xFF;
    }

    public static void main(String[] args) {
        FontColorChooser fcc;

        if (args.length == 0) {
            System.out.println("Missing argument!");
            System.out.println(
                "The first argument must be the background" +
                "color in hex notation."
            );
            System.out.println(
                "E.g. \"FFFFFF\" for white or \"000000\" for black."
            );
            return;
        }
        try {
            fcc = new FontColorChooser(args[0]);
        } catch (Exception e) {
            System.out.println(
                args[0] + " is no valid hex color!"
            );
            return;
        }
        try {
            fcc.start();
        } catch (IOException e) {
            System.out.println("Failed to write output file!");
        }
    }

    public void start() throws IOException {
        int r;
        int b;
        int g;
        OutputStreamWriter out;

        out = new OutputStreamWriter(
            new FileOutputStream("chosen-font-colors.html"),
            "UTF-8"
        );

        // simple, not W3C comform (most browsers won't care), HTML header
        out.write("<html><head><title>\n");
        out.write("</title><style type=\"text/css\">\n");
        out.write("body { background-color:#");
        out.write(rgb2hex(bred, bgreen, bblue));
        out.write("; }\n</style></head>\n<body>\n");

        // try 4096 colors
        for (r = 0; r <= 15; r++) {
            for (g = 0; g <= 15; g++) {
                for (b = 0; b <= 15; b++) {
                    int red;
                    int blue;
                    int green;
                    double cDiff;

                    // brightness increasse like this: 00, 11,22, ..., ff
                    red = (r << 4) | r;
                    blue = (b << 4) | b;
                    green = (g << 4) | g;

                    cDiff = contrastDiff(
                        red, green, blue,
                        bred, bgreen, bblue
                    );
                    if (cDiff < 5.0) continue;
                    writeDiv(red, green, blue, out);
                }
            }
        }

        // finalize HTML document
        out.write("</body></html>");

        out.close();
    }

    private void writeDiv(int r, int g, int b, OutputStreamWriter out)
        throws IOException
    {
        String hex;

        hex = rgb2hex(r, g, b);
        out.write("<div style=\"color:#" + hex + "\">");
        out.write("This is a sample text for color " + hex + "</div>\n");
    }

    private double contrastDiff(
        int r1, int g1, int b1, int r2, int g2, int b2
    ) {
        double l1;
        double l2;

        l1 = ( 
            0.2126 * Math.pow((double)r1/255.0, 2.2) +
            0.7152 * Math.pow((double)g1/255.0, 2.2) +
            0.0722 * Math.pow((double)b1/255.0, 2.2) +
            0.05
        );
        l2 = ( 
            0.2126 * Math.pow((double)r2/255.0, 2.2) +
            0.7152 * Math.pow((double)g2/255.0, 2.2) +
            0.0722 * Math.pow((double)b2/255.0, 2.2) +
            0.05
        );

        return (l1 > l2) ? (l1 / l2) : (l2 / l1);
    }

    private String rgb2hex(int r, int g, int b) {
        String rs = Integer.toHexString(r);
        String gs = Integer.toHexString(g);
        String bs = Integer.toHexString(b);
        if (rs.length() == 1) rs = "0" + rs;
        if (gs.length() == 1) gs = "0" + gs;
        if (bs.length() == 1) bs = "0" + bs;
        return (rs + gs + bs);
    }
}

C++ -- expected primary-expression before ' '

You should not be repeating the string part when sending parameters.

int wordLength = wordLengthFunction(word); //you do not put string word here.

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples).

Without any additional extension, you may use standard PostAsync method:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));

where jsonInString value you can get by calling JsonConvert.SerializeObject(<your object>);

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

How to split a String by space

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }

How do I delete unpushed git commits?

Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.

git reset --hard origin

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    'Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

PHP: Return all dates between two dates in an array

$arr = range(strtotime("2013-12-01"),strtotime("2013-12-31"), "86400");
array_walk_recursive($arr, function(&$element) { $element = date("Y-m-d", $element); });
print_r ($arr);

How to use the read command in Bash?

The read in your script command is fine. However, you execute it in the pipeline, which means it is in a subshell, therefore, the variables it reads to are not visible in the parent shell. You can either

  • move the rest of the script in the subshell, too:

    echo hello | { read str
      echo $str
    }
    
  • or use command substitution to get the value of the variable out of the subshell

    str=$(echo hello)
    echo $str
    

    or a slightly more complicated example (Grabbing the 2nd element of ls)

    str=$(ls | { read a; read a; echo $a; })
    echo $str
    

LIMIT 10..20 in SQL Server

SELECT TOP 10 *
FROM TABLE
WHERE IDCOLUMN NOT IN (SELECT TOP 10 IDCOLUMN FROM TABLE)

Should give records 11-20. Probably not too efficient if incrementing to get further pages, and not sure how it might be affected by ordering. Might have to specify this in both WHERE statements.

Remove/ truncate leading zeros by javascript/jquery

One another way without regex:

function trimLeadingZerosSubstr(str) {
    var xLastChr = str.length - 1, xChrIdx = 0;
    while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
        xChrIdx++;
    }
    return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}

With short string it will be more faster than regex (jsperf)

How to get text box value in JavaScript

because you used space between software engineer html/php will not support space between value under textbox, you have to use this code <input type="text" name="txtJob" value=software_engineer> It will work

how to delete default values in text field using selenium?

driver.findElement(locator).clear() - This command will work in all cases

Python: IndexError: list index out of range

Here is your code. I'm assuming you're using python 3 based on the your use of print() and input():

import random

def main():
    #random.seed() --> don't need random.seed()

    #Prompts the user to enter the number of tickets they wish to play.

    #python 3 version:
    tickets = int(input("How many lottery tickets do you want?\n"))

    #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
    winning_numbers = []
    winnings = 0

    #Generates the winning lotto numbers.
    for i in range(tickets * 5):
        #del winning_numbers[:] what is this line for?
        randNum = random.randint(1,30)
        while randNum in winning_numbers:    
            randNum = random.randint(1,30)
        winning_numbers.append(randNum)

    print(winning_numbers)
    guess = getguess(tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    winningRanks = [0, 0, 10, 500, 20000, 1000000]

    winnings = sum(winningRanks[:nummatches + 1])

    print("You won a total of",winnings,"with",tickets,"tickets.\n")


#Gets the guess from the user.
def getguess(tickets):
    guess = []
    for i in range(tickets):
        bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
        guess.extend(bubble)
        print(bubble)
    return guess

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
    match = 0
    for i in range(5):
        if guess[i] == winning_numbers[i]:
            match += 1
    return match

main()

Method to Add new or update existing item in Dictionary

There's no problem. I would even remove the CreateNewOrUpdateExisting from the source and use map[key] = value directly in your code, because this this is much more readable, because developers would usually know what map[key] = value means.

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

How to set text size of textview dynamically for different screens

float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

How to manage local vs production settings in Django?

For most of my projects I use following pattern:

  1. Create settings_base.py where I store settings that are common for all environments
  2. Whenever I need to use new environment with specific requirements I create new settings file (eg. settings_local.py) which inherits contents of settings_base.py and overrides/adds proper settings variables (from settings_base import *)

(To run manage.py with custom settings file you simply use --settings command option: manage.py <command> --settings=settings_you_wish_to_use.py)

Maximum number of records in a MySQL database table

Link http://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html

Row Size Limits

The maximum row size for a given table is determined by several factors:

The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.

The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page for 4KB, 8KB, 16KB, and 32KB innodb_page_size settings. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size. For 64KB pages, the maximum row size is slightly less than 16KB. See Section 15.8.8, “Limits on InnoDB Tables”.

If a row containing variable-length columns exceeds the InnoDB maximum row size, InnoDB selects variable-length columns for external off-page storage until the row fits within the InnoDB row size limit. The amount of data stored locally for variable-length columns that are stored off-page differs by row format. For more information, see Section 15.11, “InnoDB Row Storage and Row Formats”.

Different storage formats use different amounts of page header and trailer data, which affects the amount of storage available for rows.

For information about InnoDB row formats, see Section 15.11, “InnoDB Row Storage and Row Formats”, and Section 15.8.3, “Physical Row Structure of InnoDB Tables”.

For information about MyISAM storage formats, see Section 16.2.3, “MyISAM Table Storage Formats”.

http://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html

How do I POST a x-www-form-urlencoded request using Fetch?

You have to put together the x-www-form-urlencoded payload yourself, like this:

var details = {
    'userName': '[email protected]',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('https://example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  body: formBody
})

Note that if you were using fetch in a (sufficiently modern) browser, instead of React Native, you could instead create a URLSearchParams object and use that as the body, since the Fetch Standard states that if the body is a URLSearchParams object then it should be serialised as application/x-www-form-urlencoded. However, you can't do this in React Native because React Native does not implement URLSearchParams.

jQuery: select all elements of a given class, except for a particular Id

Or take the .not() method

https://api.jquery.com/not/

$(".thisClass").not("#thisId").doAction();

ASP.NET IIS Web.config [Internal Server Error]

I got similar error when i run legacy application in Visual studio 2013 iis express and solved the issue by following steps 1.Navigate to "Documents\IISExpress\config" 2.Open "applicationhost.config" using notepad or any preferred editor 3.scroll down and find for section name="anonymousAuthentication" under 4. Update overrideModeDefault="Deny" to "Allow" 5. save the config file 6. Run the legacy application and worked fine for me.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Simulate delayed and dropped packets on Linux

This tutorial on networking physics simulations contains a C++ class in the sample code for simulating latency and packet loss in a UDP connection and may be of guidance. See the public latency and packetLoss variables of the Connection class found in the Connection.h file of the downloadable source code.

How to update an object in a List<> in C#

Just to add to CKoenig's response. His answer will work as long as the class you're dealing with is a reference type (like a class). If the custom object were a struct, this is a value type, and the results of .FirstOrDefault will give you a local copy of that, which will mean it won't persist back to the collection, as this example shows:

struct MyStruct
{
    public int TheValue { get; set; }
}

Test code:

List<MyStruct> coll = new List<MyStruct> {
                                            new MyStruct {TheValue = 10},
                                            new MyStruct {TheValue = 1},
                                            new MyStruct {TheValue = 145},
                                            };
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;

foreach (var myStruct in coll)
{
    Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();

The output is 10,1,145

Change the struct to a class and the output is 10,12,145

HTH

How to group time by hour or by 10 minutes

For SQL Server 2012, though I believe it would work in SQL Server 2008R2, I use the following approach to get time slicing down to the millisecond:

DATEADD(MILLISECOND, -DATEDIFF(MILLISECOND, CAST(time AS DATE), time) % @msPerSlice, time)

This works by:

  • Getting the number of milliseconds between a fixed point and target time:
    @ms = DATEDIFF(MILLISECOND, CAST(time AS DATE), time)
  • Taking the remainder of dividing those milliseconds into time slices:
    @rms = @ms % @msPerSlice
  • Adding the negative of that remainder to the target time to get the slice time:
    DATEADD(MILLISECOND, -@rms, time)

Unfortunately, as is this overflows with microseconds and smaller units, so larger, finer data sets would need to use a less convenient fixed point.

I have not rigorously benchmarked this and I am not in big data, so your mileage may vary, but performance was not noticeably worse than the other methods tried on our equipment and data sets, and the payout in developer convenience for arbitrary slicing makes it worthwhile for us.

Is it possible to get the current spark context settings in PySpark?

I would suggest you try the method below in order to get the current spark context settings.

SparkConf.getAll()

as accessed by

SparkContext.sc._conf

Get the default configurations specifically for Spark 2.1+

spark.sparkContext.getConf().getAll() 

Stop the current Spark Session

spark.sparkContext.stop()

Create a Spark Session

spark = SparkSession.builder.config(conf=conf).getOrCreate()

Remove all whitespace from C# string with regex

Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"

  if (!string.IsNullOrEmpty(url))
          {
           string origFileName = Path.GetFileName(url);
           string modiFileName = origFileName.Trim().Replace(" ", "~");
           url = url.Replace(origFileName , modiFileName );
          }
          return url;

Is there a difference between PhoneGap and Cordova commands?

I have also noticed that cordova has a "serve" command that Phonegap doesn't. This command launches a local server on port 8000. This is handy for running your app in Chrome and using the Ripple emulator.

why should I make a copy of a data frame in pandas

It's necessary to mention that returning copy or view depends on kind of indexing.

The pandas documentation says:

Returning a view versus a copy

The rules about when a view on the data is returned are entirely dependent on NumPy. Whenever an array of labels or a boolean vector are involved in the indexing operation, the result will be a copy. With single label / scalar indexing and slicing, e.g. df.ix[3:6] or df.ix[:, 'A'], a view will be returned.

How do you create a dropdownlist from an enum in ASP.NET MVC?

So without Extension functions if you are looking for simple and easy.. This is what I did

<%= Html.DropDownListFor(x => x.CurrentAddress.State, new SelectList(Enum.GetValues(typeof(XXXXX.Sites.YYYY.Models.State))))%>

where XXXXX.Sites.YYYY.Models.State is an enum

Probably better to do helper function, but when time is short this will get the job done.

Changing the sign of a number in PHP?

I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:

$int = (($int > 0) ? -$int : $int);

EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:

/* I am not proposing you actually use functions called
   "makeNegative" and "makePositive"; I am just presenting
   the most direct solution in the form of two clearly named
   functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }

Angular, content type is not being sent with $http

You need to include a body with the request. Angular removes the content-type header otherwise.

Add data: '' to the argument to $http.

C# how to create a Guid value?

There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.

PM> Install-Package CSharpVitamins.ShortGuid

Usage:

Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine(sguid1);
Console.WriteLine(sguid1.Guid);

This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:

ShortGuid: FEx1sZbSD0ugmgMAF_RGHw 
Guid:      b1754c14-d296-4b0f-a09a-030017f4461f

Jquery in React is not defined

I just want to receive ajax request, but the problem is that jQuery is not defined in React.

Then don't use it. Use Fetch and have a look at Fetch polyfill in React not completely working in IE 11 to see example of alternative ways to get it running

Something like this

const that = this; 
fetch('http://jsonplaceholder.typicode.com/posts') 
  .then(function(response) { return response.json(); }) 
  .then(function(myJson) { 
     that.setState({data: myJson}); // for example
  });

JavaScript closure inside loops – simple practical example

Here's a simple solution that uses forEach (works back to IE9):

_x000D_
_x000D_
var funcs = [];_x000D_
[0,1,2].forEach(function(i) {          // let's create 3 functions_x000D_
    funcs[i] = function() {            // and store them in funcs_x000D_
        console.log("My value: " + i); // each should log its value._x000D_
    };_x000D_
})_x000D_
for (var j = 0; j < 3; j++) {_x000D_
    funcs[j]();                        // and now let's run each one to see_x000D_
}
_x000D_
_x000D_
_x000D_

Prints:

My value: 0
My value: 1
My value: 2

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

View list of all JavaScript variables in Google Chrome Console

If you want to exclude all the standard properties of the window object and view application-specific globals, this will print them to the Chrome console:

{

    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);

    for (const key of Object.keys(window)) {
        if (!standardGlobals.has(key)) {
            console.log(key)
        }
    }
}

The script works well as a bookmarklet. To use the script as a bookmarklet, create a new bookmark and replace the URL with the following:

javascript:(() => {
    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);
    for (const key of Object.keys(window)) {
        if (!standardGlobals.has(key)) {
            console.log(key)
        }
    }
})()

How do I set up a private Git repository on GitHub? Is it even possible?

On January 7th 2019, GitHub announced free and unlimited private repositories for all GitHub users, paying or not. When creating a new repository, you can simply select the Private option.

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Django gives Bad Request (400) when DEBUG = False

The ALLOWED_HOSTS list should contain fully qualified host names, not urls. Leave out the port and the protocol. If you are using 127.0.0.1, I would add localhost to the list too:

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

You could also use * to match any host:

ALLOWED_HOSTS = ['*']

Quoting the documentation:

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE_CLASSES).

Bold emphasis mine.

The status 400 response you get is due to a SuspiciousOperation exception being raised when your host header doesn't match any values in that list.

How can I output leading zeros in Ruby?

As stated by the other answers, "%03d" % number works pretty well, but it goes against the rubocop ruby style guide:

Favor the use of sprintf and its alias format over the fairly cryptic String#% method

We can obtain the same result in a more readable way using the following:

format('%03d', number)

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

I resolved it by replacing Tomcat 8.5.* with Tomcat 7.0.* version.

how to implement a pop up dialog box in iOS

Here is C# version in Xamarin.iOS

var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

ORA-00904: invalid identifier

In my case, this error occurred, due to lack of existence of column name in the table.

When i executed "describe tablename" , i was not able to find the column specified in the mapping hbm file.

After altering the table, it worked fine.

how do you pass images (bitmaps) between android activities using bundles?

Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transferring large bitmap (Compress bitmap)

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

How to round a Double to the nearest Int in swift?

Swift 3 & 4 - making use of the rounded(_:) method as blueprinted in the FloatingPoint protocol

The FloatingPoint protocol (to which e.g. Double and Float conforms) blueprints the rounded(_:) method

func rounded(_ rule: FloatingPointRoundingRule) -> Self

Where FloatingPointRoundingRule is an enum enumerating a number of different rounding rules:

case awayFromZero

Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

case down

Round to the closest allowed value that is less than or equal to the source.

case toNearestOrAwayFromZero

Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

case toNearestOrEven

Round to the closest allowed value; if two values are equally close, the even one is chosen.

case towardZero

Round to the closest allowed value whose magnitude is less than or equal to that of the source.

case up

Round to the closest allowed value that is greater than or equal to the source.

We make use of similar examples to the ones from @Suragch's excellent answer to show these different rounding options in practice.

.awayFromZero

Round to the closest allowed value whose magnitude is greater than or equal to that of the source; no direct equivalent among the C functions, as this uses, conditionally on sign of self, ceil or floor, for positive and negative values of self, respectively.

3.000.rounded(.awayFromZero) // 3.0
3.001.rounded(.awayFromZero) // 4.0
3.999.rounded(.awayFromZero) // 4.0

(-3.000).rounded(.awayFromZero) // -3.0
(-3.001).rounded(.awayFromZero) // -4.0
(-3.999).rounded(.awayFromZero) // -4.0

.down

Equivalent to the C floor function.

3.000.rounded(.down) // 3.0
3.001.rounded(.down) // 3.0
3.999.rounded(.down) // 3.0

(-3.000).rounded(.down) // -3.0
(-3.001).rounded(.down) // -4.0
(-3.999).rounded(.down) // -4.0

.toNearestOrAwayFromZero

Equivalent to the C round function.

3.000.rounded(.toNearestOrAwayFromZero) // 3.0
3.001.rounded(.toNearestOrAwayFromZero) // 3.0
3.499.rounded(.toNearestOrAwayFromZero) // 3.0
3.500.rounded(.toNearestOrAwayFromZero) // 4.0
3.999.rounded(.toNearestOrAwayFromZero) // 4.0

(-3.000).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.001).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.499).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.500).rounded(.toNearestOrAwayFromZero) // -4.0
(-3.999).rounded(.toNearestOrAwayFromZero) // -4.0

This rounding rule can also be accessed using the zero argument rounded() method.

3.000.rounded() // 3.0
// ...

(-3.000).rounded() // -3.0
// ...

.toNearestOrEven

Round to the closest allowed value; if two values are equally close, the even one is chosen; equivalent to the C rint (/very similar to nearbyint) function.

3.499.rounded(.toNearestOrEven) // 3.0
3.500.rounded(.toNearestOrEven) // 4.0 (up to even)
3.501.rounded(.toNearestOrEven) // 4.0

4.499.rounded(.toNearestOrEven) // 4.0
4.500.rounded(.toNearestOrEven) // 4.0 (down to even)
4.501.rounded(.toNearestOrEven) // 5.0 (up to nearest)

.towardZero

Equivalent to the C trunc function.

3.000.rounded(.towardZero) // 3.0
3.001.rounded(.towardZero) // 3.0
3.999.rounded(.towardZero) // 3.0

(-3.000).rounded(.towardZero) // 3.0
(-3.001).rounded(.towardZero) // 3.0
(-3.999).rounded(.towardZero) // 3.0

If the purpose of the rounding is to prepare to work with an integer (e.g. using Int by FloatPoint initialization after rounding), we might simply make use of the fact that when initializing an Int using a Double (or Float etc), the decimal part will be truncated away.

Int(3.000) // 3
Int(3.001) // 3
Int(3.999) // 3

Int(-3.000) // -3
Int(-3.001) // -3
Int(-3.999) // -3

.up

Equivalent to the C ceil function.

3.000.rounded(.up) // 3.0
3.001.rounded(.up) // 4.0
3.999.rounded(.up) // 4.0

(-3.000).rounded(.up) // 3.0
(-3.001).rounded(.up) // 3.0
(-3.999).rounded(.up) // 3.0

Addendum: visiting the source code for FloatingPoint to verify the C functions equivalence to the different FloatingPointRoundingRule rules

If we'd like, we can take a look at the source code for FloatingPoint protocol to directly see the C function equivalents to the public FloatingPointRoundingRule rules.

From swift/stdlib/public/core/FloatingPoint.swift.gyb we see that the default implementation of the rounded(_:) method makes us of the mutating round(_:) method:

public func rounded(_ rule: FloatingPointRoundingRule) -> Self {
    var lhs = self
    lhs.round(rule)
    return lhs
}

From swift/stdlib/public/core/FloatingPointTypes.swift.gyb we find the default implementation of round(_:), in which the equivalence between the FloatingPointRoundingRule rules and the C rounding functions is apparent:

public mutating func round(_ rule: FloatingPointRoundingRule) {
    switch rule {
    case .toNearestOrAwayFromZero:
        _value = Builtin.int_round_FPIEEE${bits}(_value)
    case .toNearestOrEven:
        _value = Builtin.int_rint_FPIEEE${bits}(_value)
    case .towardZero:
        _value = Builtin.int_trunc_FPIEEE${bits}(_value)
    case .awayFromZero:
        if sign == .minus {
            _value = Builtin.int_floor_FPIEEE${bits}(_value)
        }
        else {
            _value = Builtin.int_ceil_FPIEEE${bits}(_value)
        }
    case .up:
        _value = Builtin.int_ceil_FPIEEE${bits}(_value)
    case .down:
        _value = Builtin.int_floor_FPIEEE${bits}(_value)
    }
}

Vertically centering Bootstrap modal window

e(document).on('show.bs.modal', function () {
        if($winWidth < $(window).width()){
            $('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
        }
    });
    e(document).on('hidden.bs.modal', function () {
        $('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
    });

How can I reset or revert a file to a specific revision?

git revert <hash>

Will revert a given commit. It sounds like you think git revert only affects the most recent commit.

That doesn't solve your problem, if you want to revert a change in a specific file and that commit changed more than that file.

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

How to create a cron job using Bash automatically without the interactive editor?

(2>/dev/null crontab -l ; echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -
cat <(crontab -l 2>/dev/null) <(echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -

#write out current crontab

crontab -l > mycron 2>/dev/null

#echo new cron into cron file

echo "0 3 * * * /usr/local/bin/certbot-auto renew" >> mycron

#install new cron file

crontab mycron

rm mycron

How to pass optional arguments to a method in C++?

With the introduction of std::optional in C++17 you can pass optional arguments:

#include <iostream>
#include <string>
#include <optional>

void myfunc(const std::string& id, const std::optional<std::string>& param = std::nullopt)
{
    std::cout << "id=" << id << ", param=";

    if (param)
        std::cout << *param << std::endl;
    else
        std::cout << "<parameter not set>" << std::endl;
}

int main() 
{
    myfunc("first");
    myfunc("second" , "something");
}

Output:

id=first param=<parameter not set>
id=second param=something

See https://en.cppreference.com/w/cpp/utility/optional

C++, What does the colon after a constructor mean?

It means that len is not set using the default constructor. while the demo class is being constructed. For instance:

class Demo{
    int foo;
public:
    Demo(){ foo = 1;}
};

Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.

What is the difference between lower bound and tight bound?

The basic difference between

Blockquote

asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.

Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.

Cannot declare instance members in a static class in C#

It says what it means:

make your class non-static:

public class employee
{
  NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

or the member static:

public static class employee
{
  static NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

Build Error - missing required architecture i386 in file

I just wanted to mention that in XCode if you go to "Edit Project Settings" and find "Search Paths" There is a field for "Framework Search Paths". Updating this should fix the problem, without having to hack the project file!

Cheers!

Jesse

MySQL: can't access root account

I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.

We can check this with ls -l /var/lib/mysql command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod commands.

After these changes, restart the mysqld daemon and login with root with command:

mysql -u root

Then change passwords or create other users for logging into mysql.

HTH

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

How can I call controller/view helper methods from the console in Ruby on Rails?

In Ruby on Rails 3, try this:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body

The body will contain the HTML of the URL.

How to route and render (dispatch) from a model in Ruby on Rails 3

Could not create the Java virtual machine

Make sure the physical available memory is more then VM defined min/max memory.

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

Add new column with foreign key constraint in one command

For DB2, the syntax is:

ALTER TABLE one ADD two_id INTEGER FOREIGN KEY (two_id) REFERENCES two (id);

Calling class staticmethod within the class body?

staticmethod objects apparently have a __func__ attribute storing the original raw function (makes sense that they had to). So this will work:

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):

>>> class Foo(object):
...     @staticmethod
...     def foo():
...         return 3
...     global z
...     z = foo

>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>

Similar sorts of digging in an interactive session (dir is very helpful) can often solve these sorts of question very quickly.

Stored procedure or function expects parameter which is not supplied

In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :

cmd.CommandType = System.Data.CommandType.StoredProcedure;

This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.

Get the Highlighted/Selected text

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

Preferred way of getting the selected item of a JComboBox

Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"

how to open *.sdf files?

You can use SQL Compact Query Analyzer

http://sqlcequery.codeplex.com/

SQL Compact Query Analyzer is really snappy. 3 MB download, requires an install but really snappy and works.

Generate Row Serial Numbers in SQL Query

Implementing Serial Numbers Without Ordering Any of the Columns

enter image description here

Demo SQL Script-

IF OBJECT_ID('Tempdb..#TestTable') IS NOT NULL
    DROP TABLE #TestTable;

CREATE TABLE #TestTable (Names VARCHAR(75), Random_No INT); 

INSERT INTO #TestTable (Names,Random_No) VALUES
 ('Animal', 363)
,('Bat', 847)
,('Cat', 655)
,('Duet', 356)
,('Eagle', 136)
,('Frog', 784)
,('Ginger', 690); 

SELECT * FROM #TestTable;

There are ‘N’ methods for implementing Serial Numbers in SQL Server. Hereby, We have mentioned the Simple Row_Number Function to generate Serial Numbers.

ROW_NUMBER() Function is one of the Window Functions that numbers all rows sequentially (for example 1, 2, 3, …) It is a temporary value that will be calculated when the query is run. It must have an OVER Clause with ORDER BY. So, we cannot able to omit Order By Clause Simply. But we can use like below-

SQL Script

IF OBJECT_ID('Tempdb..#TestTable') IS NOT NULL
    DROP TABLE #TestTable;

CREATE TABLE #TestTable (Names VARCHAR(75), Random_No INT); 

INSERT INTO #TestTable (Names,Random_No) VALUES
 ('Animal', 363)
,('Bat', 847)
,('Cat', 655)
,('Duet', 356)
,('Eagle', 136)
,('Frog', 784)
,('Ginger', 690); 

SELECT Names,Random_No,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS SERIAL_NO FROM #TestTable;

In the Above Query, We can Also Use SELECT 1, SELECT ‘ABC’, SELECT ” Instead of SELECT NULL. The result would be Same.

Detect WebBrowser complete page loading

I think the DocumentCompleted event will get fired for all child documents that are loaded as well (like JS and CSS, for example). You could look at the WebBrowserDocumentCompletedEventArgs in DocumentCompleted and check the Url property and compare that to the Url of the main page.

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

How do I connect to a MySQL Database in Python?

you can connect your python code to mysql in this way.

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

Adding Python Path on Windows 7

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

What static analysis tools are available for C#?

  • Gendarme is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
  • Clone Detective is a nice plug-in for Visual Studio that finds duplicate code.
  • Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).

Export pictures from excel file into jpg using VBA

New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

Option Explicit

Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub weGucciFam()

Dim tmp As Variant, str As String, h As Double, w As Double

Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"

keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28

str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height

Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
    .PageSetup.PaperSize = xlPaper11x17
    .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
    .PageSetup.BottomMargin = 0
    .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
    .PageSetup.LeftMargin = 0
    .PageSetup.HeaderMargin = 0
    .PageSetup.FooterMargin = 0
    .SeriesCollection(1).Delete
    DoEvents
    .Paste
    DoEvents
    .Export Filename:=str, Filtername:="jpeg"
    .Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
    wsTMP.Shapes(1).Delete
Loop

Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False

End Sub