Programs & Examples On #Case study

Fastest method of screen capturing on Windows

For C++ you can use: http://www.pinvoke.net/default.aspx/gdi32/BitBlt.html
This may hower not work on all types of 3D applications/video apps. Then this link may be more useful as it describes 3 different methods you can use.

Old answer (C#):
You can use System.Drawing.Graphics.Copy, but it is not very fast.

A sample project I wrote doing exactly this: http://blog.tedd.no/index.php/2010/08/16/c-image-analysis-auto-gaming-with-source/

I'm planning to update this sample using a faster method like Direct3D: http://spazzarama.com/2009/02/07/screencapture-with-direct3d/

And here is a link for capturing to video: How to capture screen to be video using C# .Net?

Setting a property with an EventTrigger

I modified Neutrino's solution to make the xaml look less verbose when specifying the value:

Sorry for no pictures of the rendered xaml, just imagine a [=] hamburger button that you click and it turns into [<-] a back button and also toggles the visibility of a Grid.

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

...

<Grid>
    <Button x:Name="optionsButton">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <local:SetterAction PropertyName="Visibility" Value="Collapsed" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="Visible" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Visible" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <glyphs:Hamburger Width="10" Height="10" />
    </Button>

    <Button x:Name="optionsBackButton" Visibility="Collapsed">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <local:SetterAction PropertyName="Visibility" Value="Collapsed" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsButton}" Value="Visible" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Collapsed" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <glyphs:Back Width="12" Height="11" />
    </Button>
</Grid>

...

<Grid Grid.RowSpan="2" x:Name="optionsPanel" Visibility="Collapsed">

</Grid>

You can also specify values this way like in Neutrino's solution:

<Button x:Name="optionsButton">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <local:SetterAction PropertyName="Visibility" Value="{x:Static Visibility.Collapsed}" />
            <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="{x:Static Visibility.Visible}" />
            <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="{x:Static Visibility.Visible}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <glyphs:Hamburger Width="10" Height="10" />
</Button>

And here's the code.

using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;

namespace Mvvm.Actions
{
    /// <summary>
    /// Sets a specified property to a value when invoked.
    /// </summary>
    public class SetterAction : TargetedTriggerAction<FrameworkElement>
    {
        #region Properties

        #region PropertyName

        /// <summary>
        /// Property that is being set by this setter.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty =
            DependencyProperty.Register("PropertyName", typeof(string), typeof(SetterAction),
            new PropertyMetadata(String.Empty));

        #endregion

        #region Value

        /// <summary>
        /// Property value that is being set by this setter.
        /// </summary>
        public object Value
        {
            get { return (object)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(SetterAction),
            new PropertyMetadata(null));

        #endregion

        #endregion

        #region Overrides

        protected override void Invoke(object parameter)
        {
            var target = TargetObject ?? AssociatedObject;

            var targetType = target.GetType();

            var property = targetType.GetProperty(PropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
            if (property == null)
                throw new ArgumentException(String.Format("Property not found: {0}", PropertyName));

            if (property.CanWrite == false)
                throw new ArgumentException(String.Format("Property is not settable: {0}", PropertyName));

            object convertedValue;

            if (Value == null)
                convertedValue = null;

            else
            {
                var valueType = Value.GetType();
                var propertyType = property.PropertyType;

                if (valueType == propertyType)
                    convertedValue = Value;

                else
                {
                    var propertyConverter = TypeDescriptor.GetConverter(propertyType);

                    if (propertyConverter.CanConvertFrom(valueType))
                        convertedValue = propertyConverter.ConvertFrom(Value);

                    else if (valueType.IsSubclassOf(propertyType))
                        convertedValue = Value;

                    else
                        throw new ArgumentException(String.Format("Cannot convert type '{0}' to '{1}'.", valueType, propertyType));
                }
            }

            property.SetValue(target, convertedValue);
        }

        #endregion
    }
}

100% Min Height CSS layout

kleolb02's answer looks pretty good. another way would be a combination of the sticky footer and the min-height hack

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Just delete the user related data from mysql.db(maybe from other tables too), then recreate both.

Jackson JSON: get node name from json-tree

This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera's answer for a version that works with newer versions of Jackson.


The JSON terms for "node name" is "key." Since JsonNode#iterator() does not include keys, you need to iterate differently:

for (Map.Entry<String, JsonNode> elt : rootNode.fields())
{
    if ("foo".equals(elt.getKey()))
    {
        // bar
    }
}

If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames():

for (String key : rootNode.fieldNames())
{
    if ("foo".equals(key))
    {
        // bar
    }
}

And if you just want to find the node with key "foo", you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:

JsonNode foo = rootNode.get("foo");
if (foo != null)
{
    // frob that widget
}

C# How do I click a button by hitting Enter whilst textbox has focus?

The usual way to do this is to set the Form's AcceptButton to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton can be changed at any time.

This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus events for different TextBoxes on my form to enable different behavior based on where the user hit Enter. For example:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

One thing to be careful of when using this method is that you don't leave the AcceptButton set to ProcessTextBox1 when TextBox3 becomes focused. I would recommend using either the LostFocus event on the TextBoxes that set the AcceptButton, or create a GotFocus method that all of the controls that don't use a specific AcceptButton call.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


Reverse each individual word of "Hello World" string with Java

Well I'm a C/C++ guy, practicing java for interviews let me know if something can be changed or bettered. The following allows for multiple spaces and newlines.

First one is using StringBuilder

public static String reverse(String str_words){
    StringBuilder sb_result = new StringBuilder(str_words.length());
    StringBuilder sb_tmp = new StringBuilder();
    char c_tmp;
    for(int i = 0; i < str_words.length(); i++){
        c_tmp = str_words.charAt(i);    
        if(c_tmp == ' ' || c_tmp == '\n'){
            if(sb_tmp.length() != 0){   
                sb_tmp.reverse();
                sb_result.append(sb_tmp);
                sb_tmp.setLength(0);
            }   
            sb_result.append(c_tmp);
        }else{
            sb_tmp.append(c_tmp);
        }
    } 
    if(sb_tmp.length() != 0){
        sb_tmp.reverse();
        sb_result.append(sb_tmp);
    }
    return sb_result.toString();
}

This one is using char[]. I think its more efficient...

public static String reverse(String str_words){
    char[] c_array = str_words.toCharArray();
    int pos_start = 0;
    int pos_end;
    char c, c_tmp; 
    int i, j, rev_length;
    for(i = 0; i < c_array.length; i++){
        c = c_array[i];
        if( c == ' ' || c == '\n'){
            if(pos_start != i){ 
                pos_end = i-1;
                rev_length = (i-pos_start)/2;
                for(j = 0; j < rev_length; j++){
                    c_tmp = c_array[pos_start+j];
                    c_array[pos_start+j] = c_array[pos_end-j];
                    c_array[pos_end-j] = c_tmp;
                }
            }
            pos_start = i+1;
        }
    }
    //redundant, if only java had '\0' @ end of string
    if(pos_start != i){
        pos_end = i-1;
        rev_length = (i-pos_start)/2;
        for(j = 0; j < rev_length; j++){
            c_tmp = c_array[pos_start+j];
            c_array[pos_start+j] = c_array[pos_end-j];
            c_array[pos_end-j] = c_tmp;
        }
    }   
    return new String(c_array);
}

How to list the certificates stored in a PKCS12 keystore with keytool?

If the keystore is PKCS12 type (.pfx) you have to specify it with -storetype PKCS12 (line breaks added for readability):

keytool -list -v -keystore <path to keystore.pfx> \
    -storepass <password> \
    -storetype PKCS12

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

What does if __name__ == "__main__": do?

There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:

When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all of the methods and functions defined in the file, but it does define them.)

Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.

If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value "__main__".

If this is being imported from another module, __name__ will be set to that module's name.

So, in your example in part:

if __name__ == "__main__":
   lock = thread.allocate_lock()
   thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
   thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

means that the code block:

lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to "main" in that particular instance.

Hope this helps out.

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

Why is IoC / DI not common in Python?

pytest fixtures all based on DI (source)

How to fix SSL certificate error when running Npm on Windows?

set the below property:

"npm config set strict-ssl false"

How to generate all permutations of a list?

Regular implementation (no yield - will do everything in memory):

def getPermutations(array):
    if len(array) == 1:
        return [array]
    permutations = []
    for i in range(len(array)): 
        # get all perm's of subarray w/o current item
        perms = getPermutations(array[:i] + array[i+1:])  
        for p in perms:
            permutations.append([array[i], *p])
    return permutations

Yield implementation:

def getPermutations(array):
    if len(array) == 1:
        yield array
    else:
        for i in range(len(array)):
            perms = getPermutations(array[:i] + array[i+1:])
            for p in perms:
                yield [array[i], *p]

The basic idea is to go over all the elements in the array for the 1st position, and then in 2nd position go over all the rest of the elements without the chosen element for the 1st, etc. You can do this with recursion, where the stop criteria is getting to an array of 1 element - in which case you return that array.

enter image description here

Conditional Formatting (IF not empty)

An equivalent result, "other things being equal", would be to format all cells grey and then use Go To Special to select the blank cells prior to removing their grey highlighting.

How do you get git to always pull from a specific branch?

If you prefer, you can set these options via the commmand line (instead of editing the config file) like so:

  $ git config branch.master.remote origin
  $ git config branch.master.merge refs/heads/master

Or, if you're like me, and want this to be the default across all of your projects, including those you might work on in the future, then add it as a global config setting:

  $ git config --global branch.master.remote origin
  $ git config --global branch.master.merge refs/heads/master

Twitter Bootstrap modal: How to remove Slide down effect

you can also overwrite bootstrap.css by simply removing "top:-25%;"

once removed, the modal will simply fade in and out without the slide animation.

Environment variable substitution in sed

You can use other characters besides "/" in substitution:

sed "s#$1#$2#g" -i FILE

convert from Color to brush

This is for Color to Brush....

you can't convert it, you have to make a new brush....

SolidColorBrush brush = new SolidColorBrush( myColor );

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

Query to count the number of tables I have in MySQL

Hope this helps, and returns only number of tables in a database

Use database;

SELECT COUNT(*) FROM sys.tables;

How to detect if URL has changed after hash in JavaScript

window.addEventListener("beforeunload", function (e) {
    // do something
}, false);

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

What are database normal forms and can you give examples?

1NF: Only one value per column

2NF: All the non primary key columns in the table should depend on the entire primary key.

3NF: All the non primary key columns in the table should depend DIRECTLY on the entire primary key.

I have written an article in more detail over here

"inappropriate ioctl for device"

I tried the following code that seemed to work:

if(open(my $FILE, "<File.txt")) {
    while(<$FILE>){
    print "$_";}
} else {
    print "File could not be opened or did not exists\n";
}

reading text file with utf-8 encoding using java

Ok, I am definitively late to the party but if you are still looking for an optimal solution I would use the following ( for Java 8 )

    Charset inputCharset = Charset.forName("ISO-8859-1");
    Path pathToFile = ....
    try (BufferedReader br = Files.newBufferedReader( pathToFile, inputCharset )) {
        ...
     }

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

How do I convert a file path to a URL in ASP.NET

This worked for me:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "ImageName";

How can I check what version/edition of Visual Studio is installed programmatically?

Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Zero an array in C code

int arr[20];
memset(arr, 0, sizeof arr);

See the reference for memset

Twitter Bootstrap vs jQuery UI?

I have on several projects.

The biggest difference in my opinion

  • jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old

  • Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding

  • jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)

So what to choose?

That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?

I always end up using both, so I can use the best of both worlds.

Here are the links to both frameworks, if you decide to use them.

  1. jQuery UI
  2. Bootstrap

apc vs eaccelerator vs xcache

APC segfaults all day and all night, got no experience with eAccelerator but XCache is very reliable with loads of options and constant development.

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Replace

 var myNewString = myOldString.replace ("username," visitorName);

with

 var myNewString = myOldString.replace("username", visitorName);

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

As shown below, range only supports integers:

>>> range(15.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

However, c/10 is a float because / always returns a float.

Before you put it in range, you need to make c/10 an integer. This can be done by putting it in int:

range(int(c/10))

or by using //, which returns an integer:

range(c//10)

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

Manually adding a Userscript to Google Chrome

This parameter is is working for me:

--enable-easy-off-store-extension-install

Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

How to update ruby on linux (ubuntu)?

The author of this article claims that it would be best to avoid installing Ruby from the local packet manager, but to use RVM instead.

You can easily switch between different Ruby versions:

rvm use 1.9.3

etc.

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

Disable Enable Trigger SQL server for a table

The line before needs to end with a ; because in SQL DISABLE is not a keyword. For example:

BEGIN
;
DISABLE TRIGGER ...

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Display the binary representation of a number in C?

There is no direct way (i.e. using printf or another standard library function) to print it. You will have to write your own function.

/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
   for (; v; v >>= 1) putchar('0' + (v & 1));
}

If you're using terminal, you can use control codes to print out bytes in natural order:

void printbits(unsigned char v) {
    printf("%*s", (int)ceil(log2(v)) + 1, ""); 
    for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

Moment Js UTC to Local Time

To convert UTC to local time

let UTC = moment.utc()
let local = moment(UTC).local()

Or you want directly get the local time

let local = moment()

_x000D_
_x000D_
var UTC = moment.utc()_x000D_
console.log(UTC.format()); // UTC time_x000D_
_x000D_
var cLocal = UTC.local()_x000D_
console.log(cLocal.format()); // Convert UTC time_x000D_
_x000D_
var local = moment();_x000D_
console.log(local.format()); // Local time
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

How to submit an HTML form without redirection

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

Getting each individual digit from a whole integer

Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.

SQL Server : SUM() of multiple rows including where clauses

The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

BULK INSERT with identity (auto-increment) column

This is a very old post to answer, but none of the answers given solves the problem without changing the posed conditions, which I can't do.

I solved it by using the OPENROWSET variant of BULK INSERT. This uses the same format file and works in the same way, but it allows the data file be read with a SELECT statement.

Create your table:

CREATE TABLE target_table(
id bigint IDENTITY(1,1),
col1 varchar(256) NULL,
col2 varchar(256) NULL,
col3 varchar(256) NULL)

Open a command window an run:

bcp dbname.dbo.target_table format nul -c -x -f C:\format_file.xml -t; -T

This creates the format file based on how the table looks.

Now edit the format file and remove the entire rows where FIELD ID="1" and COLUMN SOURCE="1", since this does not exist in our data file.
Also adjust terminators as may be needed for your data file:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
 </RECORD>
 <ROW>
  <COLUMN SOURCE="2" NAME="col1" xsi:type="SQLVARYCHAR"/>
  <COLUMN SOURCE="3" NAME="col2" xsi:type="SQLVARYCHAR"/>
  <COLUMN SOURCE="4" NAME="col3" xsi:type="SQLVARYCHAR"/>
 </ROW>
</BCPFORMAT>

Now we can bulk load the data file into our table with a select, thus having full controll over the columns, in this case by not inserting data into the identity column:

INSERT INTO target_table (col1,col2, col3)
SELECT * FROM  openrowset(
bulk 'C:\data_file.txt',
formatfile='C:\format_file.xml') as t;

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

Clearing all cookies with JavaScript

Here's a simple code to delete all cookies in JavaScript.

function deleteAllCookies(){
   var cookies = document.cookie.split(";");
   for (var i = 0; i < cookies.length; i++)
     deleteCookie(cookies[i].split("=")[0]);
}

function setCookie(name, value, expirydays) {
 var d = new Date();
 d.setTime(d.getTime() + (expirydays*24*60*60*1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie = name + "=" + value + "; " + expires;
}

function deleteCookie(name){
  setCookie(name,"",-1);
}

Run the function deleteAllCookies() to clear all cookies.

Pass user defined environment variable to tomcat

Environment Entries specified by <Environment> markup are JNDI, accessible using InitialContext.lookup under java:/comp/env. You can specify environment properties to the JNDI by using the environment parameter to the InitialContext constructor and application resource files.

System.getEnv() is about system environment variables of the tomcat process itself.

To set an environment variable using bash command : export TOMCAT_OPTS=-Dmy.bar=foo and start the Tomcat : ./startup.sh To retrieve the value of System property bar use System.getProperty(). System.getEnv() can be used to retrieve the environment variable i.e. TOMCAT_OPTS.

Most efficient way to find mode in numpy array

If you want to use numpy only:

x = [-1, 2, 1, 3, 3]
vals,counts = np.unique(x, return_counts=True)

gives

(array([-1,  1,  2,  3]), array([1, 1, 1, 2]))

And extract it:

index = np.argmax(counts)
return vals[index]

How to find which views are using a certain table in SQL Server (2008)?

If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

enter image description here

enter image description here

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

Run a PHP file in a cron job using CPanel

This cron line worked for me on hostgator VPS using cpanel.

/usr/bin/php -q /home/username/public_html/scriptname.php

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

ADB Shell Input Events

One other difference:

  • "adb shell input" is calling the input.jar to process and send the keycode from the Java layer of the android framework.
  • "adb sendevent" is actually c code (part of toolbox utility ) that sends the input code directly into the /dev/input.... of Linux input subsystem.

More detail code trace into inside AOSP Framework can be found here:

http://www.srcmap.org/sd_share/4/aba57bc6/AOSP_adb_shell_input_Code_Trace.html#RefId=7c8f5285

REST API - Use the "Accept: application/json" HTTP Header

Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement

from your model class and than run the same url, you have used for xml representation.

Make sure that you have jacson-databind dependency in your pom.xml

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1</version>
</dependency>

javascript find and remove object in array based on key value

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

If you are using jQuery, use jQuery.grep like this:

items = $.grep(items, function(item) { 
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

Using ES5 Array.prototype.filter:

items = items.filter(function(item) { 
  return item.id !== '88'; 
});
// items => [{ id: "99" }, { id: "108" }]

Image inside div has extra space below the image

I found it works great using display:block; on the image and vertical-align:top; on the text.

_x000D_
_x000D_
.imagebox {_x000D_
    width:200px;_x000D_
    float:left;_x000D_
    height:88px;_x000D_
    position:relative;_x000D_
    background-color: #999;_x000D_
}_x000D_
.container {_x000D_
    width:600px;_x000D_
    height:176px;_x000D_
    background-color: #666;_x000D_
    position:relative;_x000D_
    overflow:hidden;_x000D_
}_x000D_
.text {_x000D_
    color: #000;_x000D_
    font-size: 11px;_x000D_
    font-family: robotomeduim, sans-serif;_x000D_
    vertical-align:top;_x000D_
    _x000D_
}_x000D_
_x000D_
.imagebox img{ display:block;}
_x000D_
<div class="container">_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or you can edit the code a JS FIDDLE

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

How to pass table value parameters to stored procedure from .net code

The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

Create this extension method...

public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
   if(paramCollection != null)
   {
       var p = paramCollection.Add(parameterName, SqlDbType.Structured);
       p.TypeName = "dbo.tvp_Int";
       DataTable _dt = new DataTable() {Columns = {"Value"}};
       data.ForEach(value => _dt.Rows.Add(value));
       p.Value = _dt;
   }
}

Now you can add a table valued parameter in one line anywhere simply by doing this:

cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);

Asp.net Validation of viewstate MAC failed

This error message is normally displayed after you have published your website to the server.

The main problem lies in the Application Pool you use for your website.

Configure your website to use the proper .NET Framework version (i.e. v4.0) under the General section of the Application Pool related to your website.

Under the Process Model, set the Identity value to Network Service.

Close the dialog box and right-click your website and select Advanced Settings... from the Manage Website option of the content menu. In the dialog box, under General section, make sure you have selected the proper name of the Application Pool to be used.

Your website should now run without any problem.

Hope this helps you overcome this error.

How To limit the number of characters in JTextField?

If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:

public class JTextFieldLimit extends JTextField {
    private int limit;

    public JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    protected Document createDefaultModel() {
        return new LimitDocument();
    }

    private class LimitDocument extends PlainDocument {

        @Override
        public void insertString( int offset, String  str, AttributeSet attr ) throws BadLocationException {
            if (str == null) return;

            if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);
            }
        }       

    }

}

Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.

Loading cross-domain endpoint with AJAX

Your URL doesn't work these days, but your code can be updated with this working solution:

_x000D_
_x000D_
var url = "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute";_x000D_
_x000D_
url = 'https://google.com'; // TEST URL_x000D_
_x000D_
$.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=" + encodeURI(url), function(data) {_x000D_
    $('div.ajax-field').html(data);_x000D_
});
_x000D_
<div class="ajax-field"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

how to open a url in python

import webbrowser  
webbrowser.open(url, new=0, autoraise=True)

Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised

webbrowser.open_new(url)

Open url in a new window of the default browser

webbrowser.open_new_tab(url)

Open url in a new page (“tab”) of the default browser

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

How to set the timezone in Django?

Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:

Area is a continent or ocean name. Area currently includes:

  • Africa
  • America (both North America and South America)
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Etc (administrative zone. For example, “Etc/UTC” represents Coordinated Universal Time.)
  • Indian
  • Pacific

Location is the city, island, or other regional name.

The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).

Here is a list all valid timezones

You can change time zone in your settings.py as follows

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

How to enable relation view in phpmyadmin

first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab) enter image description here

if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation

enter image description here

if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns

enter image description here

How do I get the last four characters from a string in C#?

You can use an extension method:

public static class StringExtension
{
    public static string GetLast(this string source, int tail_length)
    {
       if(tail_length >= source.Length)
          return source;
       return source.Substring(source.Length - tail_length);
    }
}

And then call:

string mystring = "34234234d124";
string res = mystring.GetLast(4);

GitHub Error Message - Permission denied (publickey)

Issue solved if you change the ssh access to https access to the remote repository:

git remote set-url origin https_link_to_repository

git push -u origin master

How to load GIF image in Swift?

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)

    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as! Double

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    for i in 0..<count {
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}

Here is the file updated for Swift 3

Pandas: change data type of Series to String

You can use:

df.loc[:,'id'] = df.loc[:, 'id'].astype(str)

This is why they recommend this solution: Pandas doc

TD;LR

To reflect some of the answers:

df['id'] = df['id'].astype("string")

This will break on the given example because it will try to convert to StringArray which can not handle any number in the 'string'.

df['id']= df['id'].astype(str)

For me this solution throw some warning:

> SettingWithCopyWarning:  
> A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

Android open camera from button

You are correct about the action used in Intent but it's not the only thing you have to do. You'll also have to add

startActivityForResult(intent, YOUR_REQUEST_CODE);

To get it all done and retrieve the actual picture you could check the following thread.

Android - Capture photo

HTML Input="file" Accept Attribute File Type (CSV)

Now you can use new html5 input validation attribute pattern=".+\.(xlsx|xls|csv)".

Could someone explain this for me - for (int i = 0; i < 8; i++)

it's the same as think the next:

"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"

It's also the same as:

while( i < 8 )
{
    // instrucctions like:
    Console.WriteLine(i);
    i++;
}

the For sentences is a basis of coding, and it's as useful as necessary its understanding.

It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array

What is the mouse down selector in CSS?

I think you mean the active state

 button:active{
  //some styling
 }

These are all the possible pseudo states a link can have in CSS:

a:link {color:#FF0000;}    /* unvisited link, same as regular 'a' */
a:hover {color:#FF00FF;}   /* mouse over link */
a:focus {color:#0000FF;}   /* link has focus */
a:active {color:#0000FF;}  /* selected link */
a:visited {color:#00FF00;} /* visited link */

See also: http://www.w3.org/TR/selectors/#the-user-action-pseudo-classes-hover-act

How to copy a row from one SQL Server table to another

Alternative syntax:

INSERT tbl (Col1, Col2, ..., ColN)
  SELECT Col1, Col2, ..., ColN
  FROM Tbl2
  WHERE ...

The select query can (of course) include expressions, case statements, constants/literals, etc.

WPF global exception handler

You can trap unhandled exceptions at different levels:

  1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.

You should consider what level you need to trap unhandled exceptions at.

Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

View JSON file in Browser

json-ie.reg. for IE

try this url

http://www.jsonviewer.com/

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

What is the regex for "Any positive integer, excluding 0"

Sorry to come in late but the OP wants to allow 076 but probably does NOT want to allow 0000000000.

So in this case we want a string of one or more digits containing at least one non-zero. That is

^[0-9]*[1-9][0-9]*$

How to search file text for a pattern and replace it with a given value

Keep in mind that, when you do this, the filesystem could be out of space and you may create a zero-length file. This is catastrophic if you're doing something like writing out /etc/passwd files as part of system configuration management.

Note that in-place file editing like in the accepted answer will always truncate the file and write out the new file sequentially. There will always be a race condition where concurrent readers will see a truncated file. If the process is aborted for any reason (ctrl-c, OOM killer, system crash, power outage, etc) during the write then the truncated file will also be left over, which can be catastrophic. This is the kind of dataloss scenario which developers MUST consider because it will happen. For that reason, I think the accepted answer should most likely not be the accepted answer. At a bare minimum write to a tempfile and move/rename the file into place like the "simple" solution at the end of this answer.

You need to use an algorithm that:

  1. Reads the old file and writes out to the new file. (You need to be careful about slurping entire files into memory).

  2. Explicitly closes the new temporary file, which is where you may throw an exception because the file buffers cannot be written to disk because there is no space. (Catch this and cleanup the temporary file if you like, but you need to rethrow something or fail fairly hard at this point.

  3. Fixes the file permissions and modes on the new file.

  4. Renames the new file and drops it into place.

With ext3 filesystems you are guaranteed that the metadata write to move the file into place will not get rearranged by the filesystem and written before the data buffers for the new file are written, so this should either succeed or fail. The ext4 filesystem has also been patched to support this kind of behavior. If you are very paranoid you should call the fdatasync() system call as a step 3.5 before moving the file into place.

Regardless of language, this is best practice. In languages where calling close() does not throw an exception (Perl or C) you must explicitly check the return of close() and throw an exception if it fails.

The suggestion above to simply slurp the file into memory, manipulate it and write it out to the file will be guaranteed to produce zero-length files on a full filesystem. You need to always use FileUtils.mv to move a fully-written temporary file into place.

A final consideration is the placement of the temporary file. If you open a file in /tmp then you have to consider a few problems:

  • If /tmp is mounted on a different file system you may run /tmp out of space before you've written out the file that would otherwise be deployable to the destination of the old file.

  • Probably more importantly, when you try to mv the file across a device mount you will transparently get converted to cp behavior. The old file will be opened, the old files inode will be preserved and reopened and the file contents will be copied. This is most likely not what you want, and you may run into "text file busy" errors if you try to edit the contents of a running file. This also defeats the purpose of using the filesystem mv commands and you may run the destination filesystem out of space with only a partially written file.

    This also has nothing to do with Ruby's implementation. The system mv and cp commands behave similarly.

What is more preferable is to open a Tempfile in the same directory as the old file. This ensures that there will be no cross-device move issues. The mv itself should never fail, and you should always get a complete and untruncated file. Any failures, such as device out of space, permission errors, etc., should be encountered during writing the Tempfile out.

The only downsides to the approach of creating the Tempfile in the destination directory are:

  • Sometimes you may not be able to open a Tempfile there, such as if you are trying to 'edit' a file in /proc for example. For that reason you might want to fall back and try /tmp if opening the file in the destination directory fails.
  • You must have enough space on the destination partition in order to hold both the complete old file and the new file. However, if you have insufficient space to hold both copies then you are probably short on disk space and the actual risk of writing a truncated file is much higher, so I would argue this is a very poor tradeoff outside of some exceedingly narrow (and well-monitored) edge cases.

Here's some code that implements the full-algorithm (windows code is untested and unfinished):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  tempdir = File.dirname(filename)
  tempprefix = File.basename(filename)
  tempprefix.prepend('.') unless RUBY_PLATFORM =~ /mswin|mingw|windows/
  tempfile =
    begin
      Tempfile.new(tempprefix, tempdir)
    rescue
      Tempfile.new(tempprefix)
    end
  File.open(filename).each do |line|
    tempfile.puts line.gsub(regexp, replacement)
  end
  tempfile.fdatasync unless RUBY_PLATFORM =~ /mswin|mingw|windows/
  tempfile.close
  unless RUBY_PLATFORM =~ /mswin|mingw|windows/
    stat = File.stat(filename)
    FileUtils.chown stat.uid, stat.gid, tempfile.path
    FileUtils.chmod stat.mode, tempfile.path
  else
    # FIXME: apply perms on windows
  end
  FileUtils.mv tempfile.path, filename
end

file_edit('/tmp/foo', /foo/, "baz")

And here is a slightly tighter version that doesn't worry about every possible edge case (if you are on Unix and don't care about writing to /proc):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
    File.open(filename).each do |line|
      tempfile.puts line.gsub(regexp, replacement)
    end
    tempfile.fdatasync
    tempfile.close
    stat = File.stat(filename)
    FileUtils.chown stat.uid, stat.gid, tempfile.path
    FileUtils.chmod stat.mode, tempfile.path
    FileUtils.mv tempfile.path, filename
  end
end

file_edit('/tmp/foo', /foo/, "baz")

The really simple use-case, for when you don't care about file system permissions (either you're not running as root, or you're running as root and the file is root owned):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
    File.open(filename).each do |line|
      tempfile.puts line.gsub(regexp, replacement)
    end
    tempfile.close
    FileUtils.mv tempfile.path, filename
  end
end

file_edit('/tmp/foo', /foo/, "baz")

TL;DR: That should be used instead of the accepted answer at a minimum, in all cases, in order to ensure the update is atomic and concurrent readers will not see truncated files. As I mentioned above, creating the Tempfile in the same directory as the edited file is important here to avoid cross device mv operations being translated into cp operations if /tmp is mounted on a different device. Calling fdatasync is an added layer of paranoia, but it will incur a performance hit, so I omitted it from this example since it is not commonly practiced.

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

Counter increment in Bash loop not working

minimalist

counter=0
((counter++))
echo $counter

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

Drop data frame columns by name

You can use a simple list of names :

DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
drops <- c("x","z")
DF[ , !(names(DF) %in% drops)]

Or, alternatively, you can make a list of those to keep and refer to them by name :

keeps <- c("y", "a")
DF[keeps]

EDIT : For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:

keeps <- "y"
DF[ , keeps, drop = FALSE]

drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

package javax.mail and javax.mail.internet do not exist

You need the javax.mail.jar library. Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:

  1. Download javax.mail.jar
  2. Navigate to File > Project Structure...
  3. Go to the Libraries tab
  4. Click on the + button (Add New Project Library)
  5. Browse to the javax.mail.jar file
  6. Click OK to apply the changes

Full Screen Theme for AppCompat

This theme only works after API 21(included). And make both the StatusBar and NavigationBar transparent.

<style name="TransparentAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <item name="windowActionBar">false</item>
  <item name="windowNoTitle">true</item>
  <item name="android:statusBarColor">@android:color/transparent</item>
  <item name="android:windowBackground">@android:color/transparent</item>
  <item name="android:navigationBarColor">@android:color/transparent</item>
  <item name="android:windowIsTranslucent">true</item>
  <item name="android:windowContentOverlay">@null</item>
</style>

Location of hibernate.cfg.xml in project?

This is an reality example when customize folder structure: Folder structure, and initialize class HibernateUtil

enter image description here

with:

return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();

mapping: enter image description here


with customize entities mapping files:

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping class="com.vy.entities.Users"/>
        <mapping class="com.vy.entities.Post"/>
        <mapping resource="config/Users.hbm.xml"/>      
        <mapping resource="config/Post.hbm.xml"/>               
    </session-factory>
</hibernate-configuration>

(Note: Simplest way, if you follow default way, it means put all xml config files inside src folder, when build sessionFactory, only:

return new Configuration().configure().buildSessionFactory();

)

How to get the connection String from a database

My solution was to use (2010).

In a new worksheet, select a cell, then:

Data -> From Other Sources -> From SQL Server 

put in the server name, select table, etc,

When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.

And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)

Parsing JSON using C

You can have a look at Jansson

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:

  • Simple and intuitive API and data model
  • Can both encode to and decode from JSON
  • Comprehensive documentation
  • No dependencies on other libraries
  • Full Unicode support (UTF-8)
  • Extensive test suite

Object spread vs. Object.assign

As others have mentioned, at this moment of writing, Object.assign() requires a polyfill and object spread ... requires some transpiling (and perhaps a polyfill too) in order to work.

Consider this code:

// Babel wont touch this really, it will simply fail if Object.assign() is not supported in browser.
const objAss = { message: 'Hello you!' };
const newObjAss = Object.assign(objAss, { dev: true });
console.log(newObjAss);

// Babel will transpile with use to a helper function that first attempts to use Object.assign() and then falls back.
const objSpread = { message: 'Hello you!' };
const newObjSpread = {...objSpread, dev: true };
console.log(newObjSpread);

These both produce the same output.

Here is the output from Babel, to ES5:

var objAss = { message: 'Hello you!' };
var newObjAss = Object.assign(objAss, { dev: true });
console.log(newObjAss);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var objSpread = { message: 'Hello you!' };
var newObjSpread = _extends({}, objSpread, { dev: true });
console.log(newObjSpread);

This is my understanding so far. Object.assign() is actually standardised, where as object spread ... is not yet. The only problem is browser support for the former and in future, the latter too.

Play with the code here

Hope this helps.

What is a daemon thread in Java?

A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.

When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.

You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops.

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

Remove last item from array

If you want to remove n item from end of array in javascript, you can easily use:

arr.splice(-n, n);

Convert RGBA PNG to RGB with PIL

The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.

Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.

You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:

import Image
import numpy as np

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')

enter image description here


Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.

A better quality result could be made using imagemagick's convert command:

convert logo.png -background white -flatten /tmp/out.jpg

enter image description here


To make a nicer quality blend using numpy, you could use alpha compositing:

import Image
import numpy as np

def alpha_composite(src, dst):
    '''
    Return the alpha composite of src and dst.

    Parameters:
    src -- PIL RGBA Image object
    dst -- PIL RGBA Image object

    The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
    '''
    # http://stackoverflow.com/a/3375291/190597
    # http://stackoverflow.com/a/9166671/190597
    src = np.asarray(src)
    dst = np.asarray(dst)
    out = np.empty(src.shape, dtype = 'float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    src_a = src[alpha]/255.0
    dst_a = dst[alpha]/255.0
    out[alpha] = src_a+dst_a*(1-src_a)
    old_setting = np.seterr(invalid = 'ignore')
    out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
    np.seterr(**old_setting)    
    out[alpha] *= 255
    np.clip(out,0,255)
    # astype('uint8') maps np.nan (and np.inf) to 0
    out = out.astype('uint8')
    out = Image.fromarray(out, 'RGBA')
    return out            

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')

enter image description here

Where is the Keytool application?

keytool is part of the standard java distribution.

In a windows 64-bit machine, you would normally find the jdk at

C:\Program Files\Java\jdk1.8.0_121\bin

It is used for managing keys and certificates you can sign things with, in your case, probably a jar file.

If you provide more details of what you need to do, we could probably give you a more specific answer.

jQuery find and replace string

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

Git for beginners: The definitive practical guide

I found this post to be very useful to get me started. I still need to read the book and other resources but the post was helpful in, as the title says, "understanding git conceptually". I also recommend taking the Git & GitHub course offered at RubyLearning.

Check if int is between two numbers

You are human, and therefore you understand what the term "10 < x < 20" suppose to mean. The computer doesn't have this intuition, so it reads it as: "(10 < x) < 20".

For example, if x = 15, it will calculate:

(10 < x) => TRUE

"TRUE < 20" => ???

In C programming, it will be worse, since there are no True\False values. If x = 5, the calculation will be:

10 < x => 0 (the value of False)

0 < 20 => non-0 number (True)

and therefore "10 < 5 < 20" will return True! :S

Convert timestamp to date in MySQL query

Convert timestamp to date in MYSQL

Make the table with an integer timestamp:

mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)

Insert some values

mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)

Take a look

mysql> select * from foo;
+------+-------------+
| id   | mytimestamp |
+------+-------------+
|    1 |  1381262848 |
+------+-------------+
1 row in set (0.00 sec)

Convert the number to a timestamp:

mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id   | from_unixtime(mytimestamp) |
+------+----------------------------+
|    1 | 2013-10-08 16:07:28        |
+------+----------------------------+
1 row in set (0.00 sec)

Convert it into a readable format:

mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id   | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
|    1 | 2013 8th October 04:07:28                       |
+------+-------------------------------------------------+
1 row in set (0.00 sec)

Print text in Oracle SQL Developer SQL Worksheet window

You could set echo to on:

set echo on
REM Querying table
select * from dual;

In SQLDeveloper, hit F5 to run as a script.

Reverse HashMap keys and values in Java

Iterate through the list of keys and values, then add them.

HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
    reversedHashMap.put(myHashMap.get(key), key);
}

How do I write a Windows batch script to copy the newest file from a directory?

This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.

Obviously, replace new_file_loc with whatever your new file location will be.

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0

Cannot use object of type stdClass as array?

When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context

How to get system time in Java without creating a new Date

Use System.currentTimeMillis() or System.nanoTime().

React JSX: selecting "selected" on selected <select> option

React makes this even easier for you. Instead of defining selected on each option, you can (and should) simply write value={optionsState} on the select tag itself:

<select value={optionsState}>
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

For more info, see the React select tag doc.

Also, React automatically understands booleans for this purpose, so you can simply write (note: not recommended)

<option value={option.value} selected={optionsState == option.value}>{option.label}</option>

and it will output 'selected' appropriately.

node.js require() cache - possible to invalidate?

If it's for unit tests, another good tool to use is proxyquire. Everytime you proxyquire the module, it will invalidate the module cache and cache a new one. It also allows you to modify the modules required by the file that you are testing.

Get Month name from month number

You can get this in following way,

DateTimeFormatInfo mfi = new DateTimeFormatInfo();
string strMonthName = mfi.GetMonthName(8).ToString(); //August

Now, get first three characters

string shortMonthName = strMonthName.Substring(0, 3); //Aug

I am not able launch JNLP applications using "Java Web Start"?

I know this is an older question but this past week I started to get a similar problem, so I leave here some notes regarding the solution that fits me.

This happened only in some Windows machines using even the last JRE to date (1.8.0_45).

The Java Web Start started to load but nothing happened and none of the previous solution attempts worked.

After some digging i've found this thread, which gives the same setup and a great explanation.

https://community.oracle.com/thread/3676876

So, in conclusion, it was a memory problem in x86 JRE and since our JNLP's max heap was defined as 1024MB, we changed to 780MB as suggested and it was fixed.

However, if you need more than 780MB, can always try launching in a x64 JRE version.

Set HTML element's style property in javascript

You can set the style attribute of any element... the trick is that in IE you have to do it differently. (bug 245)

//Standards base browsers
elem.setAttribute('style', styleString);

//Non Standards based IE browser
elem.style.setAttribute('cssText', styleString);

Note that in IE8, in Standards Mode, the first way does work.

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

if you need to add a date-time to your backup file name (Centos7) use the following:

/usr/bin/mysqldump -u USER -pPASSWD DBNAME | gzip > ~/backups/db.$(date +%F.%H%M%S).sql.gz

this will create the file: db.2017-11-17.231537.sql.gz

Validation error: "No validator could be found for type: java.lang.Integer"

You can add hibernate validator dependency, to provide a Validator

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>

C compile error: Id returned 1 exit status

it could be that you just said main{....I use int main{ when I start my main.

Converting a Java Keystore into PEM Format

Converting a JKS KeyStore to a single PEM file can easily be accomplished using the following command:

keytool -list -rfc -keystore "myKeystore.jks" | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" >> "myKeystore.pem"

Explanation:

  1. keytool -list -rfc -keystore "myKeystore.jks" lists everything in the 'myKeyStore.jks' KeyStore in PEM format. However, it also prints extra information.
  2. | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" filters out everything we don't need. We are left with only the PEMs of everything in the KeyStore.
  3. >> "myKeystore.pem" write the PEMs to the file 'myKeyStore.pem'.

How to start MySQL server on windows xp

I was using MySQL Server 5.5 as a result I was missing the folder which majority of the answers made mention of in the bin folder. What I did instead was the following:

  1. Open Explorer and make your way to C:\Program Files\MySQL\MySQL Server 5.5\bin or your MySQL installation directory.
  2. Run the executable application MySQLInstanceConfig and follow the images below.

This solved my issue and I was able to access the database without any errors.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

What's the difference between passing by reference vs. passing by value?

Here is an example:

#include <iostream>

void by_val(int arg) { arg += 2; }
void by_ref(int&arg) { arg += 2; }

int main()
{
    int x = 0;
    by_val(x); std::cout << x << std::endl;  // prints 0
    by_ref(x); std::cout << x << std::endl;  // prints 2

    int y = 0;
    by_ref(y); std::cout << y << std::endl;  // prints 2
    by_val(y); std::cout << y << std::endl;  // prints 2
}

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

Why is Thread.Sleep so harmful

I agree with many here, but I also think it depends.

Recently I did this code:

private void animate(FlowLayoutPanel element, int start, int end)
{
    bool asc = end > start;
    element.Show();
    while (start != end) {
        start += asc ? 1 : -1;
        element.Height = start;
        Thread.Sleep(1);
    }
    if (!asc)
    {
        element.Hide();
    }
    element.Focus();
}

It was a simple animate-function, and I used Thread.Sleep on it.

My conclusion, if it does the job, use it.

regular expression for Indian mobile numbers

Swift 4

 - Mobile Number Validation [starting with 7,8,9]

     func validate(value: String) -> Bool {
                let PHONE_REGEX = "^[7-9][0-9]{9}$";
                let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
                let result =  phoneTest.evaluate(with: value)
                return result
            }

       if validate(value: value) {
                print("True")
            }

Differences between hard real-time, soft real-time, and firm real-time?

Hard Real-Time

The hard real-time definition considers any missed deadline to be a system failure. This scheduling is used extensively in mission critical systems where failure to conform to timing constraints results in a loss of life or property.

Examples:

  • Air France Flight 447 crashed into the ocean after a sensor malfunction caused a series of system errors. The pilots stalled the aircraft while responding to outdated instrument readings. All 12 crew and 216 passengers were killed.

  • Mars Pathfinder spacecraft was nearly lost when a priority inversion caused system restarts. A higher priority task was not completed on time due to being blocked by a lower priority task. The problem was corrected and the spacecraft landed successfully.

  • An Inkjet printer has a print head with control software for depositing the correct amount of ink onto a specific part of the paper. If a deadline is missed then the print job is ruined.


Firm Real-Time

The firm real-time definition allows for infrequently missed deadlines. In these applications the system can survive task failures so long as they are adequately spaced, however the value of the task's completion drops to zero or becomes impossible.

Examples:

  • Manufacturing systems with robot assembly lines where missing a deadline results in improperly assembling a part. As long as ruined parts are infrequent enough to be caught by quality control and not too costly, then production continues.

  • A digital cable set-top box decodes time stamps for when frames must appear on the screen. Since the frames are time order sensitive a missed deadline causes jitter, diminishing quality of service. If the missed frame later becomes available it will only cause more jitter to display it, so it's useless. The viewer can still enjoy the program if jitter doesn't occur too often.


Soft Real-Time

The soft real-time definition allows for frequently missed deadlines, and as long as tasks are timely executed their results continue to have value. Completed tasks may have increasing value up to the deadline and decreasing value past it.

Examples:

  • Weather stations have many sensors for reading temperature, humidity, wind speed, etc. The readings should be taken and transmitted at regular intervals, however the sensors are not synchronized. Even though a sensor reading may be early or late compared with the others it can still be relevant as long as it is close enough.

  • A video game console runs software for a game engine. There are many resources that must be shared between its tasks. At the same time tasks need to be completed according to the schedule for the game to play correctly. As long as tasks are being completely relatively on time the game will be enjoyable, and if not it may only lag a little.


Siewert: Real-Time Embedded Systems and Components.
Liu & Layland: Scheduling Algorithms for Multiprogramming in a Hard Real-Time Environment.
Marchand & Silly-Chetto: Dynamic Scheduling of Soft Aperiodic Tasks and Periodic Tasks with Skips.

Windows batch files: .bat vs .cmd?

a difference:

.cmd files are loaded into memory before being executed. .bat files execute a line, read the next line, execute that line...

you can come across this when you execute a script file and then edit it before it's done executing. bat files will be messed up by this, but cmd files won't.

How to convert a Binary String to a base 10 integer in Java

You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I'm afraid none of these solutions worked for me. Perhaps because I was using belongs_to in my create_table migration for a polymorphic association.

I'll add my code below and a link to the solution that helped me in case anyone else stumbles upon when searching for 'Index name is too long' in connection with polymorphic associations.

The following code did NOT work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true
    t.timestamps
  end
  add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end

This code DID work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }

    t.timestamps
  end
end

This is the SO Q&A that helped me out: https://stackoverflow.com/a/30366460/3258059

toggle show/hide div with button?

JavaScript - Toggle Element.styleMDN

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
  display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

About the ^ bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

JavaScript - Toggle .classList.toggle()

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.classList.toggle("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle

.toggle()Docs; .fadeToggle()Docs; .slideToggle()Docs

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
  display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle .toggleClass()Docs

.toggle() toggles an element's display "block"/"none" values

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

HTML5 - Toggle using <summary> and <details>

(unsupported on IE and Opera Mini)

_x000D_
_x000D_
<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>
_x000D_
_x000D_
_x000D_

HTML - Toggle using checkbox

_x000D_
_x000D_
[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
_x000D_
_x000D_

HTML - Switch using radio

_x000D_
_x000D_
[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_

CSS - Switch using :target

(just to make sure you have it in your arsenal)

_x000D_
_x000D_
[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_


Animating class transition

If you pick one of JS / jQuery way to actually toggle a className, you can always add animated transitions to your element, here's a basic example:

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function(){
  content.classList.toggle("appear");
}, false);
_x000D_
#content{
  /* DON'T USE DISPLAY NONE/BLOCK! Instead: */
  background: #cf5;
  padding: 10px;
  position: absolute;
  visibility: hidden;
  opacity: 0;
          transition: 0.6s;
  -webkit-transition: 0.6s;
          transform: translateX(-100%);
  -webkit-transform: translateX(-100%);
}
#content.appear{
  visibility: visible;
  opacity: 1;
          transform: translateX(0);
  -webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
_x000D_
_x000D_

Importing a Maven project into Eclipse from Git

Eclipse Indigo + M2Eclipse 1.0 makes it very easy.

If you don't already have the Git connector for M2Eclipse install it. M2Eclipse will help you along by prompting you on the Import menu.

  1. Select the "Import..." context menu from the Package Explorer view
  2. Select "Check out Maven projects from SCM" option under the Maven category
  3. On the window that is presented choose the link "Find more SCM connectors in the m2e Marketplace
  4. Find connector for Git...install...restart

Note that in the search box you may have to enter "EGit" instead of "Git" to find the right connector.

With that done, simply go to the EGit repository, bring up the context menu for the Working directory and select "Import Maven projects...".

Done!

Conversion between UTF-8 ArrayBuffer and String

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                                   ((char2 & 0x3F) << 6) |
                                   ((char3 & 0x3F) << 0));
        break;
    }
  }    
  return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here, here

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

Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html

Basically, start the server with the -u option:

./script/server -u

And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.

class EventsController < ApplicationController
  def index
    debugger
  end
end

And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.

MySQL: is a SELECT statement case sensitive?

The default is case insensitive, but the next most important thing you should take a look at is how the table was created in the first place, because you can specify case sensitivity when you create the table.

The script below creates a table. Notice down at the bottom it says "COLLATE latin1_general_cs". That cs at the end means case sensitive. If you wanted your table to be case insensitive you would either leave that part out or use "COLLATE latin1_general_ci".

   CREATE Table PEOPLE (

       USER_ID  INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,

       FIRST_NAME  VARCHAR(50) NOT NULL,
       LAST_NAME  VARCHAR(50) NOT NULL,

       PRIMARY KEY (USER_ID)

   )

   ENGINE=MyISAM DEFAULT CHARACTER SET latin1
    COLLATE latin1_general_cs AUTO_INCREMENT=0;

If your project is such that you can create your own table, then it makes sense to specify your case sensitivity preference when you create the table.

How to retrieve available RAM from Windows command line?

PS C:\Users\Rack> systeminfo | findstr "System Memory"
System Boot Time:          5/5/2016, 11:10:41 PM
System Manufacturer:       VMware, Inc.
System Model:              VMware Virtual Platform
System Type:               x64-based PC
System Directory:          C:\Windows\system32
System Locale:             en-us;English (United States)
Total Physical Memory:     40,959 MB
Available Physical Memory: 36,311 MB
Virtual Memory: Max Size:  45,054 MB
Virtual Memory: Available: 41,390 MB
Virtual Memory: In Use:    3,664 MB

How to generate a random string of a fixed length in Go?

Here is my way ) Use math rand or crypto rand as you wish.

func randStr(len int) string {
    buff := make([]byte, len)
    rand.Read(buff)
    str := base64.StdEncoding.EncodeToString(buff)
    // Base 64 can be longer than len
    return str[:len]
}

What is a View in Oracle?

A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.

Access properties file programmatically with Spring?

You can get your properties through Environment class. As documentation stands:

Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.

Having Environment as a env variable, simply call:

env.resolvePlaceholders("${your-property:default-value}")

You can get your 'raw' properties through:

env.getProperty("your-property")

It will search through all properties source that spring has registered.

You can either obtain Environment through:

  • inject ApplicationContext by implementing ApplicationContextAware and then call getEnvironment() on context
  • implement EnvironmentAware.

It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.

Read more on documentation: spring Environment documentation

how to make div click-able?

I suggest to use a CSS class called clickbox and activate it with jQuery:

$(".clickbox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
 });

Now the only thing you have to do is mark your div as clickable and provide a link:

<div id="logo" class="clickbox"><a href="index.php"></a></div>

Plus a CSS style to change the mouse cursor:

.clickbox {
    cursor: pointer;
}

Easy, isn't it?

Disable scrolling on `<input type=number>`

function fixNumericScrolling() {
$$( "input[type=number]" ).addEvent( "mousewheel", function(e) {
    stopAll(e);     
} );
}

function stopAll(e) {
if( typeof( e.preventDefault               ) != "undefined" ) e.preventDefault();
if( typeof( e.stopImmediatePropagation     ) != "undefined" ) e.stopImmediatePropagation();
if( typeof( event ) != "undefined" ) {
    if( typeof( event.preventDefault           ) != "undefined" ) event.preventDefault();
    if( typeof( event.stopImmediatePropagation ) != "undefined" ) event.stopImmediatePropagation();
}

return false;
}

Correct set of dependencies for using Jackson mapper

<properties>
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
   <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
</dependencies>

you have a ObjectMapper (from Jackson Databind package) handy. if so, you can do:

JsonFactory factory = objectMapper.getFactory();

Source: https://github.com/FasterXML/jackson-core

So, the 3 "fasterxml" dependencies which you already have in u'r pom are enough for ObjectMapper as it includes jackson-databind.

How do I make an input field accept only letters in javaScript?

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

function validate() {
    if (document.myForm.name.value == "") {
        alert("Enter a name");
        document.myForm.name.focus();
        return false;
    }
    if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
        alert("Invalid characters");
        document.myForm.name.focus();
        return false;
    }
}

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

How generate unique Integers based on GUIDs

I had a requirement where multiple instances of a console application needed to get an unique integer ID. It is used to identify the instance and assigned at startup. Because the .exe is started by hands, I settled on a solution using the ticks of the start time.

My reasoning was that it would be nearly impossible for the user to start two .exe in the same millisecond. This behavior is deterministic: if you have a collision, you know that the problem was that two instances were started at the same time. Methods depending on hashcode, GUID or random numbers might fail in unpredictable ways.

I set the date to 0001-01-01, add the current time and divide the ticks by 10000 (because I don't set the microseconds) to get a number that is small enough to fit into an integer.

 var now = DateTime.Now;
 var zeroDate = DateTime.MinValue.AddHours(now.Hour).AddMinutes(now.Minute).AddSeconds(now.Second).AddMilliseconds(now.Millisecond);
 int uniqueId = (int)(zeroDate.Ticks / 10000);

EDIT: There are some caveats. To make collisions unlikely, make sure that:

  • The instances are started manually (more than one millisecond apart)
  • The ID is generated once per instance, at startup
  • The ID must only be unique in regard to other instances that are currently running
  • Only a small number of IDs will ever be needed

String concatenation in Ruby

Here are more ways to do this:

"String1" + "String2"

"#{String1} #{String2}"

String1<<String2

And so on ...

Laravel Advanced Wheres how to pass variable into function?

You can pass the necessary variables from the parent scope into the closure with the use keyword.

For example:

DB::table('users')->where(function ($query) use ($activated) {
    $query->where('activated', '=', $activated);
})->get();

More on that here.

EDIT (2019 update):

PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.

An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):

DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();

Differences compared to the regular syntax:

  • fn keyword instead of function.
  • No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of use keyword in the latter example.
  • Arrow functions always return a value. This also means that it's impossible to use void return type when declaring them.
  • The return keyword must be omitted.
  • Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.

Function to Calculate a CRC16 Checksum

Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.

unsigned short crc16(const unsigned char* data_p, unsigned char length){
    unsigned char x;
    unsigned short crc = 0xFFFF;

    while (length--){
        x = crc >> 8 ^ *data_p++;
        x ^= x>>4;
        crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
    }
    return crc;
}

How can I pause setInterval() functions?

i wrote a simple ES6 class that may come handy. inspired by https://stackoverflow.com/a/58580918/4907364 answer

export class IntervalTimer {
    private callbackStartTime;
    private remaining= 0;
    private paused= false;
    public timerId = null;
    private readonly _callback;
    private readonly _delay;

    constructor(callback, delay) {
        this._callback = callback;
        this._delay = delay;
    }

    pause() {
        if (!this.paused) {
            this.clear();
            this.remaining = new Date().getTime() - this.callbackStartTime;
            this.paused = true;
        }
    }

    resume() {
        if (this.paused) {
            if (this.remaining) {
                setTimeout(() => {
                    this.run();
                    this.paused = false;
                    this.start();
                }, this.remaining);
            } else {
                this.paused = false;
                this.start();
            }
        }
    }

    clear() {
        clearInterval(this.timerId);
    }

    start() {
        this.clear();
        this.timerId = setInterval(() => {
            this.run();
        }, this._delay);
    }

    private run() {
        this.callbackStartTime = new Date().getTime();
        this._callback();
    }
}

usage is pretty straightforward,

const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();

Get first day of week in PHP?

I was searching for a solution similar to this and I finally came up with something that will return each day of the current week.

//set current timestamp
$today = time();
//calculate the number of days since Monday
$dow = date('w', $today);
  $offset = $dow - 1;
if ($offset < 0) {
  $offset = 6;
  }
//calculate timestamp for Monday and Sunday
$monday = $today - ($offset * 86400);
$tuesday = $monday + (1 * 86400);
$wednesday = $monday + (2 * 86400);
$thursday = $monday + (3 * 86400);
$friday = $monday + (4 * 86400);
$saturday = $monday + (5 * 86400);
$sunday = $monday + (6 * 86400);
//print dates for Monday and Sunday in the current week
print date("Y-m-d", $monday) . "\n";
print date("Y-m-d", $tuesday) . "\n";
print date("Y-m-d", $wednesday) . "\n";
print date("Y-m-d", $thursday) . "\n";
print date("Y-m-d", $friday) . "\n";
print date("Y-m-d", $saturday) . "\n";
print date("Y-m-d", $sunday) . "\n";

Thank you to dbunic who posted this here: http://www.redips.net/php/week-list-current-date/#comments

Escaping double quotes in JavaScript onClick event handler

Did you try

&quot; or \x22

instead of

\"

?

How to set value to variable using 'execute' in t-sql?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
    @columnName varchar(255),
    @id int
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @columnVal TABLE (columnVal nvarchar(255));

    DECLARE @sql nvarchar(max);
    SET @sql = 'SELECT ' + @columnName + ' FROM regUsers WHERE id=' + CAST(@id AS varchar(10));
    INSERT @columnVal EXEC sp_executesql @sql;

    SELECT * FROM @columnVal;
END
GO

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

Text Editor which shows \r\n?

You can get this in Emacs by changing the mode. For example, here is what things look like in Whitespace mode.

alt text

Loop in Jade (currently known as "Pug") template engine

Here is a very simple jade file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}:

- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
    head
    body
        section= s
        - for (var i=0; i<3; i++)
            div= arr[i]

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

Add custom header in HttpWebRequest

You use the Headers property with a string index:

request.Headers["X-My-Custom-Header"] = "the-value";

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

Android : Check whether the phone is dual SIM

I have found these system properties on Samsung S8

SystemProperties.getInt("ro.multisim.simslotcount", 1) > 1

Also, according to the source: https://android.googlesource.com/platform/frameworks/base/+/master/telephony/java/com/android/internal/telephony/TelephonyProperties.java

getprop persist.radio.multisim.config returns "dsds" or "dsda" on multi sim.

I have tested this on Samsung S8 and it works

How do I use a C# Class Library in a project?

I'm not certain why everyone is claiming that you need a using statement at the top of your file, as this is entirely unnecessary.

Right-click on the "References" folder in your project and select "Add Reference". If your new class library is a project in the same solution, select the "Project" tab and pick the project. If the new library is NOT in the same solution, click the "Browse" tab and find the .dll for your new project.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

There is no HTTP status code 0. What you see is a 0 returned by the API/library that you are using. You will have to check the documentation for that.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Get Client Machine Name in PHP

Try

echo getenv('COMPUTERNAME');

This will return your computername.

phonegap open link in browser

<a onclick="navigator.app.loadUrl('https://google.com/', { openExternal:true });">Link</a>

Works for me with android & PG 3.0

Grouping functions (tapply, by, aggregate) and the *apply family

I recently discovered the rather useful sweep function and add it here for the sake of completeness:

sweep

The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):

Let's say you have a matrix and want to standardize it column-wise:

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,]  0.5  0.5  0.5
## [4,]  1.5  1.5  1.5

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)

Using continue in a switch statement

It's syntactically correct and stylistically okay.

Good style requires every case: statement should end with one of the following:

 break;
 continue;
 return (x);
 exit (x);
 throw (x);
 //fallthrough

Additionally, following case (x): immediately with

 case (y):
 default:

is permissible - bundling several cases that have exactly the same effect.

Anything else is suspected to be a mistake, just like if(a=4){...} Of course you need enclosing loop (while, for, do...while) for continue to work. It won't loop back to case() alone. But a construct like:

while(record = getNewRecord())
{
    switch(record.type)
    {
        case RECORD_TYPE_...;
            ...
        break;
        default: //unknown type
            continue; //skip processing this record altogether.
    }
    //...more processing...
}

...is okay.

What is dtype('O'), in pandas?

It means:

'O'     (Python) objects

Source.

The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are to an existing type, or an error will be raised. The supported kinds are:

'b'       boolean
'i'       (signed) integer
'u'       unsigned integer
'f'       floating-point
'c'       complex-floating point
'O'       (Python) objects
'S', 'a'  (byte-)string
'U'       Unicode
'V'       raw data (void)

Another answer helps if need check types.

Java 8 Filter Array Using Lambda

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

Javascript format date / time

Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:


Demo

I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.

moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm

Renaming the current file in Vim

You can also use :f followed by :w

Convert list to array in Java

I think this is the simplest way:

Foo[] array = list.toArray(new Foo[0]);

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

How can I send and receive WebSocket messages on the server side?

Clojure, the decode function assumes frame is sent as map of {:data byte-array-buffer :size int-size-of-buffer}, because the actual size may not be the same size as the byte-array depending on chunk size of your inputstream.

Code posted here: https://gist.github.com/viperscape/8918565

(defn ws-decode [frame]
  "decodes websocket frame"
  (let [data (:data frame)
        dlen (bit-and (second data) 127)
        mstart (if (== dlen 127) 10 (if (== dlen 126) 4 2))
        mask (drop 2 (take (+ mstart 4) data))
        msg (make-array Byte/TYPE (- (:size frame) (+ mstart 4)))]
   (loop [i (+ mstart 4), j 0]
      (aset-byte msg j (byte (bit-xor (nth data i) (nth mask (mod j 4)))))
      (if (< i (dec(:size frame))) (recur (inc i) (inc j))))
    msg))

(defn ws-encode [data]
  "takes in bytes, return websocket frame"
  (let [len (count data)
        blen (if (> len 65535) 10 (if (> len 125) 4 2))
        buf (make-array Byte/TYPE (+ len blen))
        _ (aset-byte buf 0 -127) ;;(bit-or (unchecked-byte 0x80) 
                                           (unchecked-byte 0x1)
        _ (if (= 2 blen) 
            (aset-byte buf 1 len) ;;mask 0, len
            (do
              (dorun(map #(aset-byte buf %1 
                      (unchecked-byte (bit-and (bit-shift-right len (*(- %2 2) 8))
                                               255)))
                      (range 2 blen) (into ()(range 2 blen))))
              (aset-byte buf 1 (if (> blen 4) 127 126))))
        _ (System/arraycopy data 0 buf blen len)]
    buf))

Shall we always use [unowned self] inside closure in Swift

Update 11/2016

I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

Original answer

The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

swift weak vs unowned

Scenarios

You can have two possible scenarios:

  1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

  2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

Actual Usage

So, which will/should you actually use most of the times?

Quoting Joe Groff from twitter:

Unowned is faster and allows for immutability and nonoptionality.

If you don't need weak, don't use it.

You'll find more about unowned* inner workings here.

* Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

Implements vs extends: When to use? What's the difference?

In the most simple terms extends is used to inherit from a class and implements is used to apply an interface in your class

extends:

public class Bicycle {
    //properties and methods
}
public class MountainBike extends Bicycle {
    //new properties and methods
}

implements:

public interface Relatable {
    //stuff you want to put
}
public class RectanglePlus implements Relatable {
    //your class code
}

if you still have confusion read this: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html

Why won't bundler install JSON gem?

$ bundle update json
$ bundle install

Generating random strings with T-SQL

Below are the way to Generate 4 Or 8 Characters Long Random Alphanumeric String in SQL

select LEFT(CONVERT(VARCHAR(36),NEWID()),4)+RIGHT(CONVERT(VARCHAR(36),NEWID()),4)

 SELECT RIGHT(REPLACE(CONVERT(VARCHAR(36),NEWID()),'-',''),8)

Recursively counting files in a Linux directory

ls -l | grep -e -x -e -dr | wc -l 
  1. long list
  2. filter files and dirs
  3. count the filtered line no

Gson: Directly convert String to JsonObject (no POJO)

Just encountered the same problem. You can write a trivial custom deserializer for the JsonElement class:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(
        JsonElement.class,
        new JsonDeserializer<JsonElement>() {
            @Override
            public JsonElement deserialize(JsonElement arg0,
                    Type arg1,
                    JsonDeserializationContext arg2)
                    throws JsonParseException {

                return arg0;
            }
        } );
String str = "{ \"a\": \"A\", \"b\": true }";
Gson gson = gson_builder.create();
JsonElement element = gson.fromJson(str, JsonElement.class);
JsonObject object = element.getAsJsonObject();

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

How to highlight a current menu item?

The answer from @Renan-tomal-fernandes is good, but needed a couple of improvements to work correctly. As it was, it'd always detect the link to the home page ( / ) as triggered, even if you were in another section.

So I improved it a little bit, here's the code. I work with Bootstrap so the active part is in the <li> element instead of the the <a>.

Controller

$scope.getClass = function(path) {
    var cur_path = $location.path().substr(0, path.length);
    if (cur_path == path) {
        if($location.path().substr(0).length > 1 && path.length == 1 )
            return "";
        else
            return "active";
    } else {
        return "";
    }
}

Template

<div class="nav-collapse collapse">
  <ul class="nav">
    <li ng-class="getClass('/')"><a href="#/">Home</a></li>
    <li ng-class="getClass('/contents/')"><a href="#/contests/">Contents</a></li>
    <li ng-class="getClass('/data/')"><a href="#/data/">Your data</a></li>
  </ul>
</div>

Resource u'tokenizers/punkt/english.pickle' not found

If you're looking to only download the punkt model:

import nltk
nltk.download('punkt')

If you're unsure which data/model you need, you can install the popular datasets, models and taggers from NLTK:

import nltk
nltk.download('popular')

With the above command, there is no need to use the GUI to download the datasets.

How to sort an array in Bash

This question looks closely related. And BTW, here's a mergesort in Bash (without external processes):

mergesort() {
  local -n -r input_reference="$1"
  local -n output_reference="$2"
  local -r -i size="${#input_reference[@]}"
  local merge previous
  local -a -i runs indices
  local -i index previous_idx merged_idx \
           run_a_idx run_a_stop \
           run_b_idx run_b_stop

  output_reference=("${input_reference[@]}")
  if ((size == 0)); then return; fi

  previous="${output_reference[0]}"
  runs=(0)
  for ((index = 0;;)) do
    for ((++index;; ++index)); do
      if ((index >= size)); then break 2; fi
      if [[ "${output_reference[index]}" < "$previous" ]]; then break; fi
      previous="${output_reference[index]}"
    done
    previous="${output_reference[index]}"
    runs+=(index)
  done
  runs+=(size)

  while (("${#runs[@]}" > 2)); do
    indices=("${!runs[@]}")
    merge=("${output_reference[@]}")
    for ((index = 0; index < "${#indices[@]}" - 2; index += 2)); do
      merged_idx=runs[indices[index]]
      run_a_idx=merged_idx
      previous_idx=indices[$((index + 1))]
      run_a_stop=runs[previous_idx]
      run_b_idx=runs[previous_idx]
      run_b_stop=runs[indices[$((index + 2))]]
      unset runs[previous_idx]
      while ((run_a_idx < run_a_stop && run_b_idx < run_b_stop)); do
        if [[ "${merge[run_a_idx]}" < "${merge[run_b_idx]}" ]]; then
          output_reference[merged_idx++]="${merge[run_a_idx++]}"
        else
          output_reference[merged_idx++]="${merge[run_b_idx++]}"
        fi
      done
      while ((run_a_idx < run_a_stop)); do
        output_reference[merged_idx++]="${merge[run_a_idx++]}"
      done
      while ((run_b_idx < run_b_stop)); do
        output_reference[merged_idx++]="${merge[run_b_idx++]}"
      done
    done
  done
}

declare -ar input=({z..a}{z..a})
declare -a output

mergesort input output

echo "${input[@]}"
echo "${output[@]}"

What does .class mean in Java?

In generics, an unknown type is represented by the wildcard character "?". Read here for official example.

Docker-compose: node_modules not present in a volume after npm install succeeds

In my opinion, we should not RUN npm install in the Dockerfile. Instead, we can start a container using bash to install the dependencies before runing the formal node service

docker run -it -v ./app:/usr/src/app  your_node_image_name  /bin/bash
root@247543a930d6:/usr/src/app# npm install

SQL Server dynamic PIVOT query?

You can achieve this using dynamic TSQL (remember to use QUOTENAME to avoid SQL injection attacks):

Pivots with Dynamic Columns in SQL Server 2005

SQL Server - Dynamic PIVOT Table - SQL Injection

Obligatory reference to The Curse and Blessings of Dynamic SQL

twitter bootstrap navbar fixed top overlapping site

The problem is with navbar-fixed-top, which will overlay your content unless specify body-padding. No solution provided here works in 100% cases. The JQuery solution blink/shift the page after the page is loaded, which looks weird.

The real solution for me is not to use navbar-fixed-top, but navbar-static-top.

.navbar { margin-bottom:0px;} //for jumtron support, see http://stackoverflow.com/questions/23911242/gap-between-navbar-and-jumbotron

<nav class="navbar navbar-inverse navbar-static-top">
...
</nav>

Is an anchor tag without the href attribute safe?

It is OK, but at the same time can cause some browsers to become slow.

http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/

My advice is use <a href="#"></a>

If you're using JQuery remember to also use:

.click(function(event){
    event.preventDefault();
    // Click code here...
});

Java - Convert int to Byte Array of 4 Bytes?

public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

Case insensitive 'in'

Usually (in oop at least) you shape your object to behave the way you want. name in USERNAMES is not case insensitive, so USERNAMES needs to change:

class NameList(object):
    def __init__(self, names):
        self.names = names

    def __contains__(self, name): # implements `in`
        return name.lower() in (n.lower() for n in self.names)

    def add(self, name):
        self.names.append(name)

# now this works
usernames = NameList(USERNAMES)
print someone in usernames

The great thing about this is that it opens the path for many improvements, without having to change any code outside the class. For example, you could change the self.names to a set for faster lookups, or compute the (n.lower() for n in self.names) only once and store it on the class and so on ...

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

CASE .. WHEN expression in Oracle SQL

CASE TO_CHAR(META.RHCONTRATOSFOLHA.CONTRATO)
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0001' THEN '91RJ'
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0002' THEN '91SP'
END CONTRATO,

00905. 00000 -  "missing keyword"
*Cause:    
*Action:
Erro na linha: 15 Coluna: 11

How to measure height, width and distance of object using camera?

For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.

This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.

So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.

If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.

I have found some links using Google, they may help.

  1. http://forestjohnson.blogspot.com/2010/01/how-to-measure-size-of-object-using.html
  2. http://gigaom.com/mobile/how_to_measure_/
  3. http://www.iphonelife.com/blog/5/cameasure-use-your-camera-measure-size-or-distance

They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.

One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.

See these links as well:

  1. http://iopscience.iop.org/1742-6596/48/1/074/pdf/1742-6596_48_1_074.pdf
  2. http://www.optical-metrology-centre.com/Downloads/Papers/Photogrammetric%20Record%201994%20Automated%203-D%20measurement.pdf