Programs & Examples On #Swiz

Select current date by default in ASP.Net Calendar control

I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.

These now all work:-

<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>

Datatype for storing ip address in SQL Server

For people using .NET can use IPAddress class to parse IPv4/IPv6 string and store it as a VARBINARY(16). Can use the same class to convert byte[] to string. If want to convert the VARBINARY in SQL:

--SELECT 
--  dbo.varbinaryToIpString(CAST(0x7F000001 AS VARBINARY(4))) IPv4,
--  dbo.varbinaryToIpString(CAST(0x20010DB885A3000000008A2E03707334 AS VARBINARY(16))) IPv6

--ALTER 
CREATE
FUNCTION dbo.varbinaryToIpString
(
    @varbinaryValue VARBINARY(16)
)
RETURNS VARCHAR(39)
AS
BEGIN
    IF @varbinaryValue IS NULL
        RETURN NULL
    IF DATALENGTH(@varbinaryValue) = 4
    BEGIN
        RETURN 
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 1, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 2, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 3, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 4, 1)))
    END
    IF DATALENGTH(@varbinaryValue) = 16
    BEGIN
        RETURN 
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  1, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  3, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  5, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  7, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  9, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 11, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 13, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 15, 2)
    END

    RETURN 'Invalid'
END

How to echo with different colors in the Windows command line

You can use the color command to change the color of the whole console

Color 0F

Is black and white

Color 0A 

Is black and green

Powershell: count members of a AD group

easy way to do it: To get the actual user count:

$ADInfo = Get-ADGroup -Identity '<groupname>' -Properties Members
$AdInfo.Members.Count

and you get the count easily, it is pretty fast as well for 20k+ users too

How to recover the deleted files using "rm -R" command in linux server?

Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!

Some restore utility: http://www.ubuntugeek.com/recover-deleted-files-with-foremostscalpel-in-ubuntu.html

Forum where this was previously answered: http://webcache.googleusercontent.com/search?q=cache:m4hiPw-_GekJ:ubuntuforums.org/archive/index.php/t-1134955.html+&cd=1&hl=en&ct=clnk&gl=us

Eclipse: Set maximum line length for auto formatting?

for XML line width, update preferences > XML > XML Files > Editor > Line width

Remove a fixed prefix/suffix from a string in Bash

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"

$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}

$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor

Notes:

#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.

Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.

How to sort ArrayList<Long> in decreasing order?

The following approach will sort the list in descending order and also handles the 'null' values, just in case if you have any null values then Collections.sort() will throw NullPointerException

      Collections.sort(list, new Comparator<Long>() {
          public int compare(Long o1, Long o2) {
                  return o1==null?Integer.MAX_VALUE:o2==null?Integer.MIN_VALUE:o2.compareTo(o1);

        }
    });

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

What is the most efficient way to check if a value exists in a NumPy array?

To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():

import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)

index = np.searchsorted(data, values)
print data[index] == values

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

Set selected option of select box

I know this has an accepted answer, but in reading the replies on the answer, I see some things that I can clear up that might help other people having issues with events not triggering after a value change.

This will select the value in the drop-down:

$("#gate").val("gateway_2")

If this select element is using JQueryUI or other JQuery wrapper, use the refresh method of the wrapper to update the UI to show that the value has been selected. The below example is for JQueryUI, but you will have to look at the documentation for the wrapper you are using to determine the correct method for the refresh:

$("#gate").selectmenu("refresh");

If there is an event that needs to be triggered such as a change event, you will have to trigger that manually as changing the value does not fire the event. The event you need to fire depends on how the event was created:

If the event was created with JQuery i.e. $("#gate").on("change",function(){}) then trigger the event using the below method:

$("#gate").change();

If the event was created using a standard JavaScript event i.e. then trigger the event using the below method:

var JSElem = $("#gate")[0];
if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    JSElem.dispatchEvent(evt);
} else {
    JSElem.fireEvent("onchange");
}

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

UITableViewCell, show delete button on swipe

Swift 3

All you have to do is enable these two functions:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    return true

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        tableView.reloadData()
    }

}

Any way to select without causing locking in MySQL?

another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 

http://localhost/phpMyAdmin/ unable to connect

XAMPP by default uses http://localhost/phpmyadmin

It also requires you start both Apache and MySQL from the control panel (or as a service).

In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.

If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)

How can I access iframe elements with Javascript?

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

Free Barcode API for .NET

Could the Barcode Rendering Framework at Codeplex GitHub be of help?

Gradle finds wrong JAVA_HOME even though it's correctly set

I had the same problem, but I didnt find export command in line 70 in gradle file for the latest version 2.13, but I understand a silly mistake there, that is following,

If you don't find line 70 with export command in gradle file in your gradle folder/bin/ , then check your ~/.bashrc, if you find export JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64/bin/java, then remove /bin/java from this line, like JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64, and it in path>>> instead of this export PATH=$PATH:$HOME/bin:JAVA_HOME/, it will be export PATH=$PATH:$HOME/bin:JAVA_HOME/bin/java. Then run source ~/.bashrc.

The reason is, if you check your gradle file, you will find in line 70 (if there's no export command) or in line 75,

JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

That means /bin/java is already there, so it needs to be substracted from JAVA_HOME path.

That happened in my case.

Split Strings into words with multiple word boundary delimiters

got same problem as @ooboo and find this topic @ghostdog74 inspired me, maybe someone finds my solution usefull

str1='adj:sg:nom:m1.m2.m3:pos'
splitat=':.'
''.join([ s if s not in splitat else ' ' for s in str1]).split()

input something in space place and split using same character if you dont want to split at spaces.

How to set a Default Route (To an Area) in MVC

Locating the different building blocks is done in the request life cycle. One of the first steps in the ASP.NET MVC request life cycle is mapping the requested URL to the correct controller action method. This process is referred to as routing. A default route is initialized in the Global.asax file and describes to the ASP.NET MVC framework how to handle a request. Double-clicking on the Global.asax file in the MvcApplication1 project will display the following code:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;

namespace MvcApplication1 {

   public class GlobalApplication : System.Web.HttpApplication
   {
       public static void RegisterRoutes(RouteCollection routes)
       {
           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

           routes.MapRoute(
               "Default",                                          // Route name
               "{controller}/{action}/{id}",                       // URL with parameters
               new { controller = "Home", action = "Index",
                     id = "" }  // Parameter defaults
           );

       }

       protected void Application_Start()
       {
           RegisterRoutes(RouteTable.Routes);
       }
   }

}

In the Application_Start() event handler, which is fired whenever the application is compiled or the web server is restarted, a route table is registered. The default route is named Default, and responds to a URL in the form of http://www.example.com/{controller}/{action}/{id}. The variables between { and } are populated with actual values from the request URL or with the default values if no override is present in the URL. This default route will map to the Home controller and to the Index action method, according to the default routing parameters. We won't have any other action with this routing map.

By default, all the possible URLs can be mapped through this default route. It is also possible to create our own routes. For example, let's map the URL http://www.example.com/Employee/Maarten to the Employee controller, the Show action, and the firstname parameter. The following code snippet can be inserted in the Global.asax file we've just opened. Because the ASP.NET MVC framework uses the first matching route, this code snippet should be inserted above the default route; otherwise the route will never be used.

routes.MapRoute(

   "EmployeeShow",                    // Route name
   "Employee/{firstname}",            // URL with parameters
    new {                             // Parameter defaults
       controller = "Employee",
       action = "Show", 
       firstname = "" 
   }  

);

Now, let's add the necessary components for this route. First of all, create a class named EmployeeController in the Controllers folder. You can do this by adding a new item to the project and selecting the MVC Controller Class template located under the Web | MVC category. Remove the Index action method, and replace it with a method or action named Show. This method accepts a firstname parameter and passes the data into the ViewData dictionary. This dictionary will be used by the view to display data.

The EmployeeController class will pass an Employee object to the view. This Employee class should be added in the Models folder (right-click on this folder and then select Add | Class from the context menu). Here's the code for the Employee class:

namespace MvcApplication1.Models {

   public class Employee
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email { get; set; }
   }

} 

Postgres FOR LOOP

I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:

https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/

I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:

https://www.postgresql.org/docs/current/tsm-system-rows.html

CREATE EXTENSION tsm_system_rows;

Then you can grab whatever number of rows you want:

select * from playtime tablesample system_rows (15);

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Please check this: https://jsfiddle.net/wazb1jks/3/

_x000D_
_x000D_
navigator.getUserMedia(mediaConstraints, function(stream) {_x000D_
    window.streamReference = stream;_x000D_
}, onMediaError);
_x000D_
_x000D_
_x000D_

Stop Recording

_x000D_
_x000D_
function stopStream() {_x000D_
    if (!window.streamReference) return;_x000D_
_x000D_
    window.streamReference.getAudioTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference.getVideoTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference = null;_x000D_
}
_x000D_
_x000D_
_x000D_

Remove a folder from git tracking

To forget directory recursively add /*/* to the path:

git update-index --assume-unchanged wordpress/wp-content/uploads/*/*

Using git rm --cached is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?

Sort an Array by keys based on another Array?

  • sort as requested
  • save for int-keys (because of array_replace)
  • don't return keys are not existing in inputArray
  • (optionally) filter keys no existing in given keyList

Code:

 /**
 * sort keys like in key list
 * filter: remove keys are not listed in keyList
 * ['c'=>'red', 'd'=>'2016-12-29'] = sortAndFilterKeys(['d'=>'2016-12-29', 'c'=>'red', 'a'=>3 ]], ['c', 'd', 'z']){
 *
 * @param array $inputArray
 * @param string[]|int[] $keyList
 * @param bool $removeUnknownKeys
 * @return array
 */
static public function sortAndFilterKeys($inputArray, $keyList, $removeUnknownKeys=true){
    $keysAsKeys = array_flip($keyList);
    $result = array_replace($keysAsKeys, $inputArray); // result = sorted keys + values from input + 
    $result = array_intersect_key($result, $inputArray); // remove keys are not existing in inputArray 
    if( $removeUnknownKeys ){
        $result = array_intersect_key($result, $keysAsKeys); // remove keys are not existing in keyList 
    }
    return $result;
}

Find a string between 2 known values

A Regex approach using lazy match and back-reference:

foreach (Match match in Regex.Matches(
        "morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
        @"<([^>]+)>(.*?)</\1>"))
{
    Console.WriteLine("{0}={1}",
        match.Groups[1].Value,
        match.Groups[2].Value);
}

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Representing null in JSON

This is a personal and situational choice. The important thing to remember is that the empty string and the number zero are conceptually distinct from null.

In the case of a count you probably always want some valid number (unless the count is unknown or undefined), but in the case of strings, who knows? The empty string could mean something in your application. Or maybe it doesn't. That's up to you to decide.

Java get String CompareTo as a comparator object

Solution for Java 8 based on java.util.Comparator.comparing(...):

Comparator<String> c = Comparator.comparing(String::toString);

or

Comparator<String> c = Comparator.comparing((String x) -> x);

Add item to array in VBScript

Arrays are not very dynamic in VBScript. You'll have to use the ReDim Preserve statement to grow the existing array so it can accommodate an extra item:

ReDim Preserve yourArray(UBound(yourArray) + 1)
yourArray(UBound(yourArray)) = "Watermelons"

DropdownList DataSource

It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.

How to implement a Keyword Search in MySQL?

I will explain the method i usally prefer:

First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.

1) Add a field (i usually call it "digest") where you store all the data from the table.

The field will look like:

"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word

I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.

2) Use the LIKE statement %keyword% on the digest field:

SELECT * FROM table WHERE digest LIKE %keyword%

you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:

SELECT * FROM table WHERE 
 digest LIKE %keyword1% AND 
 digest LIKE %keyword2% AND 
 digest LIKE %keyword3% ... 

Getting the minimum of two values in SQL

Building on the brilliant logic / code from mathematix and scottyc, I submit:

DECLARE @a INT, @b INT, @c INT = 0

WHILE @c < 100
    BEGIN
        SET @c += 1
        SET @a = ROUND(RAND()*100,0)-50
        SET @b = ROUND(RAND()*100,0)-50
        SELECT @a AS a, @b AS b,
            @a - ( ABS(@a-@b) + (@a-@b) ) / 2 AS MINab,
            @a + ( ABS(@b-@a) + (@b-@a) ) / 2 AS MAXab,
            CASE WHEN (@a <= @b AND @a = @a - ( ABS(@a-@b) + (@a-@b) ) / 2)
            OR (@a >= @b AND @a = @a + ( ABS(@b-@a) + (@b-@a) ) / 2)
            THEN 'Success' ELSE 'Failure' END AS Status
    END

Although the jump from scottyc's MIN function to the MAX function should have been obvious to me, it wasn't, so I've solved for it and included it here: SELECT @a + ( ABS(@b-@a) + (@b-@a) ) / 2. The randomly generated numbers, while not proof, should at least convince skeptics that both formulae are correct.

How to check if a registry value exists using C#?

public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
    RegistryKey root;
    switch (hive_HKLM_or_HKCU.ToUpper())
    {
        case "HKLM":
            root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
            break;
        case "HKCU":
            root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
            break;
        default:
            throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
    }

    return root.GetValue(valueName) != null;
}

Run a mySQL query as a cron job?

I personally find it easier use MySQL event scheduler than cron.

Enable it with

SET GLOBAL event_scheduler = ON;

and create an event like this:

CREATE EVENT name_of_event
ON SCHEDULE EVERY 1 DAY
STARTS '2014-01-18 00:00:00'
DO
DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7;

and that's it.

Read more about the syntax here and here is more general information about it.

Impact of Xcode build options "Enable bitcode" Yes/No

From the docs

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.

  • Are there any performance impacts if I enable / disable it?

The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.

There should not be any performance impacts.

What exactly is Python's file.flush() doing?

It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.

But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync() in those cases.

[1] http://docs.python.org/library/stdtypes.html

Node.js get file extension

I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)

Assume you are sending your data using HTTP POST:

POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----   WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png


------WebKitFormBoundaryPDULZN8DYK3VppPp--

Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).

Restify BodyParser converts this header in to a property with name type

File {
  domain: 
   Domain {
     domain: null,
     _events: { .... },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [ ... ] },
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 1047621,
  path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
  name: 'blob',
  **type: 'image/png'**,
  hash: null,
  lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
  _writeStream: 
  WriteStream {
   ... },
     writable: true,
     domain: 
     Domain {
        ...
     },
      _events: {},
      _eventsCount: 0,
     _maxListeners: undefined,
     path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
     fd: null,
     flags: 'w',
     mode: 438,
     start: undefined,
     pos: undefined,
     bytesWritten: 1047621,
     closed: true } 
}

You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search

  • mime
  • mime-types

and their usage is simple as well:

 app.post('/upload2', function (req, res) {
  console.log(mime.extension(req.files.image.type));
 }

above snippet will print png to console.

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

What is lexical scope?

Scope defines the area, where functions, variables and such are available. The availability of a variable for example is defined within its the context, let's say the function, file, or object, they are defined in. We usually call these local variables.

The lexical part means that you can derive the scope from reading the source code.

Lexical scope is also known as static scope.

Dynamic scope defines global variables that can be called or referenced from anywhere after being defined. Sometimes they are called global variables, even though global variables in most programmin languages are of lexical scope. This means, it can be derived from reading the code that the variable is available in this context. Maybe one has to follow a uses or includes clause to find the instatiation or definition, but the code/compiler knows about the variable in this place.

In dynamic scoping, by contrast, you search in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. "Dynamic" refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from. (see here)

To see an interesting example for dynamic scope see here.

For further details see here and here.

Some examples in Delphi/Object Pascal

Delphi has lexical scope.

unit Main;
uses aUnit;  // makes available all variables in interface section of aUnit

interface

  var aGlobal: string; // global in the scope of all units that use Main;
  type 
    TmyClass = class
      strict private aPrivateVar: Integer; // only known by objects of this class type
                                    // lexical: within class definition, 
                                    // reserved word private   
      public aPublicVar: double;    // known to everyboday that has access to a 
                                    // object of this class type
    end;

implementation

  var aLocalGlobal: string; // known to all functions following 
                            // the definition in this unit    

end.

The closest Delphi gets to dynamic scope is the RegisterClass()/GetClass() function pair. For its use see here.

Let's say that the time RegisterClass([TmyClass]) is called to register a certain class cannot be predicted by reading the code (it gets called in a button click method called by the user), code calling GetClass('TmyClass') will get a result or not. The call to RegisterClass() does not have to be in the lexical scope of the unit using GetClass();

Another possibility for dynamic scope are anonymous methods (closures) in Delphi 2009, as they know the variables of their calling function. It does not follow the calling path from there recursively and therefore is not fully dynamic.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

Is there a simple way to convert C++ enum to string?

Not so long ago I made some trick to have enums properly displayed in QComboBox and to have definition of enum and string representations as one statement

#pragma once
#include <boost/unordered_map.hpp>

namespace enumeration
{

   struct enumerator_base : boost::noncopyable
   {
      typedef
         boost::unordered_map<int, std::wstring>
         kv_storage_t;
      typedef
         kv_storage_t::value_type
         kv_type;
      kv_storage_t const & kv() const
      {
         return storage_;
      }

      LPCWSTR name(int i) const
      {
         kv_storage_t::const_iterator it = storage_.find(i);
         if(it != storage_.end())
            return it->second.c_str();
         return L"empty";
      }

   protected:
      kv_storage_t storage_;
   };

   template<class T>
   struct enumerator;

   template<class D>
   struct enum_singleton : enumerator_base
   {
      static enumerator_base const & instance()
      {
         static D inst;
         return inst;
      }
   };
}

#define QENUM_ENTRY(K, V, N)  K, N storage_.insert(std::make_pair((int)K, V));

#define QBEGIN_ENUM(NAME, C)   \
enum NAME                     \
{                             \
   C                          \
}                             \
};                            \
}                             \

#define QEND_ENUM(NAME) \
};                     \
namespace enumeration  \
{                      \
template<>             \
struct enumerator<NAME>\
   : enum_singleton< enumerator<NAME> >\
{                      \
   enumerator()        \
   {

//usage
/*
QBEGIN_ENUM(test_t,
   QENUM_ENTRY(test_entry_1, L"number uno",
   QENUM_ENTRY(test_entry_2, L"number dos",
   QENUM_ENTRY(test_entry_3, L"number tres",
QEND_ENUM(test_t)))))
*/

Now you've got enumeration::enum_singleton<your_enum>::instance() able to convert enums to strings. If you replace kv_storage_t with boost::bimap, you will also be able to do backward conversion. Common base class for converter was introduced to store it in Qt object, because Qt objects couldn't be templates

Previous appearance

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to monitor Java memory usage?

I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:

In theory, theory and practice are the same. In practice, they are not.

The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.

Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.

Deleting Row in SQLite in Android

if you are using SQLiteDatabase then there is a delete method

Definition of Delete

int delete (String table, String whereClause, String[] whereArgs)

Example Implementation

Now we can write a method called delete with argument as name

public void delete(String value) {
    db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{String.valueOf(value)});
}

if you want to delete all records then just pass null to the above method,

public void delete() {
    db.delete(DATABASE_TABLE, null, null);
}

Source Of Information

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

Selecting one row from MySQL using mysql_* API

It is working for me..

$show = mysql_query("SELECT data FROM wp_10_options WHERE
 option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
 echo $row['data'];

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

Laravel 4: how to "order by" using Eloquent ORM

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

Laravel form html with PUT method for PUT routes

You CAN add css clases, and any type of attributes you need to blade template, try this:

{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}

If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:

Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)

<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">

    <!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->

    <input name="_method" type="hidden" value="PUT">

    <div class="form-group">
        <textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
    </div>
</form>

Node.js Web Application examples/tutorials

Update

Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.

He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.

He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.

The demos can be found on his GitHub Account.

The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.

Original Answer

Well go ahead and built it yourself then.

Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.

One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.

Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.

What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.

I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.

Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).

Rome (or RoR) wasn't built over night, and neither will Node.js be.

Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)

How can I open a link in a new window?

Microsoft IE does not support a name as second argument.

window.open('url', 'window name', 'window settings');

Problem is window name. This will work:

window.open('url', '', 'window settings')

Microsoft only allows the following arguments, If using that argument at all:

  • _blank
  • _media
  • _parent
  • _search
  • _self
  • _top

Check this Microsoft site

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

How to get difference between two dates in Year/Month/Week/Day?

If you have to find the difference between originalDate and today’s date, Here is a reliable algorithm without so many condition checks.

  1. Declare a intermediateDate variable and initialize to the originalDate
  2. Find difference between years.(yearDiff)
  3. Add yearDiff to intermediateDate and check whether the value is greater than today’s date.
  4. If newly obtained intermediateDate > today’s date adjust the yearDiff and intermediateDate by one.
  5. Continue above steps for month and Days.

I have used System.Data.Linq functions to do find the year, month and day differences. Please find c# code below

        DateTime todaysDate = DateTime.Now;
        DateTime interimDate = originalDate;

        ///Find Year diff
        int yearDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffYear(interimDate, todaysDate);
        interimDate = interimDate.AddYears(yearDiff);
        if (interimDate > todaysDate)
        {
            yearDiff -= 1;
            interimDate = interimDate.AddYears(-1);
        }

        ///Find Month diff
        int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(interimDate, todaysDate);
        interimDate = interimDate.AddMonths(monthDiff);
        if (interimDate > todaysDate)
        {
            monthDiff -= 1;
            interimDate = interimDate.AddMonths(-1);
        }

        ///Find Day diff
        int daysDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(interimDate, todaysDate);

how to delete installed library form react native project

you have to check your linked project, in the new version of RN, don't need to link if you linked it cause a problem, I Fixed the problem by unlinked manually the dependency that I linked and re-run.

Is there a <meta> tag to turn off caching in all browsers?

It doesn't work in IE5, but that's not a big issue.

However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.

adb command for getting ip address assigned by operator

ip route | grep rmnet_data0 | cut -d" " -f1 | cut -d"/" -f1

Change rmnet_data0 to the desired nic, in my case, rmnet_data0 represents the data nic.

To get a list of the available nic's you can use ip route

How to define dimens.xml for every different screen size in android?

You can put dimens.xml in

1) values

2) values-hdpi

3) values-xhdpi

4) values-xxhdpi

And give different sizes in dimens.xml within corresponding folders according to densities.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

MySQL: Fastest way to count number of rows

This is the best query able to get the fastest results.

SELECT SQL_CALC_FOUND_ROWS 1 FROM `orders`;
SELECT FOUND_ROWS();

In my benchmark test: 0.448s

enter image description here

This query takes 4.835s

SELECT SQL_CALC_FOUND_ROWS * FROM `orders`;
SELECT FOUND_ROWS();

enter image description here

count * takes 25.675s

SELECT count(*) FROM `orders`;

enter image description here

How to add style from code behind?

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

The openssl extension is required for SSL/TLS protection

After trying everything, I finally managed to get this sorted. None of the above suggested solutions worked for me. My system is A PC Windows 10. In order to get this sorted I had to change the config.json file located here C:\Users\[Your User]\AppData\Roaming\Composer\. In there, you will find:

{
    "config": {
        "disable-tls": true},
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "http://repo.packagist.org" // this needs to change to 'https'
        }
    }
}

where you need to update the packagist repo url to point to the 'https' url version.

I am aware that the above selected solution will work for 95% of the cases, but as I said, that did not work for me. Hope this helps someone.

Happy coding!

Android center view in FrameLayout doesn't work

Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MovieActivity"
    android:id="@+id/mainContainerMovie"
    >


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3a3f51b5"
       />

    <ProgressBar
        android:id="@+id/movieprogressbar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>

How to convert enum value to int?

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(I've changed the names to be a bit more conventional and readable, btw.)

This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

Simple regular expression for a decimal with a precision of 2

In general, i.e. unlimited decimal places:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.

How to create Toast in Flutter?

There is a three-way to show toast on flutter App.
I will tell you about all three way that I know and choose which one you want to use. I would recommend the second one.

1: using of the external package.

this is the first method which is the easiest way to show toast on flutter app.

first of all, you have to add this package to pubspec.YAML

flutter_just_toast:^version_here

then import the package in the file where you want to show a toast.

'package:flutter_just_toast/flutter_just_toast.dart';

and the last step shows the toast.

Toast.show( message: "Your toast message", 
           duration: Delay.SHORT, 
           textColor: Colors.black);

2 : using official way.

this method is also simple but you have to deal with it. I am not saying that it is hard it is simple and clean I would recommend this method.

for this method, all you have to do show toast is using the below code.

Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("Sending Message"),
        ));

but remember that you have to use the scaffold context.

3: using native API.

now, this method does not make sense anymore when you already have the two methods above. using this method you have to write native code for android and iOS and then convert it to plugin and you are ready to go. this method will consume your time and you have to reinvent the wheel. which has already been invented.

"Cannot start compilation: the output path is not specified for module..."

If none of the above method worked then try this it worked for me.

Go to File > Project Structure> Project and then in Project Compiler Output click on the three dots and provide the path of your project name(name of the file) and then click on Apply and than on Ok.

"Parse Error : There is a problem parsing the package" while installing Android application

In my case I signed with only V2 signature (from Android 7 onward) but tried to install on 5 and 6. Adding V1 during ARK generation/signing fixed the issue.

See Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?.

What is the relative performance difference of if/else versus switch statement in Java?

That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.

Alternatively, you can also grab Polymorphism. First create some interface:

public interface Action { 
    void execute(String input);
}

And get hold of all implementations in some Map. You can do this either statically or dynamically:

Map<String, Action> actions = new HashMap<String, Action>();

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):

actions.get(name).execute(input);

It might be microslower than if/else or switch, but the code is at least far better maintainable.

As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

Set default option in mat-select

HTML

<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
  <mat-option *ngFor="let obj of Array"  [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>

Now set your default value to

modeSelect

, where you are getting the values in Array variable.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

This happens to me every time I add a pod to the podfile.

I constantly try and find the problem but I just go round in circles again and again!

The error messages range, however the way to fix it is the same every time!

Comment out(#) ALL of the pods in the podfile and run pod install in terminal.

Then...

Uncomment out all of the pods in the podfile and run pod install again.

This has worked for me every single time!

Differences between socket.io and websockets

Misconceptions

There are few common misconceptions regarding WebSocket and Socket.IO:

  1. The first misconception is that using Socket.IO is significantly easier than using WebSocket which doesn't seem to be the case. See examples below.

  2. The second misconception is that WebSocket is not widely supported in the browsers. See below for more info.

  3. The third misconception is that Socket.IO downgrades the connection as a fallback on older browsers. It actually assumes that the browser is old and starts an AJAX connection to the server, that gets later upgraded on browsers supporting WebSocket, after some traffic is exchanged. See below for details.

My experiment

I wrote an npm module to demonstrate the difference between WebSocket and Socket.IO:

It is a simple example of server-side and client-side code - the client connects to the server using either WebSocket or Socket.IO and the server sends three messages in 1s intervals, which are added to the DOM by the client.

Server-side

Compare the server-side example of using WebSocket and Socket.IO to do the same in an Express.js app:

WebSocket Server

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

Socket.IO Server

Socket.IO server example using Express.js:

var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
  console.error('socket.io connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js

Client-side

Compare the client-side example of using WebSocket and Socket.IO to do the same in the browser:

WebSocket Client

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

Socket.IO Client

Socket.IO client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html

Network traffic

To see the difference in network traffic you can run my test. Here are the results that I got:

WebSocket Results

2 requests, 1.50 KB, 0.05 s

From those 2 requests:

  1. HTML page itself
  2. connection upgrade to WebSocket

(The connection upgrade request is visible on the developer tools with a 101 Switching Protocols response.)

Socket.IO Results

6 requests, 181.56 KB, 0.25 s

From those 6 requests:

  1. the HTML page itself
  2. Socket.IO's JavaScript (180 kilobytes)
  3. first long polling AJAX request
  4. second long polling AJAX request
  5. third long polling AJAX request
  6. connection upgrade to WebSocket

Screenshots

WebSocket results that I got on localhost:

WebSocket results - websocket-vs-socket.io module

Socket.IO results that I got on localhost:

Socket.IO results - websocket-vs-socket.io module

Test yourself

Quick start:

# Install:
npm i -g websocket-vs-socket.io
# Run the server:
websocket-vs-socket.io

Open http://localhost:3001/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the WebSocket version.

Open http://localhost:3002/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the Socket.IO version.

To uninstall:

# Uninstall:
npm rm -g websocket-vs-socket.io

Browser compatibility

As of June 2016 WebSocket works on everything except Opera Mini, including IE higher than 9.

This is the browser compatibility of WebSocket on Can I Use as of June 2016:

enter image description here

See http://caniuse.com/websockets for up-to-date info.

Change collations of all columns of all tables in SQL Server

Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)

SQL SCRIPT HERE:

BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'DATABASE_DEFAULT';

DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy 
INNER JOIN sys.objects  o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1

OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE tbl_cursor_changed CURSOR FOR
        SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
            , c.name column_name
            , t.Name data_type
            , c.max_length
            , c.column_id
        FROM sys.columns c
        JOIN sys.types t ON c.system_type_id = t.system_type_id
        LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
    ORDER BY c.column_id


    OPEN tbl_cursor_changed 
     FETCH NEXT FROM tbl_cursor_changed
    INTO @row_id, @column_name, @data_type, @max_length, @column_id



    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF (@max_length = -1) SET @max_length = 'MAX';
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            print @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR:'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM tbl_cursor_changed
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE tbl_cursor_changed
    DEALLOCATE tbl_cursor_changed

    FETCH NEXT FROM tbl_cursor
    INTO @schema, @table

END

CLOSE tbl_cursor
DEALLOCATE tbl_cursor

PRINT 'Collation For All Tables Done!'
END

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

How do I read a string entered by the user in C?

You should never use gets (or scanf with an unbounded string size) since that opens you up to buffer overflows. Use the fgets with a stdin handle since it allows you to limit the data that will be placed in your buffer.

Here's a little snippet I use for line input from the user:

#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.

You can test it with something like:

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        // Extra NL since my system doesn't output that on EOF.
        printf ("\nNo input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long [%s]\n", buff);
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

Can an Android Toast be longer than Toast.LENGTH_LONG?

Simply use SuperToast to make an elegant toast on any situation. Make your toast colourful. Edit your font color and also it's size. Hope it will be all in one for you.

What is the difference between jQuery: text() and html() ?

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

Where to use:

  • use .html() to operate on containers having html elements.
  • use .text() to modify text of elements usually having separate open and closing tags

Where not to use:

  • .text() method cannot be used on form inputs or scripts.

    • .val() for input or textarea elements.
    • .html() for value of a script element.
  • Picking up html content from .text() will convert the html tags into html entities.

Difference:

  • .text() can be used in both XML and HTML documents.
  • .html() is only for html documents.

Check this example on jsfiddle to see the differences in action

Example

How to match a substring in a string, ignoring case

Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True

Sleep function in Windows, using C

SleepEx function (see http://msdn.microsoft.com/en-us/library/ms686307.aspx) is the best choise if your program directly or indirectly creates windows (for example use some COM objects). In the simples cases you can also use Sleep.

How to list the contents of a package using YUM?

$ yum install -y yum-utils

$ repoquery -l packagename

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

i have tried this one and it worked for me. hope it works for others too.

  1. Open build.gradle module file
  2. downgrade you sdkversion from 25 to 24 or 23
  3. add 'multiDexEnabled true'
  4. comment this line : compile 'com.android.support:appcompat-v7:25.1.0' (if it's in 'dependencies')
  5. Sync your project and ready to go.

Here i have attached screenshot to explain things. Go through this steps

happy to help.

thanks.

What is the difference between statically typed and dynamically typed languages?

Static Typing: The languages such as Java and Scala are static typed.

The variables have to be defined and initialized before they are used in a code.

for ex. int x; x = 10;

System.out.println(x);

Dynamic Typing: Perl is an dynamic typed language.

Variables need not be initialized before they are used in code.

y=10; use this variable in the later part of code

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

Add click event on div tag using javascript

Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.

try if you really want to use class:

 document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};

or you may assign function in html itself:

<div class="drill_cursor" onclick='alert("1");'>
</div>

Why can't I shrink a transaction log file, even after backup?

Try creating another full backup after you backup the log w/ truncate_only (IIRC you should do this anyway to maintain the log chain). In simple recovery mode, your log shouldn't grow much anyway since it's effectively truncated after every transaction. Then try specifying the size you want the logfile to be, e.g.

-- shrink log file to c. 1 GB
DBCC SHRINKFILE (Wxlog0, 1000);

The TRUNCATEONLY option doesn't rearrange the pages inside the log file, so you might have an active page at the "end" of your file, which could prevent it from being shrunk.

You can also use DBCC SQLPERF(LOGSPACE) to make sure that there really is space in the log file to be freed.

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

How to get height of Keyboard?

Swift 4 and Constraints

To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.

@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}

@objc 
func keyboardWillAppear(notification: NSNotification?) {

    guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
        return
    }

    let keyboardHeight: CGFloat
    if #available(iOS 11.0, *) {
        keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
    } else {
        keyboardHeight = keyboardFrame.cgRectValue.height
    }

    tableViewBottomLayoutConstraint.constant = keyboardHeight
}

@objc 
func keyboardWillDisappear(notification: NSNotification?) {
    tableViewBottomLayoutConstraint.constant = 0.0
}

What ports does RabbitMQ use?

Port Access

Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:

4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools

5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS

25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.

15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)

61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)

1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled

15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)

15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)

Reference doc: https://www.rabbitmq.com/install-windows-manual.html

how to concatenate two dictionaries to create a new one in Python?

d4 = dict(d1.items() + d2.items() + d3.items())

alternatively (and supposedly faster):

d4 = dict(d1)
d4.update(d2)
d4.update(d3)

Previous SO question that both of these answers came from is here.

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

How to evaluate a boolean variable in an if block in bash?

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

Convert month name to month number in SQL Server

How about this:

SELECT MONTH('March' + ' 1 2014') 

Would return 3.

Creating a file name as a timestamp in a batch job

This works well with (my) German locale, should be possible to adjust it to your needs...

forfiles /p *PATH* /m *filepattern* /c "cmd /c ren @file 
%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_@file"

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

How to add/update an attribute to an HTML element using JavaScript?

Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory.

How to create a directory and give permission in single command

Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.

How to detect browser using angularjs?

Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.

So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).

However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.

I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059

Is there a RegExp.escape function in JavaScript?

The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).

If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (., ?, +, *, ^, $, |, \) or start something ((, [, {) is all you need:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

How to read XML response from a URL in java?

If you want to print XML directly onto the screen you can use TransformerFactory

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer xform = transformerFactory.newTransformer();

// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));

How do I parse a string with a decimal point to a double?

        var doublePattern = @"(?<integer>[0-9]+)(?:\,|\.)(?<fraction>[0-9]+)";
        var sourceDoubleString = "03444,44426";
        var match = Regex.Match(sourceDoubleString, doublePattern);

        var doubleResult = match.Success ? double.Parse(match.Groups["integer"].Value) + (match.Groups["fraction"].Value == null ? 0 : double.Parse(match.Groups["fraction"].Value) / Math.Pow(10, match.Groups["fraction"].Value.Length)): 0;
        Console.WriteLine("Double of string '{0}' is {1}", sourceDoubleString, doubleResult);

How to embed an autoplaying YouTube video in an iframe?

August 2018 I didn't find a working example on the iframe implementation. Other questions were related to Chrome only, which gave it away a little.

You'll have to mute sound mute=1 in order to autoplay on Chrome. FF and IE seem to be working just fine using autoplay=1 as parameter.

<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Facebook Callback appends '#_=_' to Return URL

With angular and angular ui router, you can fix this

    app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {

      // Make a trailing slash optional for all routes
      // - Note: You'll need to specify all urls with a trailing slash if you use this method.
      $urlRouterProvider.rule(function ($injector, $location) {
        /***
        Angular misbehaves when the URL contains a "#_=_" hash.

        From Facebook:
          Change in Session Redirect Behavior
          This week, we started adding a fragment #_=_ to the redirect_uri when this field is left blank.
          Please ensure that your app can handle this behavior.

        Fix:
          http://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url#answer-7297873
        ***/
        if ($location.hash() === '_=_'){
          $location.hash(null);
        }

        var path = $location.url();

        // check to see if the path already has a slash where it should be
        if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
          return;
        }
        else if (path.indexOf('?') > -1) {
          $location.replace().path(path.replace('?', '/?'));
        }
        else {
          $location.replace().path(path + '/');
        }
      });

      // etc ...
    });
});

Convert Map<String,Object> to Map<String,String>

Use the Java 8 way of converting a Map<String, Object> to Map<String, String>. This solution handles null values.

Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
    .filter(entry -> entry.getValue() != null)
    .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));

Get all directories within directory nodejs

 var getDirectories = (rootdir , cb) => {
    fs.readdir(rootdir, (err, files) => {
        if(err) throw err ;
        var dirs = files.map(filename => path.join(rootdir,filename)).filter( pathname => fs.statSync(pathname).isDirectory());
        return cb(dirs);
    })

 }
 getDirectories( myDirectories => console.log(myDirectories));``

How to remove unused dependencies from composer?

following commands will do the same perfectly

rm -rf vendor

composer install 

Chart.js canvas resize

What's happening is Chart.js multiplies the size of the canvas when it is called then attempts to scale it back down using CSS, the purpose being to provide higher resolution graphs for high-dpi devices.

The problem is it doesn't realize it has already done this, so when called successive times, it multiplies the already (doubled or whatever) size AGAIN until things start to break. (What's actually happening is it is checking whether it should add more pixels to the canvas by changing the DOM attribute for width and height, if it should, multiplying it by some factor, usually 2, then changing that, and then changing the css style attribute to maintain the same size on the page.)

For example, when you run it once and your canvas width and height are set to 300, it sets them to 600, then changes the style attribute to 300... but if you run it again, it sees that the DOM width and height are 600 (check the other answer to this question to see why) and then sets it to 1200 and the css width and height to 600.

Not the most elegant solution, but I solved this problem while maintaining the enhanced resolution for retina devices by simply setting the width and height of the canvas manually before each successive call to Chart.js

var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);

Access a URL and read Data with R

scan can read from a web page automatically; you don't necessarily have to mess with connections.

How to pop an alert message box using PHP?

You could use Javascript:

// This is in the PHP file and sends a Javascript alert to the client
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";

How to calculate 1st and 3rd quartiles?

In my efforts to learn object-oriented programming alongside learning statistics, I made this, maybe you'll find it useful:

samplesCourse = [9, 10, 10, 11, 13, 15, 16, 19, 19, 21, 23, 28, 30, 33, 34, 36, 44, 45, 47, 60]

class sampleSet:
    def __init__(self, sampleList):
        self.sampleList = sampleList
        self.interList = list(sampleList) # interList is sampleList alias; alias used to maintain integrity of original sampleList

    def find_median(self):
        self.median = 0

        if len(self.sampleList) % 2 == 0:
            # find median for even-numbered sample list length
            self.medL = self.interList[int(len(self.interList)/2)-1]
            self.medU = self.interList[int(len(self.interList)/2)]
            self.median = (self.medL + self.medU)/2

        else:
            # find median for odd-numbered sample list length
            self.median = self.interList[int((len(self.interList)-1)/2)]
        return self.median

    def find_1stQuartile(self, median):
        self.lower50List = []
        self.Q1 = 0

        # break out lower 50 percentile from sampleList
        if len(self.interList) % 2 == 0:
            self.lower50List = self.interList[:int(len(self.interList)/2)]
        else:
            # drop median to make list ready to divide into 50 percentiles
            self.interList.pop(interList.index(self.median))
            self.lower50List = self.interList[:int(len(self.interList)/2)]

        # find 1st quartile (median of lower 50 percentiles)
        if len(self.lower50List) % 2 == 0:
            self.Q1L = self.lower50List[int(len(self.lower50List)/2)-1]
            self.Q1U = self.lower50List[int(len(self.lower50List)/2)]
            self.Q1 = (self.Q1L + self.Q1U)/2

        else:
            self.Q1 = self.lower50List[int((len(self.lower50List)-1)/2)]

        return self.Q1

    def find_3rdQuartile(self, median):
        self.upper50List = []
        self.Q3 = 0

        # break out upper 50 percentile from sampleList
        if len(self.sampleList) % 2 == 0:
            self.upper50List = self.interList[int(len(self.interList)/2):]
        else:
            self.interList.pop(interList.index(self.median))
            self.upper50List = self.interList[int(len(self.interList)/2):]

        # find 3rd quartile (median of upper 50 percentiles)
        if len(self.upper50List) % 2 == 0:
            self.Q3L = self.upper50List[int(len(self.upper50List)/2)-1]
            self.Q3U = self.upper50List[int(len(self.upper50List)/2)]
            self.Q3 = (self.Q3L + self.Q3U)/2

        else:
            self.Q3 = self.upper50List[int((len(self.upper50List)-1)/2)]

        return self.Q3

    def find_InterQuartileRange(self, Q1, Q3):
        self.IQR = self.Q3 - self.Q1
        return self.IQR

    def find_UpperFence(self, Q3, IQR):
        self.fence = self.Q3 + 1.5 * self.IQR
        return self.fence

samples = sampleSet(samplesCourse)
median = samples.find_median()
firstQ = samples.find_1stQuartile(median)
thirdQ = samples.find_3rdQuartile(median)
iqr = samples.find_InterQuartileRange(firstQ, thirdQ)
fence = samples.find_UpperFence(thirdQ, iqr)

print("Median is: ", median)
print("1st quartile is: ", firstQ)
print("3rd quartile is: ", thirdQ)
print("IQR is: ", iqr)
print("Upper fence is: ", fence)

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

To go ahead and get a point out there, instead of repeatedly using these:

[A-Za-z0-9 _]
[A-Za-z0-9]

I have two (hopefully better) replacements for those two:

[\w ]
[^\W_]

The first one matches any word character (alphanumeric and _, as well as Unicode) and the space. The second matches anything that isn't a non-word character or an underscore (alphanumeric only, as well as Unicode).

If you don't want Unicode matching, then stick with the other answers. But these just look easier on the eyes (in my opinion). Taking the "preferred" answer as of this writing and using the shorter regexes gives us:

^[\w ]*[^\W_][\w ]*$

Perhaps more readable, perhaps less. Certainly shorter. Your choice.

EDIT:

Just as a note, I am assuming Perl-style regexes here. Your regex engine may or may not support things like \w and \W.

EDIT 2:

Tested mine with the JS regex tester that someone linked to and some basic examples worked fine. Didn't do anything extensive, just wanted to make sure that \w and \W worked fine in JS.

EDIT 3:

Having tried to test some Unicode with the JS regex tester site, I've discovered the problem: that page uses ISO instead of Unicode. No wonder my Japanese input didn't match. Oh well, that shouldn't be difficult to fix:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Or so. I don't know what should be done as far as JavaScript, but I'm sure it's not hard.

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".

How can I check whether a option already exist in select by JQuery

It's help me :

  var key = 'Hallo';

   if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
   alert("option not exist!");

    $('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
    $('#chosen_b').val(key);
   $('#chosen_b').trigger("chosen:updated");
                         }
  });

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

javascript get x and y coordinates on mouse click

simple solution is this:

game.js:

document.addEventListener('click', printMousePos, true);
function printMousePos(e){

      cursorX = e.pageX;
      cursorY= e.pageY;
      $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}

How to move child element from one parent to another using jQuery

As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach function.

var element = $('#childNode').detach();
$('#parentNode').append(element);

Edit:

Igor Mukhin suggested an even shorter version in the comments below:

$("#childNode").detach().appendTo("#parentNode");

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

What is the Java ?: operator called and what does it do?

Its Ternary Operator(?:)

The ternary operator is an operator that takes three arguments. The first 
argument is a comparison argument, the second is the result upon a true 
comparison, and the third is the result upon a false comparison.

Tree data structure in C#

I am surprised nobody mentioned the possibility to use XML with Linq :

https://docs.microsoft.com/fr-fr/dotnet/standard/linq/create-xml-trees

XML is the most mature and flexible solution when it comes to using trees and Linq provides you with all the tools that you need. The configuration of your tree also gets much cleaner and user-friendly as you can simply use an XML file for the initialization.

If you need to work with objects, you can use XML serialization :

https://docs.microsoft.com/fr-fr/dotnet/standard/serialization/introducing-xml-serialization

char *array and char array[]

The declaration and initialization

char *array = "One good thing about music";

declares a pointer array and make it point to a constant array of 31 characters.

The declaration and initialization

char array[] = "One, good, thing, about, music";

declares an array of characters, containing 31 characters.

And yes, the size of the arrays is 31, as it includes the terminating '\0' character.


Laid out in memory, it will be something like this for the first:

+-------+     +------------------------------+
| array | --> | "One good thing about music" |
+-------+     +------------------------------+

And like this for the second:

+------------------------------+
| "One good thing about music" |
+------------------------------+

Arrays decays to pointers to the first element of an array. If you have an array like

char array[] = "One, good, thing, about, music";

then using plain array when a pointer is expected, it's the same as &array[0].

That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.

Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer) because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer you get the address of the pointer, but &array returns a pointer to the array. It should be noted that &array is very different from array (or its equivalent &array[0]). While both &array and &array[0] point to the same location, the types are different. Using the arrat above, &array is of type char (*)[31], while &array[0] is of type char *.


For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.

For example:

char array[] = "Foobar";  /* Declare an array of 7 characters */

With the above, you can access the fourth element (the 'b' character) using either

array[3]

or

*(array + 3)

And because addition is commutative, the last can also be expressed as

*(3 + array)

which leads to the fun syntax

3[array]

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

Is there a CSS selector for the first direct child only?

Found this question searching on Google. This will return the first child of a element with class container, regardless as to what type the child is.

.container > *:first-child
{
}

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

jQuery date/time picker

@David, thanks for the recommendation! @fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:

http://www.ama3.com/anytime/

Any problems, please let me know via the comment link on my website!

How to make a JSON call to a url?

DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.

Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/

your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }

In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.

Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.

It works, in any case.

Here's my implementation of DickFeynman's approach, in the the client:

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>

I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.

More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.

webpack: Module not found: Error: Can't resolve (with relative path)

I had a different problem. some of my includes were set to 'app/src/xxx/yyy' instead of '../xxx/yyy'

What properties can I use with event.target?

If you were to inspect the event.target with firebug or chrome's developer tools you would see for a span element (e.g. the following properties) it will have whatever properties any element has. It depends what the target element is:

event.target: HTMLSpanElement

attributes: NamedNodeMap
baseURI: "file:///C:/Test.html"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList
className: ""
clientHeight: 36
clientLeft: 1
clientTop: 1
clientWidth: 1443
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: Text
firstElementChild: null
hidden: false
id: ""
innerHTML: "click"
innerText: "click"
isContentEditable: false
lang: ""
lastChild: Text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 38
offsetLeft: 26
offsetParent: HTMLBodyElement
offsetTop: 62
offsetWidth: 1445
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
outerHTML: "<span>click</span>"
outerText: "click"
ownerDocument: HTMLDocument
parentElement: HTMLElement
parentNode: HTMLElement
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 36
scrollLeft: 0
scrollTop: 0
scrollWidth: 1443
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "click"
title: ""
webkitdropzone: ""
__proto__: HTMLSpanElement

Using LINQ to group a list of objects

is this what you want?

var grouped = CustomerList.GroupBy(m => m.GroupID).Select((n) => new { GroupId = n.Key, Items = n.ToList() });

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

How do I create a crontab through a script

As a correction to those suggesting crontab -l | crontab -: This does not work on every system. For example, I had to add a job to the root crontab on dozens of servers running an old version SUSE (don't ask why). Old SUSEs prepend comment lines to the output of crontab -l, making crontab -l | crontab - non-idempotent (Debian recognizes this problem in the crontab manpage and patched its version of Vixie Cron to change the default behaviour of crontab -l).

To edit crontabs programmatically on systems where crontab -l adds comments, you can try the following:

EDITOR=cat crontab -e > old_crontab; cat old_crontab new_job | crontab -

EDITOR=cat tells crontab to use cat as an editor (not the usual default vi), which doesn't change the file, but instead copies it to stdout. This might still fail if crontab - expects input in a format different from what crontab -e outputs. Do not try to replace the final crontab - with crontab -e - it will not work.

fatal: git-write-tree: error building trees

To follow up on malat's response, you can avoid losing changes by creating a patch and reapply it at a later time.

git diff --no-prefix > patch.txt
patch -p0 < patch.txt

Store your patch outside the repository folder for safety.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

I had the same issue connecting to a remote machine. but I managed to login as below:

ssh -p 22 myName@hostname

or:

ssh -l myName -p 22 hostname

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

How to set a Postgresql default value datestamp like 'YYYYMM'?

Why would you want to do this?

IMHO you should store the date as default type and if needed fetch it transforming to desired format.

You could get away with specifying column's format but with a view. I don't know other methods.

Edited:

Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:

create table sample_table ( id serial primary key, timestamp date); 

and than

create view v_example_table as select id, to_char(date, 'yyyymmmm');

And use v_example_table in your application.

Sublime Text 2 multiple line edit

It's fine to manually select each number for a small set of numbers like in your example, but for larger collections you can do a regex search which will do the work for you.

Ctrl + F will open the search bar.

Regex searches are enabled by clicking the ".*" button on the far left.

Type in "\d+" to search for all occurrences of 1 or more digits. Clicking the "Find All" button will select each of these numbers separately.

Then you can use Ctrl + Shift + L to convert the selection into multiple cursors. From here you can do as you like.

How do I upgrade PHP in Mac OS X?

to upgrade php7 to latest stable version brew upgrade php7 or for php5.X to latest stable version

brew upgrade php56

use brew list to check installed version

How do I resolve this "ORA-01109: database not open" error?

please run this script

ALTER DATABASE OPEN

How do I set/unset a cookie with jQuery?

I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:

EDIT: also added 'never expires' option if no day number is set

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

Set the cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 

How do I change the data type for a column in MySQL?

https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

You can also set a default value for the column just add the DEFAULT keyword followed by the value.

ALTER TABLE [table_name] MODIFY [column_name] [NEW DATA TYPE] DEFAULT [VALUE];

This is also working for MariaDB (tested version 10.2)

Is there any sed like utility for cmd.exe?

You could look at GNU Tools, they provide (amongst other things) sed on windows.

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Unable to create migrations after upgrading to ASP.NET Core 2.0

I ran into same problem. I have two projects in the solution. which

  1. API
  2. Services and repo, which hold context models

Initially, API project was set as Startup project.

I changed the Startup project to the one which holds context classes. if you are using Visual Studio you can set a project as Startup project by:

open solution explorer >> right-click on context project >> select Set as Startup project

What is REST? Slightly confused

REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).

First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).

EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

CSS div element - how to show horizontal scroll bars only?

You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.

However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.

IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:

overflow: auto;
overflow-y: hidden;

You may also need to add for IE8:

-ms-overflow-y: hidden;

as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)

On the other hand it's entirely possible IE8 will have fixed the bug anyway.

In Java, how do I call a base class's method from the overriding method in a derived class?

Answer is as follows:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

Dockerfile if else condition with external arguments

Exactly as others told, shell script would help.

Just an additional case, IMHO it's worth mentioning (for someone else who stumble upon here, looking for an easier case), that is Environment replacement.

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

The ${variable_name} syntax also supports a few of the standard bash modifiers as specified below:

  • ${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.

  • ${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.

Test if a variable is a list or tuple

Go ahead and use isinstance if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str or unicode like so:

import types
isinstance(var, types.StringTypes)

N.B. Don't mistake types.StringType for types.StringTypes. The latter incorporates str and unicode objects.

The types module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str and unicode, like this:

isinstance(var, (str, unicode)):

Edit:

Better still is:

isinstance(var, basestring)

End edit

After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.

See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.

Function of Project > Clean in Eclipse

There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.

jQuery selector for the label of a checkbox

Thanks Kip, for those who may be looking to achieve the same using $(this) whilst iterating or associating within a function:

$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );

I looked for a while whilst working this project but couldn't find a good example so I hope this helps others who may be looking to resolve the same issue.

In the example above, my objective was to hide the radio inputs and style the labels to provide a slicker user experience (changing the orientation of the flowchart).

You can see an example here

If you like the example, here is the css:

.orientation {      position: absolute; top: -9999px;   left: -9999px;}
    .orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;}
    .orR{   background-position: 9px -57px;}
    .orT{   background-position: 2px -120px;}
    .orB{   background-position: 6px -177px;}

    .orienSel {background-color:#323232;}

and the relevant part of the JavaScript:

function changeHandler() {
    $(".orienSel").removeClass( "orienSel" );
    if(this.checked) {
        $("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
    }
};

An alternate root to the original question, given the label follows the input, you could go with a pure css solution and avoid using JavaScript altogether...:

input[type=checkbox]:checked+label {}

Number of visitors on a specific page

If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.

 

Terminology


Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."

User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.

Session - The number of different times that a visitor came to your site.

Pageviews - The total number of pages that a user has accessed.

 

Creating a Custom Report


  1. To create a custom report, click on the "Customization" item in the left navigation menu, and then click on "Custom Reports".

customization item expanded in navigation menu

  1. The "Create Custom Report" page will open.
  2. Enter a name for your report.
  3. In the "Metric Groups" section, enter either "Users" or "Sessions" depending on what information you want to collect (see Terminology, above).
  4. In the "Dimension Drilldowns" section, enter "Page".
  5. Under "Filters" enter the individual page (exact) or group of pages (using regex) that you would like to see the data for. enter image description here
  6. Save the report and run it.

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

None of the above worked in my case.

I was using Node 15.5.0, but this version is not compatible with node-sass. So, I deleted current Node (Add/remove programs in Windows), and installed 14.15.3 version.

Try to delete node_modules and do npm install again after you finish node installation.

Getting last month's date in php

Oh I figured this out, please ignore unless you have the same problem i did in which case:

$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

ProductionWorker extends Employee, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super(); call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super(); cannot be placed automatically due to the fact that Employee's constructor has parameters.

You either need to define a default constructor in your Employee class, or call super('Erkan', 21, new Date()); in the first line of the constructor in ProductionWorker.

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

How to disassemble a binary executable in Linux to get the assembly code?

You can come pretty damn close (but no cigar) to generating assembly that will reassemble, if that's what you are intending to do, using this rather crude and tediously long pipeline trick (replace /bin/bash with the file you intend to disassemble and bash.S with what you intend to send the output to):

objdump --no-show-raw-insn -Matt,att-mnemonic -Dz /bin/bash | grep -v "file format" | grep -v "(bad)" | sed '1,4d' | cut -d' ' -f2- | cut -d '<' -f2 | tr -d '>' | cut -f2- | sed -e "s/of\ section/#Disassembly\ of\ section/" | grep -v "\.\.\." > bash.S

Note how long this is, however. I really wish there was a better way (or, for that matter, a disassembler capable of outputting code that an assembler will recognize), but unfortunately there isn't.

PHP Sort a multidimensional array by element containing date

$array = Array
(
  [0] => Array
   (
    [id] => 2
    [type] => comment
    [text] => hey
    [datetime] => 2010-05-15 11:29:45
   )

 [1] => Array
  (
    [id] => 3
    [type] => status
    [text] => oi
    [datetime] => 2010-05-26 15:59:53
  )

  [2] => Array
   (
    [id] => 4
    [type] => status
    [text] => yeww
    [datetime] => 2010-05-26 16:04:24
   )

   );
   print_r($array);   
   $name = 'datetime';
   usort($array, function ($a, $b) use(&$name){
      return $a[$name] - $b[$name];});

   print_r($array);

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Jenkins CI: How to trigger builds on SVN commit

You can use a post-commit hook.

Put the post-commit hook script in the hooks folder, create a wget_folder in your C:\ drive, and put the wget.exe file in this folder. Add the following code in the file called post-commit.bat

SET REPOS=%1   
SET REV=%2

FOR /f "tokens=*" %%a IN (  
'svnlook uuid %REPOS%'  
) DO (  
SET UUID=%%a  
)  

FOR /f "tokens=*" %%b IN (  
'svnlook changed --revision %REV% %REPOS%'  
) DO (  
SET POST=%%b   
)

echo %REPOS% ----- 1>&2

echo %REV% -- 1>&2

echo %UUID% --1>&2

echo %POST% --1>&2

C:\wget_folder\wget ^   
    --header="Content-Type:text/plain" ^   
    --post-data="%POST%" ^   
    --output-document="-" ^   
    --timeout=2 ^     
    http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%    

where Test = name of the job

echo is used to see the value and you can also add exit 2 at the end to know about the issue and whether the post-commit hook script is running or not.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):

./gradlew wrapper --gradle-version 5.5

Moreover, you can use --distribution-type parameter with either bin or all value to choose a distribution type. Use all distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:

./gradlew wrapper --gradle-version 5.5 --distribution-type all

Or you can create a custom wrapper task

task wrapper(type: Wrapper) {
    gradleVersion = '5.5'
}

and run ./gradlew wrapper.

Unable to execute dex: Multiple dex files define

I have encountered a similar error today and the reason was that the support library was referenced by two library projects used by my app project but with different versions.

In more details: My app depends on 2 library projects

  • FaceBookSDK 3.0 -> which is referencing android-support-v4
  • ActionBarSherlock -> which is referencing android-support-v4 but with a modified version to support maps.

To solve the problem I had to make FaceBookSDK library depend on ABS library instead of the support library directly.

Easiest way to loop through a filtered list with VBA?

One way assuming filtered data in A1 downwards;

dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng 
   ...     

Confused by python file mode "w+"

As mentioned by h4z3, For a practical use, Sometimes your data is too big to directly load everything, or you have a generator, or real-time incoming data, you could use w+ to store in a file and read later.

Refresh/reload the content in Div using jquery/ajax

$(document).ready(function() {
var pageRefresh = 5000; //5 s
    setInterval(function() {
        refresh();
    }, pageRefresh);
});

// Functions

function refresh() {
    $('#div1').load(location.href + " #div1");
    $('#div2').load(location.href + " #div2");
}

How to delete all files and folders in a directory?

The only thing you should do is to set optional recursive parameter to True.

Directory.Delete("C:\MyDummyDirectory", True)

Thanks to .NET. :)

PHP date yesterday

date() itself is only for formatting, but it accepts a second parameter.

date("F j, Y", time() - 60 * 60 * 24);

To keep it simple I just subtract 24 hours from the unix timestamp.

A modern oop-approach is using DateTime

$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";

Or in your case (more readable/obvious)

$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";

(Because DateInterval is negative here, we must add() it here)

See also: DateTime::sub() and DateInterval

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

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

import types

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

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

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

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

What does the servlet <load-on-startup> value signify

yes it can have same value....the reason for giving numbers to load-on-startup is to define a sequence for server to load all the servlet. servlet with 0 load-on-startup value will load first and servlet with value 1 will load after that.

if two servlets will have the same value for load-on-startup than it will be loaded how they are declared in the web.xml from top to bottom. the servlet which comes first in the web.xml will be loaded first and the other will be loaded after that.

How to remove all options from a dropdown using jQuery / JavaScript

In case .empty() doesn't work for you, which is for me

function SetDropDownToEmpty() 
{           
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");          
}

$(document).ready(
SetDropDownToEmpty() ;
)

position fixed header in html

Well! As I saw my question now, I realized that I didn't want to mention fixed margin value because of the dynamic height of header.

Here is what I have been using for such scenarios.

Calculate the header height using jQuery and apply that as a top margin value.

var divHeight = $('#header-wrap').height(); 
$('#container').css('margin-top', divHeight+'px');

Demo

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

What is the fastest way to compare two sets in Java?

If you are using Guava library it's possible to do:

        SetView<Record> added = Sets.difference(secondSet, firstSet);
        SetView<Record> removed = Sets.difference(firstSet, secondSet);

And then make a conclusion based on these.

Genymotion error at start 'Unable to load virtualbox'

Try closing Android Studio/Eclipse if it's open. It worked for me.

Converting double to integer in Java

For the datatype Double to int, you can use the following:

Double double = 5.00;

int integer = double.intValue();

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Map<String, String>, how to print both the "key string" and "value string" together

Inside of your loop, you have the key, which you can use to retrieve the value from the Map:

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}

How to change Status Bar text color in iOS

This works in Golden Master iOS 7 and Xcode 5 GM seed and iOS7 SDK released on September 18th, 2013 (at least with navigation controller hidden):

  1. Set the UIViewControllerBasedStatusBarAppearance to NO in the Info.plist.

  2. In ViewDidLoad method or anywhere, where do you want to change status bar style: [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

How to create a hex dump of file containing only the hex characters without spaces in bash?

Perl one-liner:

perl -e 'local $/; print unpack "H*", <>' file

Upgrading PHP in XAMPP for Windows?

1) Backup your htdocs folder
2) export your databases (follow this tutorial)
3) uninstall xampp
4) install the new version of xampp
5) replace the htdocs folder that you have backed up
6) Import your databases you had exported before

Note: In case you have changed config files like PHP (php.ini), Apache (httpd.conf) or any other, please take back up of those files as well and replace them with newly installed version.

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

As for "phone numbers" you should really consider the difference between a "subscriber number" and a "dialling number" and the possible formatting options of them.

A subscriber number is generally defined in the national numbering plans. The question itself shows a relation to a national view by mentioning "area code" which a lot of nations don't have. ITU has assembled an overview of the world's numbering plans publishing recommendation E.164 where the national number was found to have a maximum of 12 digits. With international direct distance calling (DDD) defined by a country code of 1 to 3 digits they added that up to 15 digits ... without formatting.

The dialling number is a different thing as there are network elements that can interpret exta values in a phone number. You may think of an answering machine and a number code that sets the call diversion parameters. As it may contain another subscriber number it must be obviously longer than its base value. RFC 4715 has set aside 20 bcd-encoded bytes for "subaddressing".

If you turn to the technical limitation then it gets even more as the subscriber number has a technical limit in the 10 bcd-encoded bytes in the 3GPP standards (like GSM) and ISDN standards (like DSS1). They have a seperate TON/NPI byte for the prefix (type of number / number plan indicator) which E.164 recommends to be written with a "+" but many number plans define it with up to 4 numbers to be dialled.

So if you want to be future proof (and many software systems run unexpectingly for a few decades) you would need to consider 24 digits for a subscriber number and 64 digits for a dialling number as the limit ... without formatting. Adding formatting may add roughly an extra character for every digit. So as a final thought it may not be a good idea to limit the phone number in the database in any way and leave shorter limits to the UX designers.

How line ending conversions work with git core.autocrlf between different operating systems

No, the @jmlane answer is wrong.

For Checkin (git add, git commit):

  1. if text property is Set, Set value to 'auto', the conversion happens enen the file has been committed with 'CRLF'
  2. if text property is Unset:nothing happens, enen for Checkout
  3. if text property is Unspecified, conversion depends on core.autocrlf
    1. if autocrlf = input or autocrlf = true, the conversion only happens when the file in the repository is 'LF', if it has been 'CRLF', nothing will happens.
    2. if autocrlf = false, nothing happens

For Checkout:

  1. if text property is Unset: nothing happens.
  2. if text property is Set, Set value to 'auto: it depends on core.autocrlf, core.eol.
    1. core.autocrlf = input : nothing happens
    2. core.autocrlf = true : the conversion only happens when the file in the repository is 'LF', 'LF' -> 'CRLF'
    3. core.autocrlf = false : the conversion only happens when the file in the repository is 'LF', 'LF' -> core.eol
  3. if text property is Unspecified, it depends on core.autocrlf.
    1. the same as 2.1
    2. the same as 2.2
    3. None, nothing happens, core.eol is not effective when text property is Unspecified

Default behavior

So the Default behavior is text property is Unspecified and core.autocrlf = false:

  1. for checkin, nothing happens
  2. for checkout, nothing happens

Conclusions

  1. if text property is set, checkin behavior is depends on itself, not on autocrlf
  2. autocrlf or core.eol is for checkout behavior, and autocrlf > core.eol

Add column in dataframe from list

First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.

df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})

And the mapping that you desire:

mapping = dict(enumerate([2,5,6,8,12,16,26,32]))

df['D'] = df['A'].map(mapping)

Done!

print df

Output:

   A   D
0  0   2
1  4  12
2  5  16
3  6  26
4  7  32
5  7  32
6  6  26
7  5  16

how to set imageview src?

Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.

Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html

e.g.:

imageView.setImageResource(R.drawable.myimage);

Are there constants in JavaScript?

Checkout https://www.npmjs.com/package/constjs, which provides three functions to create enum, string const and bitmap. The returned result is either frozen or sealed thus you can't change/delete the properties after they are created, you can neither add new properties to the returned result

create Enum:

var ConstJs = require('constjs');

var Colors = ConstJs.enum("blue red");

var myColor = Colors.blue;

console.log(myColor.isBlue()); // output true 
console.log(myColor.is('blue')); // output true 
console.log(myColor.is('BLUE')); // output true 
console.log(myColor.is(0)); // output true 
console.log(myColor.is(Colors.blue)); // output true 

console.log(myColor.isRed()); // output false 
console.log(myColor.is('red')); // output false 

console.log(myColor._id); // output blue 
console.log(myColor.name()); // output blue 
console.log(myColor.toString()); // output blue 

// See how CamelCase is used to generate the isXxx() functions 
var AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');
var curMode = AppMode.LOG_IN;

console.log(curMode.isLogIn()); // output true 
console.log(curMode.isSignUp()); // output false 
console.log(curMode.isForgotPassword()); // output false 

Create String const:

var ConstJs = require('constjs');

var Weekdays = ConstJs.const("Mon, Tue, Wed");
console.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'} 

var today = Weekdays.Wed;
console.log(today); // output: 'Wed'; 

Create Bitmap:

var ConstJs = require('constjs');

var ColorFlags = ConstJs.bitmap("blue red");
console.log(ColorFlags.blue); // output false 

var StyleFlags = ConstJs.bitmap(true, "rustic model minimalist");
console.log(StyleFlags.rustic); // output true 

var CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});
console.log(CityFlags.Chengdu); //output true 
console.log(CityFlags.Sydney); // output false 

var DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});
console.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean  

For more information please checkout

Disclaim: I am the author if this tool.

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

Click button copy to clipboard using jQuery

It's very important that the input field does not have display: none. The browser will not select the text and therefore will not be copied. Use opacity: 0 with a width of 0px to fix the problem.