Programs & Examples On #Symbol capture

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

How can I roll back my last delete command in MySQL?

If you want rollback data, firstly you need to execute autocommit =0 and then execute query delete, insert, or update.

After executing the query then execute rollback...

How Do I Uninstall Yarn

What I've done on my side:

Went to the /usr/local/lib/node_modules, and deleted the yarn folder inside it.

What is the main purpose of setTag() getTag() methods of View?

Setting of TAGs is really useful when you have a ListView and want to recycle/reuse the views. In that way the ListView is becoming very similar to the newer RecyclerView.

@Override
public View getView(int position, View convertView, ViewGroup parent)
  {
ViewHolder holder = null;

if ( convertView == null )
{
    /* There is no view at this position, we create a new one. 
       In this case by inflating an xml layout */
    convertView = mInflater.inflate(R.layout.listview_item, null);  
    holder = new ViewHolder();
    holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
    convertView.setTag (holder);
}
else
{
    /* We recycle a View that already exists */
    holder = (ViewHolder) convertView.getTag ();
}

// Once we have a reference to the View we are returning, we set its values.

// Here is where you should set the ToggleButton value for this item!!!

holder.toggleOk.setChecked( mToggles.get( position ) );

return convertView;
}

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

Download a file from NodeJS Server using Express

Use res.download()

It transfers the file at path as an “attachment”. For instance:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

System.BadImageFormatException An attempt was made to load a program with an incorrect format

For running it on any CPU either 62 bit or 32 bit follow these steps: Right click on the name of the project in Solution Explorer> Properties>Build and have these under Configuration: Active(Release), Platform:Active(Any CPU) and Target:x86. and just beside the Run button Select option Release and Any CPU from the options. And then Save it and Run.

Using fonts with Rails asset pipeline

Here is a repo the demonstrates serving a custom font with Rails 5.2 that works on Heroku. It goes further and optimizes serving the fonts to be as fast as possible according to https://www.webpagetest.org/

https://github.com/nzoschke/edgecors

To start I picked pieces from answers above. For Rails 5.2+ you shouldn't need extra asset pipeline config.

Asset Pipeline and SCSS

  • Place fonts in app/assets/fonts
  • Place the @font-face declaration in an scss file and use the font-url helper

From app/assets/stylesheets/welcome.scss:

@font-face {
  font-family: 'Inconsolata';
  src: font-url('Inconsolata-Regular.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: "Inconsolata";
  font-weight: bold;
}

Serve from CDN with CORS

I'm using CloudFront, added with the Heroku Edge addon.

First configure a CDN prefix and default Cache-Control headers in production.rb:

Rails.application.configure do
  # e.g. https://d1unsc88mkka3m.cloudfront.net
  config.action_controller.asset_host = ENV["EDGE_URL"]

  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=31536000'
  }
end

If you try to access the font from the herokuapp.com URL to the CDN URL, you will get a CORS error in your browser:

Access to font at 'https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf' from origin 'https://edgecors.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. edgecors.herokuapp.com/ GET https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf net::ERR_FAILED

So configure CORS to allow access to the font from Heroku to the CDN URL:

module EdgeCors
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    config.middleware.insert_after ActionDispatch::Static, Rack::Deflater

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins %w[
          http://edgecors.herokuapp.com
          https://edgecors.herokuapp.com
        ]
        resource "*", headers: :any, methods: [:get, :post, :options]
      end
    end
  end
end

Serve gzip Font Asset

The asset pipeline builds a .ttf.gz file but doesn't serve it. This monkey patch changes the asset pipeline gzip whitelist to a blacklist:

require 'action_dispatch/middleware/static'

ActionDispatch::FileHandler.class_eval do
  private

    def gzip_file_path(path)
      return false if ['image/png', 'image/jpeg', 'image/gif'].include? content_type(path)
      gzip_path = "#{path}.gz"
      if File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path)))
        gzip_path
      else
        false
      end
    end
end

The ultimate result is a custom font file in app/assets/fonts served from a long-lived CloudFront cache.

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

Sum one number to every element in a list (or array) in Python

You can also use map:

a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))

It gives:

[2, 2, 2, 2, 2]

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

I wasn't able to ever accomplish this but rather used view html source apps available on the Play Store to simply look for the element.

Python memory leaks

You should specially have a look on your global or static data (long living data).

When this data grows without restriction, you can also get troubles in Python.

The garbage collector can only collect data, that is not referenced any more. But your static data can hookup data elements that should be freed.

Another problem can be memory cycles, but at least in theory the Garbage collector should find and eliminate cycles -- at least as long as they are not hooked on some long living data.

What kinds of long living data are specially troublesome? Have a good look on any lists and dictionaries -- they can grow without any limit. In dictionaries you might even don't see the trouble coming since when you access dicts, the number of keys in the dictionary might not be of big visibility to you ...

Static vs class functions/variables in Swift classes?

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

PHP: merge two arrays while keeping keys instead of reindexing?

Two arrays can be easily added or union without chaning their original indexing by + operator. This will be very help full in laravel and codeigniter select dropdown.

 $empty_option = array(
         ''=>'Select Option'
          );

 $option_list = array(
          1=>'Red',
          2=>'White',
          3=>'Green',
         );

  $arr_option = $empty_option + $option_list;

Output will be :

$arr_option = array(
   ''=>'Select Option'
   1=>'Red',
   2=>'White',
   3=>'Green',
 );

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

What does -save-dev mean in npm install grunt --save-dev

Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

https://docs.npmjs.com/getting-started/using-a-package.json#the-save-and-save-dev-install-flags

A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

How do I import a specific version of a package using go get?

It might be useful.

Just type this into your command prompt while cd your/package/src/

go get github.com/go-gl/[email protected]

You get specific revision of package in question right into your source code, ready to use in import statement.

Using set_facts and with_items together in Ansible

I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.

https://github.com/ansible/ansible/issues/39389

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }} + [ '{{ item }}' ]"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: []

    - name: Print the var
      debug:
        var: foo

How can I use a search engine to search for special characters?

Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".

Google indeed ignores most punctuation, with the following exceptions:

  1. Punctuation in popular terms that have particular meanings, like [ C++ ] or [ C# ] (both are names of programming languages), are not ignored.
  2. The dollar sign ($) is used to indicate prices. [ nikon 400 ] and [ nikon $400 ] will give different results.
  3. The hyphen - is sometimes used as a signal that the two words around it are very strongly connected. (Unless there is no space after the - and a space before it, in which case it is a negative sign.)
  4. The underscore symbol _ is not ignored when it connects two words, e.g. [ quick_sort ].

As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.

Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.

For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.

select unique rows based on single distinct column

I'm assuming you mean that you don't care which row is used to obtain the title, id, and commentname values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:

select
    id,
    title,
    email,
    commentname

from
(
select 
    *, 
    row_number() over (partition by email order by id) as RowNbr 

from YourTable
) source

where RowNbr = 1

Cant get text of a DropDownList in code - can get value but not text

What about

lstCountry.Items[lstCountry.SelectedIndex].Text;

iTunes Connect: How to choose a good SKU?

The SKU example used in the documentation was to provide the allowed characters in a new user-specified SKU.

How can I setup & run PhantomJS on Ubuntu?

For PhantomJS version above 1.5, consider this (verbatim copy of the build instructions on the phantom website):

For Ubuntu Linux (tested on a barebone install of Ubuntu 10.04 Lucid Lynx and Ubuntu 11.04 Natty Narwhal):

sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.7
./build.sh

Why does visual studio 2012 not find my tests?

In My case it was something else. I had installed a package and then uninstall it and reinstall an earlier version. That left a residual configuration/runtime/asssemblyBinding/dependencyIdentity redirecting in my app.config. I had to correct it. I figured it out by looking at the Output window and selecting "Tests" in the drop down. The error message was there. This was a pain... I hope it helps someone else.

How can I change CSS display none or block property using jQuery?

Use:

$(#id/.class).show()
$(#id/.class).hide()

This one is the best way.

base64 encode in MySQL

Yet another custom implementation that doesn't require support table:

drop function if exists base64_encode;
create function base64_encode(_data blob)
returns text
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default length(_data);
    declare _i int unsigned default 0;
    declare _chk3 char(6) default '';
    declare _chk3int int default 0;
    declare _enc text default '';

    while _i < _lim do
        set _chk3 = rpad(hex(binary substr(_data, _i + 1, 3)), 6, '0');
        set _chk3int = conv(_chk3, 16, 10);
        set _enc = concat(
            _enc
            ,                  substr(_alphabet, ((_chk3int >> 18) & 63) + 1, 1)
            , if (_lim-_i > 0, substr(_alphabet, ((_chk3int >> 12) & 63) + 1, 1), '=')
            , if (_lim-_i > 1, substr(_alphabet, ((_chk3int >>  6) & 63) + 1, 1), '=')
            , if (_lim-_i > 2, substr(_alphabet, ((_chk3int >>  0) & 63) + 1, 1), '=')
        );
        set _i = _i + 3;
    end while;

    return _enc;
end;

drop function if exists base64_decode;
create function base64_decode(_enc text)
returns blob
begin
    declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    declare _lim int unsigned default 0;
    declare _i int unsigned default 0;
    declare _chr1byte tinyint default 0;
    declare _chk4int int default 0;
    declare _chk4int_bits tinyint default 0;
    declare _dec blob default '';
    declare _rem tinyint default 0;
    set _enc = trim(_enc);
    set _rem = if(right(_enc, 3) = '===', 3, if(right(_enc, 2) = '==', 2, if(right(_enc, 1) = '=', 1, 0)));
    set _lim = length(_enc) - _rem;

    while _i < _lim
    do
        set _chr1byte = locate(substr(_enc, _i + 1, 1), binary _alphabet) - 1;
        if (_chr1byte > -1)
        then
            set _chk4int = (_chk4int << 6) | _chr1byte;
            set _chk4int_bits = _chk4int_bits + 6;

            if (_chk4int_bits = 24 or _i = _lim-1)
            then
                if (_i = _lim-1 and _chk4int_bits != 24)
                then
                    set _chk4int = _chk4int << 0;
                end if;

                set _dec = concat(
                    _dec
                    ,                        char((_chk4int >> (_chk4int_bits -  8)) & 0xff)
                    , if(_chk4int_bits >  8, char((_chk4int >> (_chk4int_bits - 16)) & 0xff), '\0')
                    , if(_chk4int_bits > 16, char((_chk4int >> (_chk4int_bits - 24)) & 0xff), '\0')
                );
                set _chk4int = 0;
                set _chk4int_bits = 0;
            end if;
        end if;
        set _i = _i + 1;
    end while;

    return substr(_dec, 1, length(_dec) - _rem);
end;

Gist

You should convert charset after decoding: convert(base64_decode(base64_encode('????')) using utf8)

Sorted array list in Java

I think the choice between SortedSets/Lists and 'normal' sortable collections depends, whether you need sorting only for presentation purposes or at almost every point during runtime. Using a sorted collection may be much more expensive because the sorting is done everytime you insert an element.

If you can't opt for a collection in the JDK, you can take a look at the Apache Commons Collections

IntelliJ does not show 'Class' when we right click and select 'New'

If you open your module settings (F4) you can nominate which paths contain 'source'. Intellij will then mark these directories in blue and allow you to add classes etc.

In a similar fashion you can highlight test directories for unit tests.

How to increase heap size for jBoss server

Look in your JBoss bin folder for the file run.bat (run.sh on Unix)

look for the line set JAVA_OPTS, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.

If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.

set the width of select2 input (through Angular-ui directive)

With > 4.0 of select2 I am using

$("select").select2({
  dropdownAutoWidth: true
});

These others did not work:

  • dropdownCssClass: 'bigdrop'
  • width: '100%'
  • width: 'resolve'

Algorithm to detect overlapping periods

Try this. This method will determine if (two) date spans are overlapping, regardless of the ordering of the method's input arguments. This can also be used with more than two date spans, by individually checking each date span combination (ex. with 3 date spans, run span1 against span2, span2 against span3, and span1 against span3):

public static class HelperFunctions
{
    public static bool AreSpansOverlapping(Tuple<DateTime,DateTime> span1, Tuple<DateTime,DateTime> span2, bool includeEndPoints)
    {
        if (span1 == null || span2 == null)
        {
            return false;
        }
        else if ((new DateTime[] { span1.Item1, span1.Item2, span2.Item1, span2.Item2 }).Any(v => v == DateTime.MinValue))
        {
            return false;
        }
        else
        {
            if (span1.Item1 > span1.Item2)
            {
                span1 = new Tuple<DateTime, DateTime>(span1.Item2, span1.Item1);
            }
            if (span2.Item1 > span2.Item2)
            {
                span2 = new Tuple<DateTime, DateTime>(span2.Item2, span2.Item1);
            }

            if (includeEndPoints)
            {
                return 
                ((
                    (span1.Item1 <= span2.Item1 && span1.Item2 >= span2.Item1) 
                    || (span1.Item1 <= span2.Item2 && span1.Item2 >= span2.Item2)
                ) || (
                    (span2.Item1 <= span1.Item1 && span2.Item2 >= span1.Item1) 
                    || (span2.Item1 <= span1.Item2 && span2.Item2 >= span1.Item2)
                ));
            }
            else
            {
                return 
                ((
                    (span1.Item1 < span2.Item1 && span1.Item2 > span2.Item1) 
                    || (span1.Item1 < span2.Item2 && span1.Item2 > span2.Item2)
                ) || (
                    (span2.Item1 < span1.Item1 && span2.Item2 > span1.Item1) 
                    || (span2.Item1 < span1.Item2 && span2.Item2 > span1.Item2)
                ) || (
                    span1.Item1 == span2.Item1 && span1.Item2 == span2.Item2
                ));
            }
        }
    }
}

Test:

static void Main(string[] args)
{  
    Random r = new Random();

    DateTime d1;
    DateTime d2;
    DateTime d3;
    DateTime d4;

    for (int i = 0; i < 100; i++)
    {
        d1 = new DateTime(2012,1, r.Next(1,31));
        d2 = new DateTime(2012,1, r.Next(1,31));
        d3 = new DateTime(2012,1, r.Next(1,31));
        d4 = new DateTime(2012,1, r.Next(1,31));

        Console.WriteLine("span1 = " + d1.ToShortDateString() + " to " + d2.ToShortDateString());
        Console.WriteLine("span2 = " + d3.ToShortDateString() + " to " + d4.ToShortDateString());
        Console.Write("\t");
        Console.WriteLine(HelperFunctions.AreSpansOverlapping(
            new Tuple<DateTime, DateTime>(d1, d2),
            new Tuple<DateTime, DateTime>(d3, d4),
            true    //or use False, to ignore span's endpoints
            ).ToString());
        Console.WriteLine();
    }

    Console.WriteLine("COMPLETE");
    System.Console.ReadKey();
}

How do I add space between two variables after a print in Python

This is a stupid/hacky way

print count,    
print conv

How do I export (and then import) a Subversion repository?

The tool to do that would be

svnadmin dump

But for this to work, you need filesystem-access to the repository. And once you have that (and provided the repository is in FSFS format), you can just copy the repository to its new location (if it's in BDB format, dump/load is strongly recommended).

If you do not have filesystem access, you would have to ask your repository provider to provide the dump for you (and make them delete their repository - and hope they comply)

Code for Greatest Common Divisor in Python

def gcdRecur(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Base case is when b = 0
    if b == 0:
        return a

    # Recursive case
    return gcdRecur(b, a % b)

How can I fetch all items from a DynamoDB table without specifying the primary key?

This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet

        string tablename = "AnyTableName"; //table whose data you want to fetch

        var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(  

            new DynamoDBOperationConfig
            {
                OverrideTableName = tablename; 
            });

        foreach(string Id in IdList) // in case you are taking string from input
        {
            Guid objGuid = Guid.Parse(Id); //parsing string to guid
            BatchRead.AddKey(objGuid);
        }

        await BatchRead.ExecuteAsync();
        var result = BatchRead.Results;

// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

MySQL root password change

So many coments, but i was helped this method:

sudo mysqladmin -u root password 'my password'

In my case after instalation i had get mysql service without a password for root user, and i was need set the password for my security.

Get user profile picture by Id

As per the current latest Facebook API version 3.2, For users you can use this generic method for getting profile picture is https://graph.facebook.com/v3.2/{user-id}/picture?type=square you can visit documentation for user picture here. The possible values for type parameter in URL can be small, normal, album, large, square

For Groups and Pages, the profile picture is not available directly. You have to get them using access token. For Groups you have to use User Access Token and for Pages you can use both User Access Token and Page Access Token.

You can get Group's or Page's Profile Picture using the generic URL: https://graph.facebook.com/v3.2/{user-id}/picture?access_token={access-token}&type=square

I hope this is helpful for people who are looking for Page or Group Profile picture.

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

How to parse this string in Java?

String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.

Invoking a PHP script from a MySQL trigger

A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.

git clone through ssh

Git 101:

git is a decentralized version control system. You do not necessary need a server to get up and running with git. Still you might want to do that as it looks cool, right? (It's also useful if you want to work on a single project from multiple computers.)

So to get a "server" running you need to run git init --bare <your_project>.git as this will create an empty repository, which you can then import on your machines without having to muck around in config files in your .git dir.

After this you could clone the repo on your clients as it is supposed to work, but I found that some clients (namely git-gui) will fail to clone a repo that is completely empty. To work around this you need to run cd <your_project>.git && touch <some_random_file> && git add <some_random_file> && git commit && git push origin master. (Note that you might need to configure your username and email for that machine's git if you hadn't done so in the past. The actual commands to run will be in the error message you get so I'll just omit them.)

So at this point you can clone the repository to any machine simply by running git clone <user>@<server>:<relative_path><your_project>.git. (As others have pointed out you might need to prefix it with ssh:// if you use the absolute path.) This assumes that you can already log in from your client to the server. (You'll also get bonus points for setting up a config file and keys for ssh, if you intend to push a lot of stuff to the remote server.)

Some relevant links:
This pretty much tells you what you need to know.
And this is for those who know the basic workings of git but sometimes forget the exact syntax.

PHP how to get local IP of system

In windows

$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

It may be useful for someone, so I'll post it here. I was missing this dependency on my pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Python constructors and __init__

coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)

def func(): #now func refers to an empty funcion
    pass
...
func=5      #now func refers to the number 5
def func():
    print "something"    #now func refers to a different function

in your class definition, it just keeps the later one

How to add form validation pattern in Angular 2?

custom validation step by step

Html template

  <form [ngFormModel]="demoForm">
  <input  
  name="NotAllowSpecialCharacters"    
  type="text"                      
  #demo="ngForm"
  [ngFormControl] ="demoForm.controls['spec']"
  >

 <div class='error' *ngIf="demo.control.touched">
   <div *ngIf="demo.control.hasError('required')"> field  is required.</div>
   <div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
 </div>
  </form>

Component App.ts

import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';

under class define

 demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
    this.demoForm = Fb.group({
       spec: new Control('', Validators.compose([Validators.required,   CustomValidator.specialCharValidator])),
      })
}

under {../../yourServices/validatorService.ts}

export class CustomValidator {
    static specialCharValidator(control: Control): { [key: string]: any } {
   if (control.value) {
       if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {            
           return null;
       }
       else {            
           return { 'invalidChar': true };
       }
   }

 }

 }

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

How to return a part of an array in Ruby?

If you want to split/cut the array on an index i,

arr = arr.drop(i)

> arr = [1,2,3,4,5]
 => [1, 2, 3, 4, 5] 
> arr.drop(2)
 => [3, 4, 5] 

Check whether IIS is installed or not?

In the menu, go to RUN > services.msc and hit enter to get the services window and check for the IIS ADMIN service. If it is not present, then reinstall IIS using your windows CD.

Transfer data from one database to another database

  1. You can backup and restore the database using Management Studio.
  2. Again from Management Studio you can use "copy database".
  3. you can even do it manually if there is a reason to do so. I mean manually create the target db and manually copying data by sql statements...

can you clarify why you ask this? Is it that you dont have expierience in doing it or something else?

Importing csv file into R - numeric values read as characters

Including this in the read.csv command worked for me: strip.white = TRUE

(I found this solution here.)

Length of string in bash

UTF-8 string length

In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

will render:

Généralités is 11 char len, but 14 bytes len.

you could even have a look at stored chars:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

will answer:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL along with $LANG.

Length of an argument

Argument work same as regular variables

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

will work as

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Useful printf correction tool:

If you:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ?'    is  7 char length
 - 'Yin Yang ?' is 10 char length

Not really pretty... For this, there is a little function:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Then now:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ?'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ?'   is 10 chars length, but uses 12 bytes

Unfortunely, this is not perfect!

But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...

Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.

How do I "break" out of an if statement?

You probably need to break up your if statement into smaller pieces. That being said, you can do two things:

  • wrap the statement into do {} while (false) and use real break (not recommended!!! huge kludge!!!)

  • put the statement into its own subroutine and use return This may be the first step to improving your code.

How do I create a new class in IntelliJ without using the mouse?

On Mac you can navigate to the location in Project view where you want to create your class and then use ?N followed by Enter.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

After a lot of googling and trying all above...the only thing that solved my problem was this command:

$install_name_tool -id /usr/local/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

I am using a macbook pro, OSX 10 El Capitan. Darwin xxxx-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 23 18:25:34 PDT 2016; XXX:xnu-3248.60.10~1/RELEASE_X86_64 x86_64 Perl:v5.18.2 Mysql:5.6.19

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

What is the difference between dict.items() and dict.iteritems() in Python2?

If you have

dict = {key1:value1, key2:value2, key3:value3,...}

In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

  • Lists as mutable snapshots: d.items() -> list(d.items())
  • Iterator objects: d.iteritems() -> iter(d.items())

The tuples are the same. You compared tuples in each so you get same.

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.

Select row and element in awk

To print the second line:

awk 'FNR == 2 {print}'

To print the second field:

awk '{print $2}'

To print the third field of the fifth line:

awk 'FNR == 5 {print $3}'

Here's an example with a header line and (redundant) field descriptions:

awk 'BEGIN {print "Name\t\tAge"}  FNR == 5 {print "Name: "$3"\tAge: "$2}'

There are better ways to align columns than "\t\t" by the way.

Use exit to stop as soon as you've printed the desired record if there's no reason to process the whole file:

awk 'FNR == 2 {print; exit}'

How to use UTF-8 in resource properties with ResourceBundle

Given that you have an instance of ResourceBundle and you can get String by:

String val = bundle.getString(key); 

I solved my Japanese display problem by:

return new String(val.getBytes("ISO-8859-1"), "UTF-8");

Setting selection to Nothing when programming Excel

There is a way to SELECT NOTHING that solve your problem.

  1. Create a shape (one rectangle)
  2. Name it in Shapes Database >>> for example: "Ready"
  3. Refer to it MYDOC.Shapes("Ready") and change the visibility to False

When you want that Excel SELECT NOTHING do it:

MYDOC.Shapes("Ready").visible=True
MYDOC.Shapes("Ready").Select
MYDOC.Shapes("Ready").visible=False

This HIDE the selection and nothing still selected in your window PLUS: The word "Ready" is shown at the Left Top in your Sheet.

Batch / Find And Edit Lines in TXT file

There is no search and replace function or stream editing at the command line in XP or 2k3 (dont know about vista or beyond). So, you'll need to use a script like the one Ghostdog posted, or a search and replace capable tool like sed.

There is more than one way to do it, as this script shows:

@echo off
    SETLOCAL=ENABLEDELAYEDEXPANSION

    rename text.file text.tmp
    for /f %%a in (text.tmp) do (
        set foo=%%a
        if !foo!==ex3 set foo=ex5
        echo !foo! >> text.file) 
del text.tmp

What is the significance of 1/1/1753 in SQL Server?

Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

What is the problem with shadowing names defined in outer scopes?

Do this:

data = [4, 5, 6]

def print_data():
    global data
    print(data)

print_data()

Cropping an UIImage

Best solution for cropping an UIImage in Swift, in term of precision, pixels scaling ...:

private func squareCropImageToSideLength(let sourceImage: UIImage,
    let sideLength: CGFloat) -> UIImage {
        // input size comes from image
        let inputSize: CGSize = sourceImage.size

        // round up side length to avoid fractional output size
        let sideLength: CGFloat = ceil(sideLength)

        // output size has sideLength for both dimensions
        let outputSize: CGSize = CGSizeMake(sideLength, sideLength)

        // calculate scale so that smaller dimension fits sideLength
        let scale: CGFloat = max(sideLength / inputSize.width,
            sideLength / inputSize.height)

        // scaling the image with this scale results in this output size
        let scaledInputSize: CGSize = CGSizeMake(inputSize.width * scale,
            inputSize.height * scale)

        // determine point in center of "canvas"
        let center: CGPoint = CGPointMake(outputSize.width/2.0,
            outputSize.height/2.0)

        // calculate drawing rect relative to output Size
        let outputRect: CGRect = CGRectMake(center.x - scaledInputSize.width/2.0,
            center.y - scaledInputSize.height/2.0,
            scaledInputSize.width,
            scaledInputSize.height)

        // begin a new bitmap context, scale 0 takes display scale
        UIGraphicsBeginImageContextWithOptions(outputSize, true, 0)

        // optional: set the interpolation quality.
        // For this you need to grab the underlying CGContext
        let ctx: CGContextRef = UIGraphicsGetCurrentContext()
        CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh)

        // draw the source image into the calculated rect
        sourceImage.drawInRect(outputRect)

        // create new image from bitmap context
        let outImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

        // clean up
        UIGraphicsEndImageContext()

        // pass back new image
        return outImage
}

Instructions used to call this function:

let image: UIImage = UIImage(named: "Image.jpg")!
let squareImage: UIImage = self.squareCropImageToSideLength(image, sideLength: 320)
self.myUIImageView.image = squareImage

Note: the initial source code inspiration written in Objective-C has been found on "Cocoanetics" blog.

SQL Row_Number() function in Where Clause

I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE/ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP
  12. OFFSET/FETCH

I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE is always processed before SELECT making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.

Scroll Automatically to the Bottom of the Page

You can use this function wherever you need to call it:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo

Conversion from 12 hours time to 24 hours time in java

12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter

Test Data Input:

String input = "07:05:45PM"; timeCoversion12to24(input);

output

19:05:45

 public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {

        //Date/time pattern of input date (12 Hours format - hh used for 12 hours)
        DateFormat df = new SimpleDateFormat("hh:mm:ssaa");

        //Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
        DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
        Date date = null;
        String output = null;

        //Returns Date object
        date = df.parse(twelveHoursTime);

        //old date format to new date format
        output = outputformat.format(date);
        System.out.println(output);

        return output;
    }

Why should C++ programmers minimize use of 'new'?

One notable reason to avoid overusing the heap is for performance -- specifically involving the performance of the default memory management mechanism used by C++. While allocation can be quite quick in the trivial case, doing a lot of new and delete on objects of non-uniform size without strict order leads not only to memory fragmentation, but it also complicates the allocation algorithm and can absolutely destroy performance in certain cases.

That's the problem that memory pools where created to solve, allowing to to mitigate the inherent disadvantages of traditional heap implementations, while still allowing you to use the heap as necessary.

Better still, though, to avoid the problem altogether. If you can put it on the stack, then do so.

How to describe table in SQL Server 2008?

May be this can help:

Use MyTest
Go
select * from information_schema.COLUMNS where TABLE_NAME='employee'

{ where: MyTest= DatabaseName Employee= TableName } --Optional conditions

How to lay out Views in RelativeLayout programmatically?

Try:

EditText edt = (EditText) findViewById(R.id.YourEditText);
RelativeLayout.LayoutParams lp =
    new RelativeLayout.LayoutParams
    (
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
    );
lp.setMargins(25, 0, 0, 0); // move 25 px to right (increase left margin)
edt.setLayoutParams(lp); // lp.setMargins(left, top, right, bottom);

How to show data in a table by using psql command line interface?

Newer versions: (from 8.4 - mentioned in release notes)

TABLE mytablename;

Longer but works on all versions:

SELECT * FROM mytablename;

You may wish to use \x first if it's a wide table, for readability.

For long data:

SELECT * FROM mytable LIMIT 10;

or similar.

For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.

 \x
SELECT * FROM mytable LIMIT 10;

Note that in all cases the semicolon at the end is important.

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

String.Replace ignoring case

Use this, Tested and 100% Worked!

For VB.NET

Dim myString As String
Dim oldValue As String
Dim newValue As String

myString = Form1.TextBox1.Text
oldValue = TextBox1.Text
newValue = TextBox2.Text

Dim working As String = myString
Dim index As Integer = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase)

While index <> -1
    working = working.Remove(index, oldValue.Length)
    working = working.Insert(index, newValue)
    index = index + newValue.Length
    index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase)
    Form1.TextBox1.Text = working
End While

For C#

private void Button2_Click(System.Object sender, System.EventArgs e)
{
    string myString;
    string oldValue;
    string newValue;

    myString = Form1.TextBox1.Text;
    oldValue = TextBox1.Text;
    newValue = TextBox2.Text;

    string working = myString;
    int index = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase);

    while (index != -1)
    {
        working = working.Remove(index, oldValue.Length);
        working = working.Insert(index, newValue);
        index = index + newValue.Length;
        index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase);
        Form1.TextBox1.Text = working;
    }
}

React - Component Full Screen (with height 100%)

<div style={{ height: "100vh", background: "#2d405f" }}>
   <Component 1 />
   <Component 2 />
</div>

Create a div with full screen with background color #2d405f

How to check iOS version?

My solution is add a utility method to your utilities class (hint hint) to parse the system version and manually compensate for float number ordering.

Also, this code is rather simple, so I hope it helps some newbies. Simply pass in a target float, and get back a BOOL.

Declare it in your shared class like this:

(+) (BOOL) iOSMeetsOrExceedsVersion:(float)targetVersion;

Call it like this:

BOOL shouldBranch = [SharedClass iOSMeetsOrExceedsVersion:5.0101];

(+) (BOOL) iOSMeetsOrExceedsVersion:(float)targetVersion {

/*
 Note: the incoming targetVersion should use 2 digits for each subVersion --

 example 5.01 for v5.1, 5.11 for v5.11 (aka subversions above 9), 5.0101 for v5.1.1, etc.
*/

// Logic: as a string, system version may have more than 2 segments (example: 5.1.1)
// so, a direct conversion to a float may return an invalid number
// instead, parse each part directly

NSArray *sysVersion = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
float floatVersion = [[sysVersion objectAtIndex:0] floatValue];
if (sysVersion.count > 1) {
    NSString* subVersion = [sysVersion objectAtIndex:1];
    if (subVersion.length == 1)
        floatVersion += ([[sysVersion objectAtIndex:1] floatValue] *0.01);
    else
        floatVersion += ([[sysVersion objectAtIndex:1] floatValue] *0.10);
}
if (sysVersion.count > 2) {
    NSString* subVersion = [sysVersion objectAtIndex:2];
    if (subVersion.length == 1)
        floatVersion += ([[sysVersion objectAtIndex:2] floatValue] *0.0001);
    else
        floatVersion += ([[sysVersion objectAtIndex:2] floatValue] *0.0010);
}

if (floatVersion  >= targetVersion) 
    return TRUE;

// else
return FALSE;
 }

Circular (or cyclic) imports in Python

I got an example here that struck me!

foo.py

import bar

class gX(object):
    g = 10

bar.py

from foo import gX

o = gX()

main.py

import foo
import bar

print "all done"

At the command line: $ python main.py

Traceback (most recent call last):
  File "m.py", line 1, in <module>
    import foo
  File "/home/xolve/foo.py", line 1, in <module>
    import bar
  File "/home/xolve/bar.py", line 1, in <module>
    from foo import gX
ImportError: cannot import name gX

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

How do you determine the ideal buffer size when using FileInputStream?

1024 is appropriate for a wide variety of circumstances, although in practice you may see better performance with a larger or smaller buffer size.

This would depend on a number of factors including file system block size and CPU hardware.

It is also common to choose a power of 2 for the buffer size, since most underlying hardware is structured with fle block and cache sizes that are a power of 2. The Buffered classes allow you to specify the buffer size in the constructor. If none is provided, they use a default value, which is a power of 2 in most JVMs.

Regardless of which buffer size you choose, the biggest performance increase you will see is moving from nonbuffered to buffered file access. Adjusting the buffer size may improve performance slightly, but unless you are using an extremely small or extremely large buffer size, it is unlikely to have a signifcant impact.

What's the difference between emulation and simulation?

Both are models of an object that you have some means of controlling inputs and observing outputs. With an emulator, you want the output to be exactly what the object you are emulating would produce. With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer by rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

sql query to return differences between two tables

I know that this may not be a popular answer but I do agree with @Randy Minder on using third party tool when more complex comparison is needed.

This specific case here is easy and for this case such tools are not needed but this can get complex easily if you introduce more columns, databases on two servers, more complex comparison criteria and such.

There are a lot of these tools such as ApexSQL Data Diff or Quest Toad and you can always use them in trial mode to get the job done.

Array definition in XML?

No, there is no simpler way. You only can lose the type=array.

<numbers>
    <value>3</value>
    <value>2</value>
    <value>1</value>
</numbers>

curl error 18 - transfer closed with outstanding read data remaining

I had the same problem, but managed to fix it by suppressing the 'Expect: 100-continue' header that cURL usually sends (the following is PHP code, but should work similarly with other cURL APIs):

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

By the way, I am sending calls to the HTTP server that is included in the JDK 6 REST stuff, which has all kinds of problems. In this case, it first sends a 100 response, and then with some requests doesn't send the subsequent 200 response correctly.

Include an SVG (hosted on GitHub) in MarkDown

Use this site: https://rawgit.com , it works for me as I don't have permission issue with the svg file.
Please pay attention that RawGit is not a service of github, as mentioned in Rawgit FAQ :

RawGit is not associated with GitHub in any way. Please don't contact GitHub asking for help with RawGit

Enter the url of svg you need, such as :

https://github.com/sel-fish/redis-experiments/blob/master/dat/memDistrib-jemalloc-4.0.3.svg

Then, you can get the url bellow which can be used to display:

https://cdn.rawgit.com/sel-fish/redis-experiments/master/dat/memDistrib-jemalloc-4.0.3.svg

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

How can I reorder a list?

This is what I used when I stumbled upon this problem.

def order(list_item, i): # reorder at index i
    order_at = list_item.index(i)
    ordered_list = list_item[order_at:] + list_item[:order_at]
    return ordered_list

EX: for the the lowercase letters

order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'

It simply just shifts the list to a specified index

How to check if a file exists in a shell script

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let's delete it. But there are a few treacherous rapids on this river:

  • Everything is a file.

  • Scripts have real power only if they solve general tasks

  • To be general, we use variables

  • We often use -f force in scripts to avoid manual intervention

  • And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

We also hava a path variable to make things really flexible

<host>:~/Documents/thisfolderexists pathtofile=".."

<host>:~/Documents/thisfolderexists ls $pathtofile

filesexists.json  history20170728  SE-Data-API.pem  thisfolderexists

So let's see if -e does what it is supposed to. Does the files exist?

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

It does. Magic.

However, what would happen, if the file variable got accidentally be evaluated to nuffin'

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

What? It is supposed to return with an error... And this is the beginning of the story how that entire folder got deleted by accident

An alternative could be to test specifically for what we understand to be a 'file'

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

0

So the file exists...

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

1

So this is not a file and maybe, we do not want to delete that entire directory

man test has the following to say:

-b FILE

       FILE exists and is block special

-c FILE

       FILE exists and is character special

-d FILE

       FILE exists and is a directory

-e FILE

       FILE exists

-f FILE

       FILE exists and is a regular file

...

-h FILE

       FILE exists and is a symbolic link (same as -L)

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

Read/Write 'Extended' file properties (C#)

Here is a solution for reading - not writing - the extended properties based on what I found on this page and at help with shell32 objects.

To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:

        var i = 0;
        while (true)
        {
            ...
            if (String.IsNullOrEmpty(header)) break;
            ...
            i++;

On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:

    private Dictionary<string, string> GetExtendedProperties(string filePath)
    {
        var directory = Path.GetDirectoryName(filePath);
        var shell = new Shell32.Shell();
        var shellFolder = shell.NameSpace(directory);
        var fileName = Path.GetFileName(filePath);
        var folderitem = shellFolder.ParseName(fileName);
        var dictionary = new Dictionary<string, string>();
        var i = -1;
        while (++i < 320)
        {
            var header = shellFolder.GetDetailsOf(null, i);
            if (String.IsNullOrEmpty(header)) continue;
            var value = shellFolder.GetDetailsOf(folderitem, i);
            if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);
            Console.WriteLine(header +": " + value);
        }
        Marshal.ReleaseComObject(shell);
        Marshal.ReleaseComObject(shellFolder);
        return dictionary;
    }

As mentioned you need to reference the Com assembly Interop.Shell32.

If you get an STA related exception, you will find the solution here:

Exception when using Shell32 to get File extended properties

I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.

BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.

On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc. https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties

And finally, I posted a much better solution that uses WindowsAPICodePack there

How can I disable HREF if onclick is executed?

Try using javascript:void(0) as follows-

<a href="javascript:void(0)" onclick="...">Text</a>

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

What is the fastest way to transpose a matrix in C++?

intel mkl suggests in-place and out-of-place transposition/copying matrices. here is the link to the documentation. I would recommend trying out of place implementation as faster ten in-place and into the documentation of the latest version of mkl contains some mistakes.

python capitalize first letter only

def solve(s):
    for i in s[:].split():
        s = s.replace(i, i.capitalize())
    return s

This is the actual code for work. .title() will not work at '12name' case

What's the most elegant way to cap a number to a segment?

Update for ECMAScript 2017:

Math.clamp(x, lower, upper)

But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

How do I analyze a .hprof file?

You can use JHAT, The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. A very useful view is the "heap histogram" link at the very bottom.

ex: jhat -port 7401 -J-Xmx4G dump.hprof

jhat can execute OQL "these days" as well (bottom link "execute OQL")

How can I search (case-insensitive) in a column using LIKE wildcard?

use ILIKE

SELECT * FROM trees WHERE trees.`title` ILIKE '%elm%';

it worked for me !!

0xC0000005: Access violation reading location 0x00000000

"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0 and so you try to read from the memory address 0x0, which the operating system detects and prevents you from doing.

Check and make sure that the array invaders[] is what you think it should be.

Also, you don't seem to be updating i ever - meaning that you keep placing the same Invader object into location 0 of invaders[] at every loop iteration.

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Multiple radio button groups in MVC 4 Razor

Ok here's how I fixed this

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
{
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
  {
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)
  }    
}

The result is:

<input name="127" type="radio" value="110">

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

Thanks to all of the people who helped me solve this ;)

identifier "string" undefined?

You forgot the namespace you're referring to. Add

using namespace std;

to avoid std::string all the time.

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Prevent direct access to a php include file

Earlier mentioned solution with PHP version check added:

    $max_includes = version_compare(PHP_VERSION, '5', '<') ? 0 : 1;
    if (count(get_included_files()) <= $max_includes)
    {
        exit('Direct access is not allowed.');
    }

What is the equivalent of 'describe table' in SQL Server?

Just double click on the table name and press Alt+F1

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

Pretty-print a Map in Java

I prefer to convert the map to a JSON string it is:

  • a standard
  • human readable
  • supported in editors like Sublime, VS Code, with syntax highlighting, formatting and section hide/show
  • supports JPath so editors can report exactly which part of the object you have navigated to
  • supports nested complex types within the object

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public static String getAsFormattedJsonString(Object object)
    {
        ObjectMapper mapper = new ObjectMapper();
        try
        {
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        }
        catch (JsonProcessingException e)
        {
            e.printStackTrace();
        }
        return "";
    }
    

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

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

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

Count specific character occurrences in a string

var charCount = "string with periods...".Count(x => '.' == x);

CMake does not find Visual C++ compiler

A couple of tips:

  • Try to set the path manually by checking 'advanced' and modifying CMAKE_LINKER and CMAKE_MAKE_PROGRAM
  • Delete the cache - in the CMake with GUI go to: File ? Delete Cache.

My problem was a combination of previously stated: I have set the compiler version to 15 instead of 14 and when corrected, I had to delete the cache.

I also started the Visual Studio command prompt as an administrator and from there I ran the cmake-gui.exe

Then everything worked as it was supposed to.

How to get a float result by dividing two integer values using T-SQL?

Looks like this trick works in SQL Server and is shorter (based in previous answers)

SELECT 1.0*MyInt1/MyInt2

Or:

SELECT (1.0*MyInt1)/MyInt2

Setting a spinner onClickListener() in Android

Whenever you have to perform some action on the click of the Spinner in Android, use the following method.

mspUserState.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatIsRequired();
        }
        return false;
    }
});

One thing to keep in mind is always to return False while using the above method. If you will return True then the dropdown items of the spinner will not be displayed on clicking the Spinner.

How to send a JSON object using html form data

HTML provides no way to generate JSON from form data.

If you really want to handle it from the client, then you would have to resort to using JavaScript to:

  1. gather your data from the form via DOM
  2. organise it in an object or array
  3. generate JSON with JSON.stringify
  4. POST it with XMLHttpRequest

You'd probably be better off sticking to application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.


Update in response to major rewrite of the question…

  • Your JS has no readystatechange handler, so you do nothing with the response
  • You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

In scikit version 0.22, you can do it like this

from sklearn.metrics import multilabel_confusion_matrix

y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]

mcm = multilabel_confusion_matrix(y_true, y_pred,labels=["ant", "bird", "cat"])

tn = mcm[:, 0, 0]
tp = mcm[:, 1, 1]
fn = mcm[:, 1, 0]
fp = mcm[:, 0, 1]

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Is there a "previous sibling" selector?

I had the same question, but then I had a "duh" moment. Instead of writing

x ~ y

write

y ~ x

Obviously this matches "x" instead of "y", but it answers the "is there a match?" question, and simple DOM traversal may get you to the right element more efficiently than looping in javascript.

I realize that the original question was a CSS question so this answer is probably completely irrelevant, but other Javascript users may stumble on the question via search like I did.

How to toggle boolean state of react component?

Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

In your case:

this.setState(prevState => ({
  check: !prevState.check
}));

See docs


Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);

How to remove numbers from a string?

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

Demo

Test

_x000D_
_x000D_
function non_digit_string(str) {_x000D_
 const regex = /\D+/g;_x000D_
 let m;_x000D_
_x000D_
 non_digit_arr = [];_x000D_
 while ((m = regex.exec(str)) !== null) {_x000D_
  // This is necessary to avoid infinite loops with zero-width matches_x000D_
  if (m.index === regex.lastIndex) {_x000D_
   regex.lastIndex++;_x000D_
  }_x000D_
_x000D_
_x000D_
  m.forEach((match, groupIndex) => {_x000D_
   if (match.trim() != '') {_x000D_
    non_digit_arr.push(match.trim());_x000D_
   }_x000D_
  });_x000D_
 }_x000D_
 return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

How to pass a value to razor variable from javascript variable?

Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:

How do I create a timer in WPF?

In WPF, you use a DispatcherTimer.

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

How do I do word Stemming or Lemmatization?

I use stanford nlp to perform lemmatization. I have been stuck up with a similar problem in the last few days. All thanks to stackoverflow to help me solve the issue .

import java.util.*; 
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.*; 
import edu.stanford.nlp.ling.CoreAnnotations.*;  

public class example
{
    public static void main(String[] args)
    {
        Properties props = new Properties(); 
        props.put("annotators", "tokenize, ssplit, pos, lemma"); 
        pipeline = new StanfordCoreNLP(props, false);
        String text = /* the string you want */; 
        Annotation document = pipeline.process(text);  

        for(CoreMap sentence: document.get(SentencesAnnotation.class))
        {    
            for(CoreLabel token: sentence.get(TokensAnnotation.class))
            {       
                String word = token.get(TextAnnotation.class);      
                String lemma = token.get(LemmaAnnotation.class); 
                System.out.println("lemmatized version :" + lemma);
            }
        }
    }
}

It also might be a good idea to use stopwords to minimize output lemmas if it's used later in classificator. Please take a look at coreNlp extension written by John Conwell.

How to define a circle shape in an Android XML drawable file?

Here's a simple circle_background.xml for pre-material:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="@color/color_accent_dark" />
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/color_accent" />
        </shape>
    </item>
</selector>

You can use with the attribute 'android:background="@drawable/circle_background" in your button's layout definition

Using CMake to generate Visual Studio C++ project files

CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.

Adding and removing source files is just a matter of modifying the CMakeLists.txt which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).

The following link explains CMake and Visual Studio specific behavior very well.

CMake and Visual Studio

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

Get skin path in Magento?

The way that Magento themes handle actual url's is as such (in view partials - phtml files):

echo $this->getSkinUrl('images/logo.png');

If you need the actual base path on disk to the image directory use:

echo Mage::getBaseDir('skin');

Some more base directory types are available in this great blog post:

http://alanstorm.com/magento_base_directories

Difference between "@id/" and "@+id/" in Android

From the Developer Guide:

android:id="@+id/my_button"

The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:

android:id="@android:id/empty"

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

If you are using hand inputted data, you can enter your data as mm:ss,0 or mm:ss.0 depending on your language/region selection instead of 00:mm:ss.

You need to specify your cell format as [m]:ss if you like to see all minutes seconds format instead of hours minutes seconds format.

Get total of Pandas column

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

Set select option 'selected', by value

Try this. Simple yet effective javaScript + jQuery the lethal combo.

SelectComponent :

<select id="YourSelectComponentID">
            <option value="0">Apple</option>
            <option value="2">Banana</option>
            <option value="3">Cat</option>
            <option value="4">Dolphin</option>
</select>

Selection :

document.getElementById("YourSelectComponentID").value = 4;

Now your option 4 will be selected. You can do this, to select the values on start by default.

$(function(){
   document.getElementById("YourSelectComponentID").value = 4;
});

or create a simple function put the line in it and call the function on anyEvent to select the option

A mixture of jQuery + javaScript does the magic....

How to remove a row from JTable?

If you need a simple working solution, try using DefaultTableModel.

If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.

For example, if you have used Vector, then it may be something like this:

public class SimpleTableModel extends AbstractTableModel {
    private Vector<String> columnNames = new Vector<String>();
    // Each value in the vector is a row; String[] - row data;
    private Vector<String[]> data = new Vector<String[]>();

    ...

    public String getValueAt(int row, int col) {
        return data.get(row)[col];
    }

    ...

    public void removeRow(int row) {
        data.removeElementAt(row);
    }
}

If you have used List, then it would be very much alike:

// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();

public void removeRow(int row) {
    data.remove(row);
}

HashMap:

//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();

public void removeRow(Integer row) {
    data.remove(row);
}

And if you are using arrays like this one

String[][] data = { { "a", "b" }, { "c", "d" } };

then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.

For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.

Reading the selected value from asp:RadioButtonList using jQuery

The simple way to retrieve checked value of RadioButtonList1 is:

$('#RadioButtonList1 input:checked').val()

Edit by Tim:

where RadioButtonList1 must be the ClientID of the RadioButtonList

var rblSelectedValue = $("#<%= RadioButtonList1.ClientID %> input:checked"); 

Adding rows to dataset

DataSet myDataset = new DataSet();

DataTable customers = myDataset.Tables.Add("Customers");

customers.Columns.Add("Name");
customers.Columns.Add("Age");

customers.Rows.Add("Chris", "25");

//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
    currentRow = myCustomers.Rows[i];
    listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));    
}

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

Better way to check if a Path is a File or a Directory?

I use the following, it also tests the extension which means it can be used for testing if the path supplied is a file but a file that doesn't exist.

private static bool isDirectory(string path)
{
    bool result = true;
    System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
    if (fileTest.Exists == true)
    {
        result = false;
    }
    else
    {
        if (fileTest.Extension != "")
        {
            result = false;
        }
    }
    return result;
}

What is the meaning of "this" in Java?

It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:

System.out.println(this);

Note that your usage of "global variable" is somewhat off... if you're using this.variableName then by definition it's not a global variable - it's a variable specific to this particular instance.

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

Error: Cannot match any routes. URL Segment: - Angular 2

Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx"> The resulting contents are :

Component1.html

<nav>
    <a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
    <router-outlet></router-outlet>

Component2.html

 <a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ...       </a>
 <a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]">   In Two...Go to 4 ...</a>

 <router-outlet name="nameThree"></router-outlet>
 <router-outlet name="nameFour"></router-outlet>

The '/two' represents the parent component and ['three']and ['four'] represents the link to the respective children of component2 . Component3.html and Component4.html are the same as in the question.

router.module.ts

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [

        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree'
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        }
    ]
},];

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Is there a combination of "LIKE" and "IN" in SQL?

Use an inner join instead:

SELECT ...
FROM SomeTable
JOIN
(SELECT 'bla%' AS Pattern 
UNION ALL SELECT '%foo%'
UNION ALL SELECT 'batz%'
UNION ALL SELECT 'abc'
) AS Patterns
ON SomeTable.SomeColumn LIKE Patterns.Pattern

How to capture Curl output to a file?

If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.

curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"

Iterating through a List Object in JSP

you can read empList directly in forEach tag.Try this

 <table>
       <c:forEach items="${sessionScope.empList}" var="employee">
            <tr>
                <td>Employee ID: <c:out value="${employee.eid}"/></td>
                <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
            </tr>
        </c:forEach>
    </table>

What is the difference between a .cpp file and a .h file?

A header (.h, .hpp, ...) file contains

  • Class definitions ( class X { ... }; )
  • Inline function definitions ( inline int get_cpus() { ... } )
  • Function declarations ( void help(); )
  • Object declarations ( extern int debug_enabled; )

A source file (.c, .cpp, .cxx) contains

  • Function definitions ( void help() { ... } or void X::f() { ... } )
  • Object definitions ( int debug_enabled = 1; )

However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type> for gcc. Like -x c++ ).

Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.

Superscript in Python plots

You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula).

You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc.

For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $e^{\sin(\omega\phi)}$',
       xlabel='meters $10^1$', ylabel=r'Hertz $(\frac{1}{s})$')
plt.show()

enter image description here

If you don't want the superscripted text to be in a different font than the rest of the text, use \mathregular (or equivalently \mathdefault). Some symbols won't be available, but most will. This is especially useful for simple superscripts like yours, where you want the expression to blend in with the rest of the text.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $\mathregular{e^{\sin(\omega\phi)}}$',
       xlabel='meters $\mathregular{10^1}$',
       ylabel=r'Hertz $\mathregular{(\frac{1}{s})}$')
plt.show()

enter image description here

For more information (and a general overview of matplotlib's "mathtext"), see: http://matplotlib.org/users/mathtext.html

How would you make a comma-separated string from a list of strings?

",".join(l) will not work for all cases. I'd suggest using the csv module with StringIO

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

drag drop files into standard html file input

Few years later, I've built this library to do drop files into any HTML element.

You can use it like

const Droppable = require('droppable');

const droppable = new Droppable({
    element: document.querySelector('#my-droppable-element')
})

droppable.onFilesDropped((files) => {
    console.log('Files were dropped:', files);
});

// Clean up when you're done!
droppable.destroy();

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

Running unittest with typical test directory structure

It's possible to use wrapper which runs selected or all tests.

For instance:

./run_tests antigravity/*.py

or to run all tests recursively use globbing (tests/**/*.py) (enable by shopt -s globstar).

The wrapper can basically use argparse to parse the arguments like:

parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*')

Then load all the tests:

for filename in args.files:
    exec(open(filename).read())

then add them into your test suite (using inspect):

alltests = unittest.TestSuite()
for name, obj in inspect.getmembers(sys.modules[__name__]):
    if inspect.isclass(obj) and name.startswith("FooTest"):
        alltests.addTest(unittest.makeSuite(obj))

and run them:

result = unittest.TextTestRunner(verbosity=2).run(alltests)

Check this example for more details.

See also: How to run all Python unit tests in a directory?

How can I get Git to follow symlinks?

I'm using Git 1.5.4.3 and it's following the passed symlink if it has a trailing slash. E.g.

# Adds the symlink itself
$ git add symlink

# Follows symlink and adds the denoted directory's contents
$ git add symlink/

How do I convert a pandas Series or index to a Numpy array?

I converted the pandas dataframe to list and then used the basic list.index(). Something like this:

dd = list(zone[0]) #Where zone[0] is some specific column of the table
idx = dd.index(filename[i])

You have you index value as idx.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Elegant way to check for missing packages and install them?

Here's my code for it:

packages <- c("dplyr", "gridBase", "gridExtra")
package_loader <- function(x){
    for (i in 1:length(x)){
        if (!identical((x[i], installed.packages()[x[i],1])){
            install.packages(x[i], dep = TRUE)
        } else {
            require(x[i], character.only = TRUE)
        }
    }
}
package_loader(packages)

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

Iteration ng-repeat only X times in AngularJs

This is the simplest workaround I could think of.

<span ng-repeat="n in [].constructor(5) track by $index">
{{$index}}
</span>

Here's a Plunker example.

How to retrieve absolute path given relative

Eugen's answer didn't quite work for me but this did:

    absolute="$(cd $(dirname \"$file\"); pwd)/$(basename \"$file\")"

Side note, your current working directory is unaffected.

How does "cat << EOF" work in bash?

In your case, "EOF" is known as a "Here Tag". Basically <<Here tells the shell that you are going to enter a multiline string until the "tag" Here. You can name this tag as you want, it's often EOF or STOP.

Some rules about the Here tags:

  1. The tag can be any string, uppercase or lowercase, though most people use uppercase by convention.
  2. The tag will not be considered as a Here tag if there are other words in that line. In this case, it will merely be considered part of the string. The tag should be by itself on a separate line, to be considered a tag.
  3. The tag should have no leading or trailing spaces in that line to be considered a tag. Otherwise it will be considered as part of the string.

example:

$ cat >> test <<HERE
> Hello world HERE <-- Not by itself on a separate line -> not considered end of string
> This is a test
>  HERE <-- Leading space, so not considered end of string
> and a new line
> HERE <-- Now we have the end of the string

"This SqlTransaction has completed; it is no longer usable."... configuration error?

In my case , I've some codes which needs to execute after committing the transaction at the same try catch block.One of the code threw an error then try block handed over the error to it's catch block which contains the transaction rollback. It will show the similar error. For example look at the code structure below :

SqlTransaction trans = null;

try{
 trans = Con.BeginTransaction();
// your codes

  trans.Commit();
//your codes having errors

}
catch(Exception ex)
{
     trans.Rollback(); //transaction roll back
    // error message
}

finally
{ 
    // connection close
}

Hope it will someone :)

How to set up Automapper in ASP.NET Core

about theutz answer , there is no need to specify the IMapper mapper parrameter at the controllers constructor.

you can use the Mapper as it is a static member at any place of the code.

public class UserController : Controller {
   public someMethod()
   {
      Mapper.Map<User, UserDto>(user);
   }
}

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

varbinary to string on SQL Server

Have a go at the below as I was struggling to

bcp "SELECT CAST(BINARYCOL AS VARCHAR(MAX)) FROM OLTP_TABLE WHERE ID=123123 AND COMPANYID=123" 
queryout "C:\Users\USER\Documents\ps_scripts\res.txt" -c -S myserver.db.com  -U admin -P password

Reference: original post

Adding devices to team provisioning profile

login to developer account of apple and open the provision profile that you have selected in settings and add the device . The device will automatically displayed if connected to PC.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Instead of detecting the keyboard, try to detect the size of the window

If the height of the window was reduced, and the width is still the same, it means that the keyboard is on. Else the keyboard is off, you can also add to that, test if any input field is on focus or not.

Try this code for example.

var last_h = $(window).height(); //  store the intial height.
var last_w = $(window).width(); //  store the intial width.
var keyboard_is_on = false;
$(window).resize(function () {
    if ($("input").is(":focus")) {
        keyboard_is_on =
               ((last_w == $(window).width()) && (last_h > $(window).height()));
    }   
});     

Gradle proxy configuration

Try the following:

gradle -Dhttp.proxyHost=yourProxy -Dhttp.proxyPort=yourPort -Dhttp.proxyUser=usernameProxy -Dhttp.proxyPassword=yourPassoword

Generate random numbers using C++11 random library

Here is some resource you can read about pseudo-random number generator.

https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Basically, random numbers in computer need a seed (this number can be the current system time).

Replace

std::default_random_engine generator;

By

std::default_random_engine generator(<some seed number>);

Deprecated: mysql_connect()

Its just a warning that is telling you to start using newer methods of connecting to your db such as pdo objects

http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338

The manual is here

http://www.php.net/manual/en/book.pdo.php

jQuery append text inside of an existing paragraph tag

I have just discovered a way to append text and its working fine at least.

 var text = 'Put any text here';
 $('#text').append(text);

You can change text according to your need.

Hope this helps.

insert a NOT NULL column to an existing table

Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"

How do I disable form fields using CSS?

You can't use CSS to disable Textbox. solution would be HTML Attribute.

disabled="disabled"

pip cannot install anything

I faced the same issue and this error is because of 'Proxy Setting'. The syntax below helped me in resolving it successfully:

sudo pip --proxy=http://username:password@proxyURL:portNumber install yolk

How to use placeholder as default value in select2 framework

Just add this class in your .css file.

.select2-search__field{width:100% !important;}

How to insert new cell into UITableView in Swift

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

If You have Legacy Cordova framework having issues with NPM and Cordova command. I would suggest the below option.

Create file android/res/xml/network_security_config.xml -

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    <base-config cleartextTrafficPermitted="true" />
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
    </domain-config>
    </network-security-config>

AndroidManifest.xml -

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
        <application
            ...
            android:networkSecurityConfig="@xml/network_security_config"
            ...>
            ...
        </application>
    </manifest>

What do multiple arrow functions mean in javascript?

Understanding the available syntaxes of arrow functions will give you an understanding of what behaviour they are introducing when 'chained' like in the examples you provided.

When an arrow function is written without block braces, with or without multiple parameters, the expression that constitutes the function's body is implicitly returned. In your example, that expression is another arrow function.

No arrow funcs              Implicitly return `e=>{…}`    Explicitly return `e=>{…}` 
---------------------------------------------------------------------------------
function (field) {         |  field => e => {            |  field => {
  return function (e) {    |                             |    return e => {
      e.preventDefault()   |    e.preventDefault()       |      e.preventDefault()
  }                        |                             |    }
}                          |  }                          |  }

Another advantage of writing anonymous functions using the arrow syntax is that they are bound lexically to the scope in which they are defined. From 'Arrow functions' on MDN:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.

This is particularly pertinent in your example considering that it is taken from a application. As as pointed out by @naomik, in React you often access a component's member functions using this. For example:

Unbound                     Explicitly bound            Implicitly bound 
------------------------------------------------------------------------------
function (field) {         |  function (field) {       |  field => e => {
  return function (e) {    |    return function (e) {  |    
      this.setState(...)   |      this.setState(...)   |    this.setState(...)
  }                        |    }.bind(this)           |    
}                          |  }.bind(this)             |  }

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);

this is the best Solution to get the path what is exactly need for now

How to find the port for MS SQL Server 2008?

I came across this because I just had problems creating a remote connection and couldn't understand why setting up 1433 port in firewall is not doing the job. I finally have the full picture now, so I thought I should share.

First of all is a must to enable "TCP/IP" using the SQL Server Configuration Manager under Protocols for SQLEXPRESS!

When a named instance is used ("SQLExpress" in this case), this will listen on a dynamic port. To find this dynamic port you have couple of options; to name a few:

  • checking ERRORLOG of SQL Server located in '{MS SQL Server Path}\{MS SQL Server instance name}\MSSQL\Log' (inside you'll find a line similar to this: "2013-07-25 10:30:36.83 Server Server is listening on [ 'any' <ipv4> 51118]" --> so 51118 is the dynamic port in this case.

  • checking registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\{MSSQL instance name}\MSSQLServer\SuperSocketNetLib\Tcp\IPAll, for my case TcpDynamicPorts=51118.

    Edit: {MSSQL instance name} is something like: MSSQL10_50.SQLEXPRESS, not only SQLEXPRESS

Of course, allowing this TCP port in firewall and creating a remote connection by passing in: "x.x.x.x,51118" (where x.x.x.x is the server ip) already solves it at this point.

But then I wanted to connect remotely by passing in the instance name (e.g: x.x.x.x\SQLExpress). This is when SQL Browser service comes into play. This is the unit which resolves the instance name into the 51118 port. SQL Browser service listens on UDP port 1434 (standard & static), so I had to allow this also in server's firewall.

To extend a bit the actual answer: if someone else doesn't like dynamic ports and wants a static port for his SQL Server instance, should try this link.

How to break/exit from a each() function in JQuery?

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

How to use apply a custom drawable to RadioButton?

You should set android:button="@null" instead of "null".

You were soo close!

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How to properly add include directories with CMake

I had the same problem.

My project directory was like this:

    --project
    ---Classes
    ----Application
    -----.h and .c files
    ----OtherFolders
    --main.cpp

And what I used to include the files in all those folders:

    file(GLOB source_files
            "*.h"
            "*.cpp"
            "Classes/*/*.cpp"
            "Classes/*/*.h"
    )

    add_executable(Server ${source_files})

And it totally worked.

How to read the Stock CPU Usage data

This should be the Unix load average. Wikipedia has a nice article about this.

The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes

How can I use a for each loop on an array?

Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something (element)
    Next element
End Sub


Sub do_something(ByVal e As String)

End Sub

The other option is to convert the variant to a string before passing it.

  do_something CStr(element)

How to generate a random number between 0 and 1?

In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.

It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG

double r2()
{
    return (double)rand() / (double)RAND_MAX ;
}

Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.

bootstrap 3 navbar collapse button not working

In <body> you should have two <script> tags:

<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="js/bootstrap.js"></script>

The first one will load jQuery from the CDN, and second one will load Bootstrap's Javascript from a local directory (in this case it's a directory called js).

Style the first <td> column of a table differently

You could use the n-th child selector.

to target the nth element you could then use:

td:nth-child(n) {  
  /* your stuff here */
}

(where n starts at 1)

Changing CSS style from ASP.NET code

If your div is an ASP.NET control with runat="server" then AviewAnew's answer should do it. If it's just an HTML div, then you'd probably want to use JavaScript. Can you add the actual div tag to your question?