Programs & Examples On #Rowdeleting

How to delete a specific file from folder using asp.net

Delete any or specific file type(for example ".bak") from a path. See demo code below -

class Program
        {
        static void Main(string[] args)
            {

            // Specify the starting folder on the command line, or in 
            TraverseTree(ConfigurationManager.AppSettings["folderPath"]);

            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            //TraverseTree(args[0]);

            Console.WriteLine("Press any key");
            Console.ReadKey();
            }

        public static void TraverseTree(string root)
            {

            if (string.IsNullOrWhiteSpace(root))
                return;

            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!System.IO.Directory.Exists(root))
                {
                return;
                }

            dirs.Push(root);

            while (dirs.Count > 0)
                {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                    {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                IEnumerable<FileInfo> files = null;
                try
                    {
                    //get only .bak file
                    var directory = new DirectoryInfo(currentDir);
                    DateTime date = DateTime.Now.AddDays(-15);
                    files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
                    }
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (FileInfo file in files)
                    {
                    try
                        {
                        // Perform whatever action is required in your scenario.
                        file.Delete();
                        Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
                        }
                    catch (System.IO.FileNotFoundException e)
                        {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                        }
                    }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
                }
            }
        }

for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx

How to delete row in gridview using rowdeleting event?

     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = GridView1.SelectedIndex;
        int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
        SqlConnection con = new SqlConnection(str);
        SqlCommand com = new SqlCommand("spDelete", con);
        com.Parameters.AddWithValue("@PatientId", id);
        con.Open();
        com.ExecuteNonQuery();

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

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

Unsetting array values in a foreach loop

foreach($images as $key => $image)
{
    if(in_array($image, array(
       'http://i27.tinypic.com/29ykt1f.gif',
       'http://img3.abload.de/img/10nxjl0fhco.gif',
       'http://i42.tinypic.com/9pp2tx.gif',
    ))
    {
        unset($images[$key]);
    }
}

How to make a <div> always full screen?

Here's the shortest solution, based on vh. Please note that vh is not supported in some older browsers.

CSS:

div {
    width: 100%;
    height: 100vh;
}

HTML:

<div>This div is fullscreen :)</div>

How to detect if javascript files are loaded?

Change the loading order of your scripts so that function1 was defined before using it in ready callback.

Plus I always found it better to define ready callback as an anonymous method then named one.

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

Nginx 403 error: directory index of [folder] is forbidden

when you want to keep the directory option,you can put the index.php ahead of $uri like this.

try_files /index.php $uri $uri/

Stop node.js program from command line

Late answer but on windows, opening up the task manager with CTRL+ALT+DEL then killing Node.js processes will solve this error.

Sieve of Eratosthenes - Finding Primes Python

Using recursion and walrus operator:

def prime_factors(n):
    for i in range(2, int(n ** 0.5) + 1):
        if (q_r := divmod(n, i))[1] == 0:
            return [i] + factor_list(q_r[0])
    return [n]

JQuery / JavaScript - trigger button click from another button click event

this works fine, but file name does not display anymore.

$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });

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'

WPF: Setting the Width (and Height) as a Percentage Value

Typically, you'd use a built-in layout control appropriate for your scenario (e.g. use a grid as a parent if you want scaling relative to the parent). If you want to do it with an arbitrary parent element, you can create a ValueConverter do it, but it probably won't be quite as clean as you'd like. However, if you absolutely need it, you could do something like this:

public class PercentageConverter : IValueConverter
{
    public object Convert(object value, 
        Type targetType, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        return System.Convert.ToDouble(value) * 
               System.Convert.ToDouble(parameter);
    }

    public object ConvertBack(object value, 
        Type targetType, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Which can be used like this, to get a child textbox 10% of the width of its parent canvas:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:PercentageConverter x:Key="PercentageConverter"/>
    </Window.Resources>
    <Canvas x:Name="canvas">
        <TextBlock Text="Hello"
                   Background="Red" 
                   Width="{Binding 
                       Converter={StaticResource PercentageConverter}, 
                       ElementName=canvas, 
                       Path=ActualWidth, 
                       ConverterParameter=0.1}"/>
    </Canvas>
</Window>

How to escape a while loop in C#

"break" is a command that breaks out of the "closest" loop.

While there are many good uses for break, you shouldn't use it if you don't have to -- it can be seen as just another way to use goto, which is considered bad.

For example, why not:

while (!(the condition you're using to break))
        {
         //Your code here.
        }

If the reason you're using "break" is because you don't want to continue execution of that iteration of the loop, you may want to use the "continue" keyword, which immediately jumps to the next iteration of the loop, whether it be while or for.

while (!condition) {
   //Some code
   if (condition) continue;
   //More code that will be skipped over if the condition was true
}

How can I pretty-print JSON using Go?

By pretty-print, I assume you mean indented, like so

{
    "data": 1234
}

rather than

{"data":1234}

The easiest way to do this is with MarshalIndent, which will let you specify how you would like it indented via the indent argument. Thus, json.MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.

An error occurred while signing: SignTool.exe not found

Click "Project" at the top. Then click " Properties" -> Signing -> Unchecked [Sign the ClickOnce manifests] is now working

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We had this error on Oracle RAC 11g on Windows, and the solution was to create the same OS directory tree and external file on both nodes.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

How to split data into training/testing sets using sample function

After looking through all the different methods posted here, I didn't see anyone utilize TRUE/FALSE to select and unselect data. So I thought I would share a method utilizing that technique.

n = nrow(dataset)
split = sample(c(TRUE, FALSE), n, replace=TRUE, prob=c(0.75, 0.25))

training = dataset[split, ]
testing = dataset[!split, ]

Explanation

There are multiple ways of selecting data from R, most commonly people use positive/negative indices to select/unselect respectively. However, the same functionalities can be achieved by using TRUE/FALSE to select/unselect.

Consider the following example.

# let's explore ways to select every other element
data = c(1, 2, 3, 4, 5)


# using positive indices to select wanted elements
data[c(1, 3, 5)]
[1] 1 3 5

# using negative indices to remove unwanted elements
data[c(-2, -4)]
[1] 1 3 5

# using booleans to select wanted elements
data[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
[1] 1 3 5

# R recycles the TRUE/FALSE vector if it is not the correct dimension
data[c(TRUE, FALSE)]
[1] 1 3 5

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

The best way is as described in the following blog http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/

Design your static table view as normal in interface builder – complete with all potentially hidden cells. But there is one thing you must do for every potential cell that you want to hide – check the “Clip subviews” property of the cell, otherwise the content of the cell doesn’t disappear when you try and hide it (by shrinking it’s height – more later).

SO – you have a switch in a cell and the switch is supposed to hide and show some static cells. Hook it up to an IBAction and in there do this:

[self.tableView beginUpdates];
[self.tableView endUpdates];

That gives you nice animations for the cells appearing and disappearing. Now implement the following table view delegate method:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
    // Show or hide cell
        if (self.mySwitch.on) {
            return 44; // Show the cell - adjust the height as you need
        } else {
            return 0; // Hide the cell
        }
   }
   return 44;
}

And that’s it. Flip the switch and the cell hides and reappears with a nice, smooth animation.

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

What are .tpl files? PHP, web design

Templates. I think that is Smarty syntax.

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

Making RGB color in Xcode

The values are determined by the bit of the image. 8 bit 0 to 255

16 bit...some ridiculous number..0 to 65,000 approx.

32 bit are 0 to 1

I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Answer: 09 December 2015

Personally, I found the accepted answer both concise (good) and terse (bad). Appreciate this statement might be subjective, so please read this answer and see if you agree or disagree

The example given in the question was something like Ruby's:

x.times do |i|
  do_stuff(i)
end

Expressing this in JS using below would permit:

times(x)(doStuff(i));

Here is the code:

let times = (n) => {
  return (f) => {
    Array(n).fill().map((_, i) => f(i));
  };
};

That's it!

Simple example usage:

let cheer = () => console.log('Hip hip hooray!');

times(3)(cheer);

//Hip hip hooray!
//Hip hip hooray!
//Hip hip hooray!

Alternatively, following the examples of the accepted answer:

let doStuff = (i) => console.log(i, ' hi'),
  once = times(1),
  twice = times(2),
  thrice = times(3);

once(doStuff);
//0 ' hi'

twice(doStuff);
//0 ' hi'
//1 ' hi'

thrice(doStuff);
//0 ' hi'
//1 ' hi'
//2 ' hi'

Side note - Defining a range function

A similar / related question, that uses fundamentally very similar code constructs, might be is there a convenient Range function in (core) JavaScript, something similar to underscore's range function.

Create an array with n numbers, starting from x

Underscore

_.range(x, x + n)

ES2015

Couple of alternatives:

Array(n).fill().map((_, i) => x + i)

Array.from(Array(n), (_, i) => x + i)

Demo using n = 10, x = 1:

> Array(10).fill().map((_, i) => i + 1)
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

> Array.from(Array(10), (_, i) => i + 1)
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

In a quick test I ran, with each of the above running a million times each using our solution and doStuff function, the former approach (Array(n).fill()) proved slightly faster.

Git push existing repo to a new and different remote repo server?

Do you really want to simply push your local repository (with its local branches, etc.) to the new remote or do you really want to mirror the old remote (with all its branches, tags, etc) on the new remote? If the latter here's a great blog on How to properly mirror a git repository.

I strongly encourage you to read the blog for some very important details, but the short version is this:

In a new directory run these commands:

git clone --mirror [email protected]/upstream-repository.git
cd upstream-repository.git
git push --mirror [email protected]/new-location.git

How do I change select2 box height

I know this question is super old, but I was looking for a solution to this same question in 2017 and found one myself.

.select2-selection {
    height: auto !important;
}

This will dynamically adjust the height of your input based on its content.

Insert current date/time using now() in a field using MySQL/PHP

NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:

date('Y-m-d H:i:s')

But I wouldn't recommend this.

Use of def, val, and var in scala

There are three ways of defining things in Scala:

  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

println(person.age)

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)

Check if string is neither empty nor space in shell script

You need a space on either side of the !=. Change your code to:

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str" != " " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2" != " " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3" != " " ]; then
        echo "Str3 is not null or space"
fi

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

error: expected class-name before ‘{’ token

Replace

#include "Landing.h"

with

class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

Change Oracle port from port 8080

Just open Run SQL Command Line and login as sysadmin and then enter below command

Exec DBMS_XDB.SETHTTPPORT(8181);

That's it. You are done.....

What is the Simplest Way to Reverse an ArrayList?

ArrayList<Integer> myArray = new ArrayList<Integer>();

myArray.add(1);
myArray.add(2);
myArray.add(3);

int reverseArrayCounter = myArray.size() - 1;

for (int i = reverseArrayCounter; i >= 0; i--) {
    System.out.println(myArray.get(i));
}

Reading binary file and looping over each byte

Python 2.4 and Earlier

f = open("myfile", "rb")
try:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)
finally:
    f.close()

Python 2.5-2.7

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)

Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it:

from __future__ import with_statement

In 2.6 this is not needed.

Python 3

In Python 3, it's a bit different. We will no longer get raw characters from the stream in byte mode but byte objects, thus we need to alter the condition:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)

Or as benhoyt says, skip the not equal and take advantage of the fact that b"" evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)

python 3.8

From now on thanks to := operator the above code can be written in a shorter way.

with open("myfile", "rb") as f:
    while (byte := f.read(1)):
        # Do stuff with byte.

How to define multiple CSS attributes in jQuery?

$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });

Jquery Date picker Default Date

While the defaultDate does not set the widget. What is needed is something like:

$(".datepicker").datepicker({
    showButtonPanel: true,
    numberOfMonths: 2

});

$(".datepicker[value='']").datepicker("setDate", "-0d"); 

jquery get all form elements: input, textarea & select

This is my favorite function and it works like a charm for me!

It returns an object with all for input, select and textarea data.

And it's trying to getting objects name by look for elements name else Id else class.

var All_Data = Get_All_Forms_Data();
console.log(All_Data);

Function:

function Get_All_Forms_Data(Element)
{
    Element = Element || '';
    var All_Page_Data = {};
    var All_Forms_Data_Temp = {};
    if(!Element)
    {
        Element = 'body';
    }

    $(Element).find('input,select,textarea').each(function(i){
        All_Forms_Data_Temp[i] = $(this);
    });

    $.each(All_Forms_Data_Temp,function(){
        var input = $(this);
        var Element_Name;
        var Element_Value;

        if((input.attr('type') == 'submit') || (input.attr('type') == 'button'))
        {
            return true;
        }

        if((input.attr('name') !== undefined) && (input.attr('name') != ''))
        {
            Element_Name = input.attr('name').trim();
        }
        else if((input.attr('id') !== undefined) && (input.attr('id') != ''))
        {
            Element_Name = input.attr('id').trim();
        }
        else if((input.attr('class') !== undefined) && (input.attr('class') != ''))
        {
            Element_Name = input.attr('class').trim();
        }

        if(input.val() !== undefined)
        {
            if(input.attr('type') == 'checkbox')
            {
                Element_Value = input.parent().find('input[name="'+Element_Name+'"]:checked').val();
            }
            else if((input.attr('type') == 'radio'))
            {
                Element_Value = $('input[name="'+Element_Name+'"]:checked',Element).val();
            }
            else
            {
                Element_Value = input.val();
            }
        }
        else if(input.text() != undefined)
        {
            Element_Value = input.text();
        }

        if(Element_Value === undefined)
        {
            Element_Value = '';
        }

        if(Element_Name !== undefined)
        {
            var Element_Array = new Array();
            if(Element_Name.indexOf(' ') !== -1)
            {
                Element_Array = Element_Name.split(/(\s+)/);
            }
            else
            {
                Element_Array.push(Element_Name);
            }

            $.each(Element_Array,function(index, Name)
            {
                Name = Name.trim();
                if(Name != '')
                {
                    All_Page_Data[Name] = Element_Value;
                }
            });
        }
    });
    return All_Page_Data;
}

Django: Display Choice Value

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

In Views

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

In Template

{{ person.get_gender_display }}

Documentation of get_FOO_display()

Creating C formatted strings (not printing them)

Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I have encounterd the same issue, but I find a anwser showing below.

web.xml

 <!-- set this param value for the filter-->
    <init-param>
            <param-name>freePages</param-name>
            <param-value>
            MainFrame.jsp;
            </param-value>
    </init-param>

filter.java

strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage)  //decide the exclude path

this way you don't have to harass the concrete Filter class.

How to use onClick with divs in React.js

I just needed a simple testing button for react.js. Here is what I did and it worked.

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}

How to parse Excel (XLS) file in Javascript/HTML5

include the xslx.js , xlsx.full.min.js , jszip.js

add a onchange event handler to the file input

function showDataExcel(event)
{
            var file = event.target.files[0];
            var reader = new FileReader();
            var excelData = [];
            reader.onload = function (event) {
                var data = event.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

                    for (var i = 0; i < XL_row_object.length; i++)
                    {
                        excelData.push(XL_row_object[i]["your column name"]);

                    }

                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    alert(excelData);
                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);

}

Count the number of items in my array list

Outside of your loop create an int:

int numberOfItemIds = 0;
for (int i = 0; i < key.length; i++) {

Then in the loop, increment it:

itemId = p.getItemId();
numberOfItemIds++;

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

Update: MVC 3 and newer versions have built-in support for this. See JohnnyO's highly upvoted answer below for recommended solutions.

I do not think there are any immediate helpers for achieving this, but I do have two ideas for you to try:

// 1: pass dictionary instead of anonymous object
<%= Html.ActionLink( "back", "Search",
    new { keyword = Model.Keyword, page = Model.currPage - 1},
    new Dictionary<string,Object> { {"class","prev"}, {"data-details","yada"} } )%>

// 2: pass custom type decorated with descriptor attributes
public class CustomArgs
{
    public CustomArgs( string className, string dataDetails ) { ... }

    [DisplayName("class")]
    public string Class { get; set; }
    [DisplayName("data-details")]
    public string DataDetails { get; set; }
}

<%= Html.ActionLink( "back", "Search",
    new { keyword = Model.Keyword, page = Model.currPage - 1},
    new CustomArgs( "prev", "yada" ) )%>

Just ideas, haven't tested it.

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

How do you read scanf until EOF in C?

Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

How do I execute a string containing Python code in Python?

Ok .. I know this isn't exactly an answer, but possibly a note for people looking at this as I was. I wanted to execute specific code for different users/customers but also wanted to avoid the exec/eval. I initially looked to storing the code in a database for each user and doing the above.

I ended up creating the files on the file system within a 'customer_filters' folder and using the 'imp' module, if no filter applied for that customer, it just carried on

import imp


def get_customer_module(customerName='default', name='filter'):
    lm = None
    try:
        module_name = customerName+"_"+name;
        m = imp.find_module(module_name, ['customer_filters'])
        lm = imp.load_module(module_name, m[0], m[1], m[2])
    except:
        ''
        #ignore, if no module is found, 
    return lm

m = get_customer_module(customerName, "filter")
if m is not None:
    m.apply_address_filter(myobj)

so customerName = "jj" would execute apply_address_filter from the customer_filters\jj_filter.py file

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

How to convert QString to std::string?

You can use this;

QString data;
data.toStdString().c_str();

Android-java- How to sort a list of objects by a certain value within the object

"Android-java" is here by no means different than "normal java", so yes Collections.sort() would be a good approach.

How do I select a sibling element using jQuery?

also if you need to select a sibling with a name rather than the class, you could use the following

var $sibling = $(this).siblings('input[name=bidbutton]');

In STL maps, is it better to use map::insert than []?

insert is better from the point of exception safety.

The expression map[key] = value is actually two operations:

  1. map[key] - creating a map element with default value.
  2. = value - copying the value into that element.

An exception may happen at the second step. As result the operation will be only partially done (a new element was added into map, but that element was not initialized with value). The situation when an operation is not complete, but the system state is modified, is called the operation with "side effect".

insert operation gives a strong guarantee, means it doesn't have side effects (https://en.wikipedia.org/wiki/Exception_safety). insert is either completely done or it leaves the map in unmodified state.

http://www.cplusplus.com/reference/map/map/insert/:

If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee).

Why is this HTTP request not working on AWS Lambda?

Of course, I was misunderstanding the problem. As AWS themselves put it:

For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling context.done() in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.

I was calling context.done way before any callbacks for the request fired, causing the termination of my function ahead of time.

The working code is this:

var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)

Although you will still find the succeed, done and fail on the context parameter, AWS suggest to use the callback function instead or null is returned by default.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

How to get the text node of an element?

This is my solution in ES6 to create a string contraining the concatenated text of all childnodes (recursive). Note that is also visit the shdowroot of childnodes.

function text_from(node) {
    const extract = (node) => [...node.childNodes].reduce(
        (acc, childnode) => [
            ...acc,
            childnode.nodeType === Node.TEXT_NODE ? childnode.textContent.trim() : '',
            ...extract(childnode),
            ...(childnode.shadowRoot ? extract(childnode.shadowRoot) : [])],
        []);

    return extract(node).filter(text => text.length).join('\n');
}

This solution was inspired by the solution of https://stackoverflow.com/a/41051238./1300775.

Rename multiple columns by names

names(x)[names(x) %in% c("q","e")]<-c("A","B")

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

How to change text color and console color in code::blocks?

textcolor function is no longer supported in the latest compilers.

This the simplest way to change text color in Code Blocks. You can use system function.

To change Text Color :

#include<stdio.h> 
#include<stdlib.h> //as system function is in the standard library

int main()        
        {
          system("color 1"); //here 1 represents the text color
          printf("This is dummy program for text color");
          return 0;
        }

If you want to change both the text color & console color you just need to add another color code in system function

To change Text Color & Console Color :

system("color 41"); //here 4 represents the console color and 1 represents the text color

N.B: Don't use spaces between color code like these

system("color 4 1");

Though if you do it Code Block will show all the color codes. You can use this tricks to know all supported color codes.

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

For Nginx, the only thing that worked for me was adding this header:

add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';

Along with the Access-Control-Allow-Origin header:

add_header 'Access-Control-Allow-Origin' '*';

Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.

In Python, what happens when you import inside of a function?

It imports once when the function executes first time.

Pros:

  • imports related to the function they're used in
  • easy to move functions around the package

Cons:

  • couldn't see what modules this module might depend on

How to stop java process gracefully?

Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int).

However a hard kill (kill -9 or kill -SIGKILL) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.

Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!

Android webview launches browser when calling loadurl

Simply Answer you can use like this

public class MainActivity extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         WebView webView = new WebView(this);
         setContentView(webView);
         webView.setWebViewClient(new WebViewClient());
         webView.loadUrl("http://www.google.com");
   }
}

Default optional parameter in Swift function

You are conflating Optional with having a default. An Optional accepts either a value or nil. Having a default permits the argument to be omitted in calling the function. An argument can have a default value with or without being of Optional type.

func someFunc(param1: String?,
          param2: String = "default value",
          param3: String? = "also has default value") {
    print("param1 = \(param1)")

    print("param2 = \(param2)")

    print("param3 = \(param3)")
}

Example calls with output:

someFunc(param1: nil, param2: "specific value", param3: "also specific value")

param1 = nil
param2 = specific value
param3 = Optional("also specific value")

someFunc(param1: "has a value")

param1 = Optional("has a value")
param2 = default value
param3 = Optional("also has default value")

someFunc(param1: nil, param3: nil)

param1 = nil
param2 = default value
param3 = nil

To summarize:

  • Type with ? (e.g. String?) is an Optional may be nil or may contain an instance of Type
  • Argument with default value may be omitted from a call to function and the default value will be used
  • If both Optional and has default, then it may be omitted from function call OR may be included and can be provided with a nil value (e.g. param1: nil)

Moment JS start and end of given month

The following code should work:

$('#reportrange').daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    'Hoy': [moment(), moment()],
                    'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Ultimos 7 dias': [moment().subtract(6, 'days'), moment()],
                    'Ultimos 30 dias': [moment().subtract(29, 'days'), moment()],
                    'Mes actual': [moment().startOf('month'), moment().endOf('month')],
                    'Ultimo mes': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'Enero': [moment().month(0).startOf('month') , moment().month(0).endOf('month')],
                    'Febrero': [moment().month(1).startOf('month') , moment().month(1).endOf('month')],
                    'Marzo': [moment().month(2).startOf('month') , moment().month(2).endOf('month')],
                    'Abril': [moment().month(3).startOf('month') , moment().month(3).endOf('month')],
                    'Mayo': [moment().month(4).startOf('month') , moment().month(4).endOf('month')],
                    'Junio': [moment().month(5).startOf('month') , moment().month(5).endOf('month')],
                    'Julio': [moment().month(6).startOf('month') , moment().month(6).endOf('month')],
                    'Agosto': [moment().month(7).startOf('month') , moment().month(7).endOf('month')],
                    'Septiembre': [moment().month(8).startOf('month') , moment().month(8).endOf('month')],
                    'Octubre': [moment().month(9).startOf('month') , moment().month(9).endOf('month')],
                    'Noviembre': [moment().month(10).startOf('month') , moment().month(10).endOf('month')],
                    'Diciembre': [moment().month(11).startOf('month') , moment().month(11).endOf('month')]
                }
            }, cb);

send Content-Type: application/json post with node.js

Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

How to add button tint programmatically

The way I managed to get mine to work was by using CompoundButtonCompat.setButtonTintList(button, colour).

To my understanding this works regardless of android version.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:

http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.

You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!

Hope it helps :)

How to use Checkbox inside Select Option

You can use this library on git for this purpose https://github.com/ehynds/jquery-ui-multiselect-widget

for initiating the selectbox use this

    $("#selectBoxId").multiselect().multiselectfilter();

and when you have the data ready in json (from ajax or any method), first parse the data & then assign the js array to it

    var js_arr = $.parseJSON(/*data from ajax*/);
    $("#selectBoxId").val(js_arr);
    $("#selectBoxId").multiselect("refresh");

R: Comment out block of code

Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.

It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.

These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.

Bulk Insertion in Laravel using eloquent ORM

I searched many times for it, finally used custom timestamps like below:

$now = Carbon::now()->toDateTimeString();
Model::insert([
    ['name'=>'Foo', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Bar', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Baz', 'created_at'=>$now, 'updated_at'=>$now],
    ..................................
]);

What are the different types of keys in RDBMS?

There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

Installing OpenCV on Windows 7 for Python 2.7

One thing that needs to be mentioned. You have to use the x86 version of Python 2.7. OpenCV doesn't support Python x64. I banged my head on this for a bit until I figured that out.

That said, follow the steps in Abid Rahman K's answer. And as Antimony said, you'll need to do a 'from cv2 import cv'

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Call a python function from jinja2

Note: This is Flask specific!

I know this post is quite old, but there are better methods of doing this in the newer versions of Flask using context processors.

Variables can easily be created:

@app.context_processor
def example():
    return dict(myexample='This is an example')

The above can be used in a Jinja2 template with Flask like so:

{{ myexample }}

(Which outputs This is an example)

As well as full fledged functions:

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

The above when used like so:

{{ format_price(0.33) }}

(Which outputs the input price with the currency symbol)

Alternatively, you can use jinja filters, baked into Flask. E.g. using decorators:

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

Or, without decorators, and manually registering the function:

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

Filters applied with the above two methods can be used like this:

{% for x in mylist | reverse %}
{% endfor %}

Java 8 Streams: multiple filters vs. complex condition

This test shows that your second option can perform significantly better. Findings first, then the code:

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}

now the code:

enum Gender {
    FEMALE,
    MALE
}

static class User {
    Gender gender;
    int age;

    public User(Gender gender, int age){
        this.gender = gender;
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

static long test1(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test2(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(u -> u.getGender() == Gender.FEMALE)
            .filter(u -> u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test3(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

public static void main(String... args) {
    int size = 10000000;
    List<User> users =
    IntStream.range(0,size)
            .mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
            .collect(Collectors.toCollection(()->new ArrayList<>(size)));
    repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
    repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
    repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);
}

private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
    System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
            .mapToLong(i -> test.applyAsLong(users))
            .summaryStatistics());
}

Group By Multiple Columns

Use an anonymous type.

Eg

group x by new { x.Column1, x.Column2 }

How can I determine whether a 2D Point is within a Polygon?

This question is so interesting. I have another workable idea different from other answers to this post. The idea is to use the sum of angles to decide whether the target is inside or outside. Better known as winding number.

Let x be the target point. Let array [0, 1, .... n] be the all the points of the area. Connect the target point with every border point with a line. If the target point is inside of this area. The sum of all angles will be 360 degrees. If not the angles will be less than 360.

Refer to this image to get a basic understanding of the idea: enter image description here

My algorithm assumes the clockwise is the positive direction. Here is a potential input:

[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]

The following is the python code that implements the idea:

def isInside(self, border, target):
degree = 0
for i in range(len(border) - 1):
    a = border[i]
    b = border[i + 1]

    # calculate distance of vector
    A = getDistance(a[0], a[1], b[0], b[1]);
    B = getDistance(target[0], target[1], a[0], a[1])
    C = getDistance(target[0], target[1], b[0], b[1])

    # calculate direction of vector
    ta_x = a[0] - target[0]
    ta_y = a[1] - target[1]
    tb_x = b[0] - target[0]
    tb_y = b[1] - target[1]

    cross = tb_y * ta_x - tb_x * ta_y
    clockwise = cross < 0

    # calculate sum of angles
    if(clockwise):
        degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))
    else:
        degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))

if(abs(round(degree) - 360) <= 3):
    return True
return False

File Explorer in Android Studio

Android Studio 3 Canary 1 has a new Device File Explorer

View -> Tool Windows -> Device File Explorer

So much better than DDMS and is the new improved way to get files off of your device!

Allows you to 'Open', 'Save As', 'Delete', 'Synchronize' and 'Copy Path'. Pretty awesome stuff!

Android Studio 3 Canary 1 - Device File Explorer

Mapping over values in a python dictionary

Due to PEP-0469 which renamed iteritems() to items() and PEP-3113 which removed Tuple parameter unpacking, in Python 3.x you should write Martijn Pieters? answer like this:

my_dictionary = dict(map(lambda item: (item[0], f(item[1])), my_dictionary.items()))

How to get all properties values of a JavaScript Object (without knowing the keys)?

var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

Query EC2 tags from within instance

Download and run a standalone executable to do that.

Sometimes one cannot install awscli that depends on python. docker might be out of the picture too.

Here is my implementation in golang: https://github.com/hmalphettes/go-ec2-describe-tags

Input jQuery get old value before onchange and get value after on change

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

SET versus SELECT when assigning variables?

I believe SET is ANSI standard whereas the SELECT is not. Also note the different behavior of SET vs. SELECT in the example below when a value is not found.

declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */

set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */

JSON.Net Self referencing loop detected

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

Single JsonConvert with an overload:

JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

How to override toString() properly in Java?

If you're interested in Unit-Tests, then you can declare a public "ToStringTemplate", and then you can unit test your toString. Even if you don't unit-test it, I think its "cleaner" and uses String.format.

public class Kid {

    public static final String ToStringTemplate = "KidName='%1s', Height='%2s', GregCalendar='%3s'";

    private String kidName;
    private double height;
    private GregorianCalendar gregCalendar;

    public String getKidName() {
        return kidName;
    }

    public void setKidName(String kidName) {
        this.kidName = kidName;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public GregorianCalendar getGregCalendar() {
        return gregCalendar;
    }

    public void setGregCalendar(GregorianCalendar gregCalendar) {
        this.gregCalendar = gregCalendar;
    }

    public String toString() { 
        return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
    } 
}

Now you can unit test by create the Kid, setting the properties, and doing your own string.format on the ToStringTemplate and comparing.

making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.

How do I use InputFilter to limit characters in an EditText in Android?

This simple solution worked for me when I needed to prevent the user from entering empty strings into an EditText. You can of course add more characters:

InputFilter textFilter = new InputFilter() {

@Override

public CharSequence filter(CharSequence c, int arg1, int arg2,

    Spanned arg3, int arg4, int arg5) {

    StringBuilder sbText = new StringBuilder(c);

    String text = sbText.toString();

    if (text.contains(" ")) {    
        return "";   
    }    
    return c;   
    }   
};

private void setTextFilter(EditText editText) {

    editText.setFilters(new InputFilter[]{textFilter});

}

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

How to count the number of files in a directory using Python

Here is a simple one-line command that I found useful:

print int(os.popen("ls | wc -l").read())

'Use of Unresolved Identifier' in Swift

One possible issue is that your new class has a different Target or different Targets from the other one.

For example, it might have a testing target while the other one doesn't. For this specific case, you have to include all of your classes in the testing target or none of them.

Targets

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.

My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.

# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE

Is it possible to assign numeric value to an enum in Java?

public enum EXIT_CODE {
    A(104), B(203);

    private int numVal;

    EXIT_CODE(int numVal) {
        this.numVal = numVal;
    }

    public int getNumVal() {
        return numVal;
    }
}

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.

Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.

In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.

Note

  • Do not blindly delete everything directly from disk that you "think" is not required occupying. I did that once and had to re-download.
  • Make sure you have a list of all active projects with the kind of emulators (if any) and API Levels and Build tools required for those to continue working/compiling properly.

First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:

Steps to safely clear up unwanted stuff from Android SDK folder on the disk

  1. Open the Stand Alone Android SDK Manager. To open do one of the following:
  • Click the SDK Manager button on toolbar in android studio or eclipse
  • In Android Studio, go to settings and search "Android SDK". Click Android SDK -> "Open Standalone SDK Manager"
  • In Eclipse, open the "Window" menu and select "Android SDK Manager"
  • Navigate to the location of the android-sdk directory on your computer and run "SDK Manager.exe"

.

  1. Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.

.

  1. Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.

.

  1. In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.

In the end the clean android sdk installed components should look something like this in the SDK manager.

enter image description here

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call command, and the second one would share the first one's window.

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit command at the end of your second batch file, or you'll be within a second cmd shell once everything is done.

Are table names in MySQL case sensitive?

  1. Locate the file at /etc/mysql/my.cnf

  2. Edit the file by adding the following lines:

     [mysqld]
    
     lower_case_table_names=1
    
  3. sudo /etc/init.d/mysql restart

  4. Run mysqladmin -u root -p variables | grep table to check that lower_case_table_names is 1 now

You might need to recreate these tables to make it work.

Is it possible to use 'else' in a list comprehension?

Yes, else can be used in Python inside a list comprehension with a Conditional Expression ("ternary operator"):

>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']

Here, the parentheses "()" are just to emphasize the conditional expression, they are not necessarily required (Operator precedence).

Additionaly, several expressions can be nested, resulting in more elses and harder to read code:

>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>

On a related note, a comprehension can also contain its own if condition(s) at the end:

>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']

Conditions? Yes, multiple ifs are possible, and actually multiple fors, too:

>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]

(The single underscore _ is a valid variable name (identifier) in Python, used here just to show it's not actually used. It has a special meaning in interactive mode)

Using this for an additional conditional expression is possible, but of no real use:

>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]

Comprehensions can also be nested to create "multi-dimensional" lists ("arrays"):

>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]

Last but not least, a comprehension is not limited to creating a list, i.e. else and if can also be used the same way in a set comprehension:

>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}

and a dictionary comprehension:

>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}

The same syntax is also used for Generator Expressions:

>>> for g in ("a" if b else "c" for b in "generator"):
...     print(g, end="")
...
aaaaaaaaa>>>

which can be used to create a tuple (there is no tuple comprehension).


Further reading:

How to write a large buffer into a binary file in C++, fast?

Try the following, in order:

  • Smaller buffer size. Writing ~2 MiB at a time might be a good start. On my last laptop, ~512 KiB was the sweet spot, but I haven't tested on my SSD yet.

    Note: I've noticed that very large buffers tend to decrease performance. I've noticed speed losses with using 16-MiB buffers instead of 512-KiB buffers before.

  • Use _open (or _topen if you want to be Windows-correct) to open the file, then use _write. This will probably avoid a lot of buffering, but it's not certain to.

  • Using Windows-specific functions like CreateFile and WriteFile. That will avoid any buffering in the standard library.

jQuery UI 1.10: dialog and zIndex option

Add this before calling dialog

$( obiect ).css('zIndex',9999);

And remove

 zIndex: 700,

from dialog

Set background colour of cell to RGB value of data in cell

Setting the Color property alone will guarantee an exact match. Excel 2003 can only handle 56 colors at once. The good news is that you can assign any rgb value at all to those 56 slots (which are called ColorIndexs). When you set a cell's color using the Color property this causes Excel to use the nearest "ColorIndex". Example: Setting a cell to RGB 10,20,50 (or 3281930) will actually cause it to be set to color index 56 which is 51,51,51 (or 3355443).

If you want to be assured you got an exact match, you need to change a ColorIndex to the RGB value you want and then change the Cell's ColorIndex to said value. However you should be aware that by changing the value of a color index you change the color of all cells already using that color within the workbook. To give an example, Red is ColorIndex 3. So any cell you made Red you actually made ColorIndex 3. And if you redefine ColorIndex 3 to be say, purple, then your cell will indeed be made purple, but all other red cells in the workbook will also be changed to purple.

There are several strategies to deal with this. One way is to choose an index not yet in use, or just one that you think will not be likely to be used. Another way is to change the RGB value of the nearest ColorIndex so your change will be subtle. The code I have posted below takes this approach. Taking advantage of the knowledge that the nearest ColorIndex is assigned, it assigns the RGB value directly to the cell (thereby yielding the nearest color) and then assigns the RGB value to that index.

Sub Example()
    Dim lngColor As Long
    lngColor = RGB(10, 20, 50)
    With Range("A1").Interior
        .Color = lngColor
        ActiveWorkbook.Colors(.ColorIndex) = lngColor
    End With
End Sub

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

We can also run npm install with registry options for multiple custom registry URLs.

npm install --registry=https://registry.npmjs.org/ 
npm install --registry=https://custom.npm.registry.com/ 

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Very nice problem. I'd go for using a set difference for Qk. A lot of programming languages even have support for it, like in Ruby:

missing = (1..100).to_a - bag

It's probably not the most efficient solution but it's one I would use in real life if I was faced with such a task in this case (known boundaries, low boundaries). If the set of number would be very large then I would consider a more efficient algorithm, of course, but until then the simple solution would be enough for me.

C# 30 Days From Todays Date

A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

Django - taking values from POST request

Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects

Also your hidden field needs a reliable name and then a value:

<input type="hidden" name="title" value="{{ source.title }}">

Then in a view:

request.POST.get("title", "")

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

Could not load file or assembly '***.dll' or one of its dependencies

I had the same problem. For me, it was caused by the default settings in the local IIS server on my machine. So the easy way to fix it, was to use the built in Visual Studio development server instead :)

Newer IIS versions on x64 machines have a setting that doesn't allow 32 bit applications to run by default. To enable 32 bit applications in the local IIS, select the relevant application pool in IIS manager, click "Advanced settings", and change "Enable 32-Bit Applications" from False to True

How to convert Base64 String to javascript file object like as from file input form?

const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

Fastest way to remove first char in a String

I'd guess that Remove and Substring would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

initialize a const array in a class initializer in C++

std::vector uses the heap. Geez, what a waste that would be just for the sake of a const sanity-check. The point of std::vector is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.

#include <stdio.h>


template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
    size_t length;

public:
    ConstFixedSizeArrayFiller() : length(0) {
    }

    virtual ~ConstFixedSizeArrayFiller() {
    }

    virtual void Fill(Type *array) = 0;

protected:
    void add_element(Type *array, const Type & element)
    {
        if(length >= MaxLength) {
            // todo: throw more appropriate out-of-bounds exception
            throw 0;
        }
        array[length] = element;
        length++;
    }
};


template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
    Type array[Length];

public:
    explicit ConstFixedSizeArray(
        ConstFixedSizeArrayFiller<Type, Length> & filler
    ) {
        filler.Fill(array);
    }

    const Type *Array() const {
        return array;
    }

    size_t ArrayLength() const {
        return Length;
    }
};


class a {
private:
    class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
    public:
        virtual ~b_filler() {
        }

        virtual void Fill(int *array) {
            add_element(array, 87);
            add_element(array, 96);
        }
    };

    const ConstFixedSizeArray<int, 2> b;

public:
    a(void) : b(b_filler()) {
    }

    void print_items() {
        size_t i;
        for(i = 0; i < b.ArrayLength(); i++)
        {
            printf("%d\n", b.Array()[i]);
        }
    }
};


int main()
{
    a x;
    x.print_items();
    return 0;
}

ConstFixedSizeArrayFiller and ConstFixedSizeArray are reusable.

The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const after this initialization.

The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.

b_filler is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.

I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

Kotlin: How to get and set a text to TextView in Android using Kotlin?

The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.

val text: TextView = findViewById(R.id.android_text) as TextView

Where 'android_text' is the ID of your textView

What is the javascript filename naming convention?

One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.

product-name.plugin-ver.sion.filetype.js

where the product-name + plugin pair can also represent a namespace and a module. The version and filetype are usually optional.

filetype can be something relative to how the content of the file is. Often seen are:

  • min for minified files
  • custom for custom built or modified files

Examples:

  • jquery-1.4.2.min.js
  • jquery.plugin-0.1.js
  • myapp.invoice.js

Python equivalent of a given wget command

For Windows and Python 3.x, my two cents contribution about renaming the file on download :

  1. Install wget module : pip install wget
  2. Use wget :
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')

Truely working command line example :

python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"

Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

How to open the second form?

In a single line it would be:

(new Form2()).Show();

Hope it helps.

How to find out what is locking my tables?

exec sp_lock

This query should give you existing locks.

exec sp_who SPID -- will give you some info

Having spids, you could check activity monitor(processes tab) to find out what processes are locking the tables ("details" for more info and "kill process" to kill it).

Add padding to HTML text input field

<input class="form-control search-query input_style" placeholder="Search…"  name="" title="Search for:" type="text">


.input_style
{
    padding-left:20px;
}

Twitter Bootstrap hide css class and jQuery

As dfsq said i just had to use removeClass("hide") instead of toggle()

How to get the difference between two arrays in JavaScript?

  • Pure JavaScript solution (no libraries)
  • Compatible with older browsers (doesn't use filter)
  • O(n^2)
  • Optional fn callback parameter that lets you specify how to compare array items

_x000D_
_x000D_
function diff(a, b, fn){_x000D_
    var max = Math.max(a.length, b.length);_x000D_
        d = [];_x000D_
    fn = typeof fn === 'function' ? fn : false_x000D_
    for(var i=0; i < max; i++){_x000D_
        var ac = i < a.length ? a[i] : undefined_x000D_
            bc = i < b.length ? b[i] : undefined;_x000D_
        for(var k=0; k < max; k++){_x000D_
            ac = ac === undefined || (k < b.length && (fn ? fn(ac, b[k]) : ac == b[k])) ? undefined : ac;_x000D_
            bc = bc === undefined || (k < a.length && (fn ? fn(bc, a[k]) : bc == a[k])) ? undefined : bc;_x000D_
            if(ac == undefined && bc == undefined) break;_x000D_
        }_x000D_
        ac !== undefined && d.push(ac);_x000D_
        bc !== undefined && d.push(bc);_x000D_
    }_x000D_
    return d;_x000D_
}_x000D_
_x000D_
alert(_x000D_
    "Test 1: " + _x000D_
    diff(_x000D_
        [1, 2, 3, 4],_x000D_
        [1, 4, 5, 6, 7]_x000D_
      ).join(', ') +_x000D_
    "\nTest 2: " +_x000D_
    diff(_x000D_
        [{id:'a',toString:function(){return this.id}},{id:'b',toString:function(){return this.id}},{id:'c',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}],_x000D_
        [{id:'a',toString:function(){return this.id}},{id:'e',toString:function(){return this.id}},{id:'f',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}],_x000D_
        function(a, b){ return a.id == b.id; }_x000D_
    ).join(', ')_x000D_
);
_x000D_
_x000D_
_x000D_

Who sets response content-type in Spring MVC (@ResponseBody)

Note that in Spring MVC 3.1 you can use the MVC namespace to configure message converters:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

Or code-based configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Convert timestamp in milliseconds to string formatted time in Java

Doing

logEvent.timeStamp / (1000*60*60)

will give you hours, not minutes. Try:

logEvent.timeStamp / (1000*60)

and you will end up with the same answer as

TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

ImportError: No module named requests

If you are using anaconda step 1: where python step 2: open anaconda prompt in administrator mode step 3: cd <python path> step 4: install the package in this location

How can I detect the touch event of an UIImageView?

You might want to override the touchesBegan:withEvent: method of the UIView (or subclass) that contains your UIImageView subview.

Within this method, test if any of the UITouch touches fall inside the bounds of the UIImageView instance (let's say it is called imageView).

That is, does the CGPoint element [touch locationInView] intersect with with the CGRect element [imageView bounds]? Look into the function CGRectContainsPoint to run this test.

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

MAX(DATE) - SQL ORACLE

SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
    SELECT MAX(p2.PAYM_DATE)
    FROM user_payments as p2
    WHERE p2.USER_ID = p.USER_ID
)

IntelliJ IDEA generating serialVersionUID

I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.

How to compile and run C files from within Notepad++ using NppExec plugin?

I've written just this to execute compiling and run the file after, plus fileinputname = fileoutputname on windowsmashines, if your compilerpath is registred in the windows PATH-var:

NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
set LEN~ strrfind $(FILE_NAME) .
set EXENAME ~ substr 0 $(LEN) $(FILE_NAME)
set $(EXENAME) = $(EXENAME).exe
c++.exe "$(FILE_NAME)" -o "$(EXENAME)"
"$(EXENAME)"

should work for any compiler if you change c++.exe to what you want

Export query result to .csv file in SQL Server 2008

If the database in question is local, the following is probably the most robust way to export a query result to a CSV file (that is, giving you the most control).

  1. Copy the query.
  2. In Object Explorer right-click on the database in question.
  3. Select "Tasks" >> "Export Data..."
  4. Configure your datasource, and click "Next".
  5. Choose "Flat File" or "Microsoft Excel" as destination.
  6. Specify a file path.
  7. If working with a flat file, configure as desired. If working with Microsoft Excel, select "Excel 2007" (previous versions have a row limit at 64k)
  8. Select "Write a query to specify the data to transfer"
  9. Paste query from Step 1.
  10. Click next >> review mappings >> click next >> select "run immediately" >> click "finish" twice.

After going through this process exhaustively, I found the following to be the best option

PowerShell Script

$dbname = "**YOUR_DB_NAME_WITHOUT_STARS**"
$AttachmentPath = "c:\\export.csv"
$QueryFmt= @"
**YOUR_QUERY_WITHOUT_STARS**
"@

Invoke-Sqlcmd   -ServerInstance **SERVER_NAME_WITHOUT_STARS** -Database  $dbname -Query $QueryFmt | Export-CSV $AttachmentPath -NoTypeInformation

Run PowerShell as Admin

& "c:\path_to_your_ps1_file.ps1"

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

Jquery each - Stop loop and return object

Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find call's return value:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

_x000D_
_x000D_
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';

var test = findXX('o322');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Multiple models in a view

Use a view model that contains multiple view models:

   namespace MyProject.Web.ViewModels
   {
      public class UserViewModel
      {
          public UserDto User { get; set; }
          public ProductDto Product { get; set; }
          public AddressDto Address { get; set; }
      }
   }

In your view:

  @model MyProject.Web.ViewModels.UserViewModel

  @Html.LabelFor(model => model.User.UserName)
  @Html.LabelFor(model => model.Product.ProductName)
  @Html.LabelFor(model => model.Address.StreetName)

How Do I Upload Eclipse Projects to GitHub?

While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:

First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.

On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:

git init

which initiates a new git repository in that directory.

When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.

git remote add origin https://github.com/[username]/[reponame].git

You need to add you existing files to your local commit:

git add .   # this adds all the files

Then you need to make an initial commit, so you do:

git commit -a -m "Initial commit" # this stages your files locally for commit. 
                                  # they haven't actually been pushed yet

Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:

git push -u origin --all

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

How to create an empty file with Ansible?

A combination of two answers, with a twist. The code will be detected as changed, when the file is created or the permission updated.

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: 0644
    modification_time: preserve
    access_time: preserve
  changed_when: >
    p.diff.before.state == "absent" or
    p.diff.before.mode|default("0644") != "0644"

and a version that also corrects the owner and group and detects it as changed when it does correct these:

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    state: touch
    mode: 0644
    owner: root
    group: root
    modification_time: preserve
    access_time: preserve
  register: p
  changed_when: >
    p.diff.before.state == "absent" or
    p.diff.before.mode|default("0644") != "0644" or
    p.diff.before.owner|default(0) != 0 or
    p.diff.before.group|default(0) != 0

Calling a function on bootstrap modal open

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

How can I get CMake to find my alternative Boost installation?

I had a similar issue, and I could use customized Boost libraries by adding the below lines to my CMakeLists.txt file:

set(Boost_NO_SYSTEM_PATHS TRUE)
if (Boost_NO_SYSTEM_PATHS)
  set(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../3p/boost")
  set(BOOST_INCLUDE_DIRS "${BOOST_ROOT}/include")
  set(BOOST_LIBRARY_DIRS "${BOOST_ROOT}/lib")
endif (Boost_NO_SYSTEM_PATHS)
find_package(Boost REQUIRED regex date_time system filesystem thread graph program_options)
include_directories(${BOOST_INCLUDE_DIRS})

Access all Environment properties as a Map or Properties object

You need something like this, maybe it can be improved. This is a first attempt:

...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...

@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer 
{
    @Autowired
    Environment env;

    public void someMethod() {
        ...
        Map<String, Object> map = new HashMap();
        for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
            PropertySource propertySource = (PropertySource) it.next();
            if (propertySource instanceof MapPropertySource) {
                map.putAll(((MapPropertySource) propertySource).getSource());
            }
        }
        ...
    }
...

Basically, everything from the Environment that's a MapPropertySource (and there are quite a lot of implementations) can be accessed as a Map of properties.

How do I do base64 encoding on iOS?

iOS includes built in support for base64 encoding and decoding. If you look at resolv.h you should see the two functions b64_ntop and b64_pton . The Square SocketRocket library provides a reasonable example of how to use these functions from objective-c.

These functions are pretty well tested and reliable - unlike many of the implementations you may find in random internet postings. Don't forget to link against libresolv.dylib.

Search and replace a line in a file in Python

If you're wanting a generic function that replaces any text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:

import re
def replace( filePath, text, subs, flags=0 ):
    with open( filePath, "r+" ) as file:
        fileContents = file.read()
        textPattern = re.compile( re.escape( text ), flags )
        fileContents = textPattern.sub( subs, fileContents )
        file.seek( 0 )
        file.truncate()
        file.write( fileContents )

How to get the anchor from the URL using jQuery?

For current window, you can use this:

var hash = window.location.hash.substr(1);

To get the hash value of the main window, use this:

var hash = window.top.location.hash.substr(1);

If you have a string with an URL/hash, the easiest method is:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

var hash = $(location).attr('hash');

Textarea onchange detection

Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.

<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea> 
<div><span id="spn"></span> characters left</div>

function check(){
    var string = document.getElementById("url").value
    var left = 15 - string.length;
    document.getElementById("spn").innerHTML = left;
}

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

I got a great response from my kids with a quick VB script to manipulate a Microsoft Agent character. For those that aren't familiar with MS Agent, it's a series of animated onscreen characters that can be manipulated via a COM interface. You can download the code and characters at the Microsoft Agent download page.

The folllowing few lines will make the Merlin character appear on screen, fly around, knock on the screen to get your attention, and say hello.

agentName = "Merlin"
agentPath = "c:\windows\msagent\chars\" & agentName & ".acs"
Set agent = CreateObject("Agent.Control.2")

agent.Connected = TRUE
agent.Characters.Load agentName, agentPath
Set character = agent.Characters.Character(agentName)

character.Show

character.MoveTo 500, 400
character.Play "GetAttention"
character.Speak "Hello, how are you?"
Wscript.Sleep 15000
character.Stop
character.Play "Hide"

There are a great many other commands you can use. Check http://www.microsoft.com/technet/scriptcenter/funzone/agent.mspx for more information.

EDIT 2011-09-02 I recently discovered that Microsoft Agent is not natively installed on Windows 7. However it is offered as a separate download here. I have not tested this so cannot verify whether it operates.

How to use Fiddler to monitor WCF service

So simple, all you need is to change the address in the config client: instead of 'localhost' change to the machine name or IP

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

I got this error when trying to install a python package in a Docker container. For me, the issue was that the docker image did not have a locale configured. Adding the following code to the Dockerfile solved the problem for me.

# Avoid ascii errors when reading files in Python
RUN apt-get install -y locales && locale-gen en_US.UTF-8
ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' LC_ALL='en_US.UTF-8'

Script not served by static file handler on IIS7.5

I solved this problem by enabling WCF Services

Programs and Features > NET Framework 4.5 Services > WCF Services> HTTP Activation node

But you have to admit it guys this ENTIRE IIS setup configure/guess/trial and see/try this/try that spends 4 or 5 of our days trying to find a solution around approach IS A COMPLETE AND UTTER JOKE.

SURELY, 'IIS' IS THE BIGGEST CONFIDENCE TRICK EVER PLAYED ON MANKIND TO DATE

Insert an item into sorted list in Python

You should use the bisect module. Also, the list needs to be sorted before using bisect.insort_left

It's a pretty big difference.

>>> l = [0, 2, 4, 5, 9]
>>> bisect.insort_left(l,8)
>>> l
[0, 2, 4, 5, 8, 9]

timeit.timeit("l.append(8); l = sorted(l)",setup="l = [4,2,0,9,5]; import bisect; l = sorted(l)",number=10000)
    1.2235019207000732

timeit.timeit("bisect.insort_left(l,8)",setup="l = [4,2,0,9,5]; import bisect; l=sorted(l)",number=10000)
    0.041441917419433594

Convert True/False value read from file to boolean

You can do with json.

In [124]: import json

In [125]: json.loads('false')
Out[125]: False

In [126]: json.loads('true')
Out[126]: True

Simple insecure two-way data "obfuscation"?

Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays.

NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use https://www.random.org/bytes/ to generate a new set easily:

Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place.


using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;


public class SimpleAES
{
    // Change these keys
    private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });

    // a hardcoded IV should not be used for production AES-CBC code
    // IVs should be unpredictable per ciphertext
    private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 });


    private ICryptoTransform EncryptorTransform, DecryptorTransform;
    private System.Text.UTF8Encoding UTFEncoder;

    public SimpleAES()
    {
        //This is our encryption method
        RijndaelManaged rm = new RijndaelManaged();

        //Create an encryptor and a decryptor using our encryption method, key, and vector.
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Used to translate bytes to text and vice versa
        UTFEncoder = new System.Text.UTF8Encoding();
    }

    /// -------------- Two Utility Methods (not used but may be useful) -----------
    /// Generates an encryption key.
    static public byte[] GenerateEncryptionKey()
    {
        //Generate a Key.
        RijndaelManaged rm = new RijndaelManaged();
        rm.GenerateKey();
        return rm.Key;
    }

    /// Generates a unique encryption vector
    static public byte[] GenerateEncryptionVector()
    {
        //Generate a Vector
        RijndaelManaged rm = new RijndaelManaged();
        rm.GenerateIV();
        return rm.IV;
    }


    /// ----------- The commonly used methods ------------------------------    
    /// Encrypt some text and return a string suitable for passing in a URL.
    public string EncryptToString(string TextValue)
    {
        return ByteArrToString(Encrypt(TextValue));
    }

    /// Encrypt some text and return an encrypted byte array.
    public byte[] Encrypt(string TextValue)
    {
        //Translates our text value into a byte array.
        Byte[] bytes = UTFEncoder.GetBytes(TextValue);

        //Used to stream the data in and out of the CryptoStream.
        MemoryStream memoryStream = new MemoryStream();

        /*
         * We will have to write the unencrypted bytes to the stream,
         * then read the encrypted result back from the stream.
         */
        #region Write the decrypted value to the encryption stream
        CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
        cs.Write(bytes, 0, bytes.Length);
        cs.FlushFinalBlock();
        #endregion

        #region Read encrypted value back out of the stream
        memoryStream.Position = 0;
        byte[] encrypted = new byte[memoryStream.Length];
        memoryStream.Read(encrypted, 0, encrypted.Length);
        #endregion

        //Clean up.
        cs.Close();
        memoryStream.Close();

        return encrypted;
    }

    /// The other side: Decryption methods
    public string DecryptString(string EncryptedString)
    {
        return Decrypt(StrToByteArray(EncryptedString));
    }

    /// Decryption when working with byte arrays.    
    public string Decrypt(byte[] EncryptedValue)
    {
        #region Write the encrypted value to the decryption stream
        MemoryStream encryptedStream = new MemoryStream();
        CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
        decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
        decryptStream.FlushFinalBlock();
        #endregion

        #region Read the decrypted value from the stream.
        encryptedStream.Position = 0;
        Byte[] decryptedBytes = new Byte[encryptedStream.Length];
        encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
        encryptedStream.Close();
        #endregion
        return UTFEncoder.GetString(decryptedBytes);
    }

    /// Convert a string to a byte array.  NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
    //      System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    //      return encoding.GetBytes(str);
    // However, this results in character values that cannot be passed in a URL.  So, instead, I just
    // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
    public byte[] StrToByteArray(string str)
    {
        if (str.Length == 0)
            throw new Exception("Invalid string value in StrToByteArray");

        byte val;
        byte[] byteArr = new byte[str.Length / 3];
        int i = 0;
        int j = 0;
        do
        {
            val = byte.Parse(str.Substring(i, 3));
            byteArr[j++] = val;
            i += 3;
        }
        while (i < str.Length);
        return byteArr;
    }

    // Same comment as above.  Normally the conversion would use an ASCII encoding in the other direction:
    //      System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    //      return enc.GetString(byteArr);    
    public string ByteArrToString(byte[] byteArr)
    {
        byte val;
        string tempStr = "";
        for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
        {
            val = byteArr[i];
            if (val < (byte)10)
                tempStr += "00" + val.ToString();
            else if (val < (byte)100)
                tempStr += "0" + val.ToString();
            else
                tempStr += val.ToString();
        }
        return tempStr;
    }
}

PHP: Split a string in to an array foreach char

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

How do I get Bin Path?

Path.GetDirectoryName(Application.ExecutablePath)

eg. value:

C:\Projects\ConsoleApplication1\bin\Debug

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

How can I add new array elements at the beginning of an array in Javascript?

you have an array: var arr = [23, 45, 12, 67];

To add an item to the beginning, you want to use splice:

_x000D_
_x000D_
var arr = [23, 45, 12, 67];_x000D_
arr.splice(0, 0, 34)_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

How do I change the language of moment.js?

For those working in asynchronous environments, moment behaves unexpectedly when loading locales on demand.

Instead of

await import('moment/locale/en-ca');
moment.locale('en-ca');

reverse the order

moment.locale('en-ca');
await import('moment/locale/en-ca');

It seems like the locales are loaded into the current selected locale, overriding any previously set locale information. So switching the locale first, then loading the locale information does not cause this issue.

Git: How to find a deleted file in the project commit history?

Get a list of the deleted files and copy the full path of the deleted file

git log --diff-filter=D --summary | grep delete

Execute the next command to find commit id of that commit and copy the commit id

git log --all -- FILEPATH

Show diff of deleted file

git show COMMIT_ID -- FILE_PATH

Remember, you can write output to a file using > like

git show COMMIT_ID -- FILE_PATH > deleted.diff

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Select SQL results grouped by weeks

the provided solutions seem a little complex? this might help:

https://msdn.microsoft.com/en-us/library/ms174420.aspx

select
   mystuff,
   DATEPART ( year, MyDateColumn ) as yearnr,
   DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc

How to open CSV file in R when R says "no such file or directory"?

My issue was very simple, the working directory was not the "Source" directory that was printed when the file ran. To fix this, you can use getwd() and setwd() to get your relative links working, or just use a full path when opening the csv.

print(getwd()) # Where does the code think it is?
setwd("~/Documents") # Where do I want my code to be?
dat = read.csv("~/Documents/Data Visualization/expDataAnalysis/one/ac1_survey.csv") #just make it work!

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

First char to upper case

Or you can do

s = Character.toUpperCase(s.charAt(0)) + s.substring(1); 

Android Google Maps v2 - set zoom level for myLocation

It's doubtful you can change it on click with the default myLocation Marker. However, if you would like the app to automatically zoom in on your location once it is found, I would check out my answer to this question

Note that the answer I provided does not zoom in, but if you modify the onLocationChanged method to be like the one below, you can choose whatever zoom level you like:

@Override
public void onLocationChanged(Location location) 
{
    if( mListener != null )
    {
        mListener.onLocationChanged( location );

        //Move the camera to the user's location and zoom in!
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.0f));
    }
}

Java: is there a map function?

Be very careful with Collections2.transform() from guava. That method's greatest advantage is also its greatest danger: its laziness.

Look at the documentation of Lists.transform(), which I believe applies also to Collections2.transform():

The function is applied lazily, invoked when needed. This is necessary for the returned list to be a view, but it means that the function will be applied many times for bulk operations like List.contains(java.lang.Object) and List.hashCode(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned list doesn't need to be a view, copy the returned list into a new list of your choosing.

Also in the documentation of Collections2.transform() they mention you get a live view, that change in the source list affect the transformed list. This sort of behaviour can lead to difficult-to-track problems if the developer doesn't realize the way it works.

If you want a more classical "map", that will run once and once only, then you're better off with FluentIterable, also from Guava, which has an operation which is much more simple. Here is the google example for it:

FluentIterable
       .from(database.getClientList())
       .filter(activeInLastMonth())
       .transform(Functions.toStringFunction())
       .limit(10)
       .toList();

transform() here is the map method. It uses the same Function<> "callbacks" as Collections.transform(). The list you get back is read-only though, use copyInto() to get a read-write list.

Otherwise of course when java8 comes out with lambdas, this will be obsolete.

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

Zero-pad digits in string

Solution using str_pad:

str_pad($digit,2,'0',STR_PAD_LEFT);

Benchmark on php 5.3

Result str_pad : 0.286863088608

Result sprintf : 0.234171152115

Code:

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    str_pad(9,2,'0',STR_PAD_LEFT);
    str_pad(15,2,'0',STR_PAD_LEFT);
    str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    sprintf("%02d", 9);
    sprintf("%02d", 15);
    sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Sometimes it is caused due to the project points to JRE rather than JDK.So try this,

1.Right Click on project -->Build Path --> Configure Build Path -->Add Library -->JRE System Library -->Environments--> Installed JREs-->Point to java folder in c: drive (Windows) and select JDK folder and ok.

2.Remove the already present JRE from build path.

How to write specific CSS for mozilla, chrome and IE

You could use php to echo the browser name as a body class, e.g.

<body class="mozilla">

Then, your conditional CSS would look like

.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.

How do I add a Fragment to an Activity with a programmatically created content view

For API level 17 or higher, View.generateViewId() will solve this problem. The utility method provides a unique id that is not used in build time.

CSS vertical alignment text inside li

As explained in here: https://css-tricks.com/centering-in-the-unknown/.

As tested in the real practice, the most reliable yet elegant solution is to insert an assistent inline element into the <li /> element as the 1st child, which height should be set to 100% (of its parent’s height, the <li />), and its vertical-align set to middle. To achieve this, you can put a <span />, but the most convenient way is to use li:after pseudo class.

Screenshot: enter image description here

ul.menu-horizontal {
    list-style-type: none;
    margin: 0;
    padding: 0;
    display: inline-block;
    vertical-align: middle;
}

ul.menu-horizontal:after {
    content: '';
    clear: both;
    float: none;
    display: block;
}

ul.menu-horizontal li {
    padding: 5px 10px;
    box-sizing: border-box;
    height: 100%;
    cursor: pointer;
    display: inline-block;
    vertical-align: middle;
    float: left;
}

/* The magic happens here! */
ul.menu-horizontal li:before {
    content: '';
    display: inline;
    height: 100%;
    vertical-align: middle;
}

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

In case anyone is still wondering...

I did it like this:

<a href="data:application/xml;charset=utf-8,your code here" download="filename.html">Save</a>

cant remember my source but it uses the following techniques\features:

  1. html5 download attribute
  2. data uri's

Found the reference:

http://paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/


EDIT: As you can gather from the comments this does NOT work in

  1. Internet Explorer (works in Edge v13 though)
  2. iOS Safari
  3. Opera Mini

http://caniuse.com/#feat=download

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

How can I make a .NET Windows Forms application that only runs in the System Tray?

notifyIcon1->ContextMenu = gcnew System::Windows::Forms::ContextMenu();
System::Windows::Forms::MenuItem^ nIItem = gcnew System::Windows::Forms::MenuItem("Open");
nIItem->Click += gcnew System::EventHandler(this, &your_class::Open_NotifyIcon);
notifyIcon1->ContextMenu->MenuItems->Add(nIItem);

Retrieving JSON Object Literal from HttpServletRequest

are you looking for this ?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());
}

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.

This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )

SELECT questionid,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM   (SELECT questionid,
               elementid,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
        FROM   emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;

Using querySelectorAll to retrieve direct children

Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?

The correct way to write a selector that is "rooted" to the current element is to use :scope.

var myDiv = getElementById("myDiv");
var fooEls = myDiv.querySelectorAll(":scope > .foo");

However, browser support is limited and you'll need a shim if you want to use it. I built scopedQuerySelectorShim for this purpose.

Should methods in a Java interface be declared with or without a public access modifier?

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.

how to add super privileges to mysql database?

just the query phpmyadmin prints after granting super user. hope help someone with console:

ON $.$ TO-> $=* doesnt show when you put two with a dot between them.

REVOKE ALL PRIVILEGES ON . FROM 'usr'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'usr'@'localhost' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

and the reverse one, removing grant:

REVOKE ALL PRIVILEGES ON . FROM 'dos007'@'localhost'; REVOKE GRANT OPTION ON . FROM 'dos007'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'dos007'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

checked on vagrant should be working in any mysql

Error #2032: Stream Error

This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5

When do we need curly braces around shell variables?

Curly braces are always needed for accessing array elements and carrying out brace expansion.

It's good to be not over-cautious and use {} for shell variable expansion even when there is no scope for ambiguity.

For example:

dir=log
prog=foo
path=/var/${dir}/${prog}      # excessive use of {}, not needed since / can't be a part of a shell variable name
logfile=${path}/${prog}.log   # same as above, . can't be a part of a shell variable name
path_copy=${path}             # {} is totally unnecessary
archive=${logfile}_arch       # {} is needed since _ can be a part of shell variable name

So, it is better to write the three lines as:

path=/var/$dir/$prog
logfile=$path/$prog.log
path_copy=$path

which is definitely more readable.

Since a variable name can't start with a digit, shell doesn't need {} around numbered variables (like $1, $2 etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {} in such contexts:

set app      # set $1 to app
fruit=$1le   # sets fruit to apple, but confusing
fruit=${1}le # sets fruit to apple, makes the intention clear

See:

Multi-dimensional associative arrays in JavaScript

If it doesn't have to be an array, you can create a "multidimensional" JS object...

<script type="text/javascript">
var myObj = { 
    fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 }, 
    mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 }, 
    sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 } 
}

document.write(myObj['fred']['apples']);
</script>

Can't connect to docker from docker-compose

The Docker machine is running. But you need to export some environment to connect to the Docker machine. By default, the docker CLI client is trying to communicate to the daemon using http+unix://var/run/docker.sock (as shown in the error message).

Export the correct environment variables using eval $(docker-machine env dev) and then try again. You can also just run docker-machine env dev to see the environment variables it will export. Notice that one of them is DOCKER_HOST, just as the error message suggests you may need to set.

Convert UTC/GMT time to local time

I came across this question as I was having a problem with the UTC dates you get back through the twitter API (created_at field on a status); I need to convert them to DateTime. None of the answers/ code samples in the answers on this page were sufficient to stop me getting a "String was not recognized as a valid DateTime" error (but it's the closest I have got to finding the correct answer on SO)

Posting this link here in case this helps someone else - the answer I needed was found on this blog post: http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/ - basically use DateTime.ParseExact with a format string instead of DateTime.Parse

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

based on meeting CodeSkill #1

validation of format should be another function :)

_x000D_
_x000D_
  _x000D_
_x000D_
function convertTimeFrom12To24(timeStr) {_x000D_
  var colon = timeStr.indexOf(':');_x000D_
  var hours = timeStr.substr(0, colon),_x000D_
      minutes = timeStr.substr(colon+1, 2),_x000D_
      meridian = timeStr.substr(colon+4, 2).toUpperCase();_x000D_
 _x000D_
  _x000D_
  var hoursInt = parseInt(hours, 10),_x000D_
      offset = meridian == 'PM' ? 12 : 0;_x000D_
  _x000D_
  if (hoursInt === 12) {_x000D_
    hoursInt = offset;_x000D_
  } else {_x000D_
    hoursInt += offset;_x000D_
  }_x000D_
  return hoursInt + ":" + minutes;_x000D_
}_x000D_
console.log(convertTimeFrom12To24("12:00 AM"));_x000D_
console.log(convertTimeFrom12To24("12:00 PM"));_x000D_
console.log(convertTimeFrom12To24("11:00 AM"));_x000D_
console.log(convertTimeFrom12To24("01:00 AM"));_x000D_
console.log(convertTimeFrom12To24("01:00 PM"));
_x000D_
_x000D_
_x000D_

svn list of files that are modified in local copy

The "Check for Modifications" command in tortoise will display a list of all changed files in the working copy. "Commit" will show all changed files as well (that you can then commit). "Revert" will also show changed files (that you can then revert).