Programs & Examples On #Stream processing

How do you change the document font in LaTeX?

As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).

Try \usepackage{times}.

Finding second occurrence of a substring in a string in Java

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);

Immutable vs Mutable types

It would seem to me that you are fighting with the question what mutable/immutable actually means. So here is a simple explenation:

First we need a foundation to base the explenation on.

So think of anything that you program as a virtual object, something that is saved in a computers memory as a sequence of binary numbers. (Don't try to imagine this too hard, though.^^) Now in most computer languages you will not work with these binary numbers directly, but rather more you use an interpretation of binary numbers.

E.g. you do not think about numbers like 0x110, 0xaf0278297319 or similar, but instead you think about numbers like 6 or Strings like "Hello, world". Never the less theses numbers or Strings are an interpretation of a binary number in the computers memory. The same is true for any value of a variable.

In short: We do not program with actual values but with interpretations of actual binary values.

Now we do have interpretations that must not be changed for the sake of logic and other "neat stuff" while there are interpretations that may well be changed. For example think of the simulation of a city, in other words a program where there are many virtual objects and some of these are houses. Now may these virtual objects (the houses) be changed and can they still be considered to be the same houses? Well of course they can. Thus they are mutable: They can be changed without becoming a "completely" different object.

Now think of integers: These also are virtual objects (sequences of binary numbers in a computers memory). So if we change one of them, like incrementing the value six by one, is it still a six? Well of course not. Thus any integer is immutable.

So: If any change in a virtual object means that it actually becomes another virtual object, then it is called immutable.

Final remarks:

(1) Never mix up your real-world experience of mutable and immutable with programming in a certain language:

Every programming language has a definition of its own on which objects may be muted and which ones may not.

So while you may now understand the difference in meaning, you still have to learn the actual implementation for each programming language. ... Indeed there might be a purpose of a language where a 6 may be muted to become a 7. Then again this would be quite some crazy or interesting stuff, like simulations of parallel universes.^^

(2) This explenation is certainly not scientific, it is meant to help you to grasp the difference between mutable and immutable.

Toggle Checkboxes on/off

This one works very well for me.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });

Proper way to rename solution (and directories) in Visual Studio

To rename a solution:

  1. In Solution Explorer, right-click the project, select Rename, and enter a new name.

  2. In Solution Explorer, right-click the project and select Properties. On the Application tab, change the "Assembly name" and "Default namespace".

  3. In the main cs file (or any other code files), rename the namespace declaration to use the new name. For this right-click the namespace and select Refactor > Rename enter a new name. For example: namespace WindowsFormsApplication1

  4. Change the AssemblyTitle and AssemblyProduct in Properties/AssemblyInfo.cs.

    [assembly: AssemblyTitle("New Name Here")]
    [assembly: AssemblyDescription("")]
    [assembly: AssemblyConfiguration("")]
    [assembly: AssemblyCompany("")]
    [assembly: AssemblyProduct("New Name Here")]
    [assembly: AssemblyCopyright("Copyright ©  2013")]
    [assembly: AssemblyTrademark("")]
    [assembly: AssemblyCulture("")]
    
  5. Delete bin and obj directories physically.

  6. Rename the project physical folder directory.

  7. Open the SLN file (within notepad or any editor) and change the path to the project.

  8. Clean and Rebuild the project.

Make Adobe fonts work with CSS3 @font-face in IE9

If you want to do this with a PHP script instead of having to run C code (or you're on a Mac like me and you can't be arsed compiling with Xcode only to wait a year for it to open), here's a PHP function that you can use to remove the embedding permissions from the font:

function convertRestrictedFont($filename) {
    $font = fopen($filename,'r+');
    if ($font === false) {
        throw new Exception('Could not open font file.');
    }

    fseek($font, 12, 0);

    while (!feof($font)) {
        $type = '';
        for ($i = 0; $i < 4; $i++) {
            $type .= fgetc($font);
            if (feof($font)) {
                fclose($font);
                throw new Exception('Could not read the table definitions of the font.');
            }
        }
        if ($type == 'OS/2') {
            // Save the location of the table definition
            // containing the checksum and pointer to the data
            $os2TableDefinition = ftell($font);
            $checksum = 0;

            for ($i = 0; $i < 4; $i++) {
                fgetc($font);
                if (feof($font)) {
                    fclose($font);
                    throw new Exception('Could not read the OS/2 table header of the font.');
                }
            }

            // Get the pointer to the OS/2 table data
            $os2TablePointer = ord(fgetc($font)) << 24;
            $os2TablePointer |= ord(fgetc($font)) << 16;
            $os2TablePointer |= ord(fgetc($font)) << 8;
            $os2TablePointer |= ord(fgetc($font));

            $length = ord(fgetc($font)) << 24;
            $length |= ord(fgetc($font)) << 16;
            $length |= ord(fgetc($font)) << 8;
            $length |= ord(fgetc($font));

            if (fseek($font, $os2TablePointer + 8, 0) !== 0) {
                fclose($font);
                throw new Exception('Could not read the embeddable type of the font.');
            }

            // Read the fsType before overriding it
            $fsType = ord(fgetc($font)) << 8;
            $fsType |= ord(fgetc($font));

            error_log('Installable Embedding: ' . ($fsType == 0));
            error_log('Reserved: ' . ($fsType & 1));
            error_log('Restricted License: ' . ($fsType & 2));
            error_log('Preview & Print: ' . ($fsType & 4));
            error_log('Editable Embedding: ' . ($fsType & 8));
            error_log('Reserved: ' . ($fsType & 16)); 
            error_log('Reserved: ' . ($fsType & 32));
            error_log('Reserved: ' . ($fsType & 64));
            error_log('Reserved: ' . ($fsType & 128));
            error_log('No subsetting: ' . ($fsType & 256));
            error_log('Bitmap embedding only: ' . ($fsType & 512));                         
            error_log('Reserved: ' . ($fsType & 1024));
            error_log('Reserved: ' . ($fsType & 2048));
            error_log('Reserved: ' . ($fsType & 4096));
            error_log('Reserved: ' . ($fsType & 8192));
            error_log('Reserved: ' . ($fsType & 16384));
            error_log('Reserved: ' . ($fsType & 32768));

            fseek($font, ftell($font) - 2);

            // Set the two bytes of fsType to 0
            fputs($font, chr(0), 1);
            fputs($font, chr(0), 1);

            // Go to the beginning of the OS/2 table data
            fseek($font, $os2TablePointer, 0);

            // Generate a new checksum based on the changed 
            for ($i = 0; $i < $length; $i++) {
                $checksum += ord(fgetc($font));
            }
            fseek($font, $os2TableDefinition, 0);
            fputs($font, chr($checksum >> 24), 1);
            fputs($font, chr(255 & ($checksum >> 16)), 1);
            fputs($font, chr(255 & ($checksum >> 8)), 1);
            fputs($font, chr(255 & $checksum), 1);

            fclose($font);

            return true;
        }
        for ($i = 0; $i < 12; $i++) {
            fgetc($font);
            if (feof($font)) {
                fclose($font);
                throw new Exception('Could not skip a table definition of the font.');
            }
        }
    }

    fclose($font);

    return false;
}

Make sure to backup your font file before running this code and don't blame me if it corrupts.

Original source in C can be found here.

Javascript to check whether a checkbox is being checked or unchecked

I am not sure what the problem is, but I am pretty sure this will fix it.

for (i=0; i<arrChecks.length; i++)
    {
        var attribute = arrChecks[i].getAttribute("xid")
        if (attribute == elementName)
        {
            if (arrChecks[i].checked == 0)  
            {
                arrChecks[i].checked = 1;
            } else {
                arrChecks[i].checked = 0;
            }

        } else {
            arrChecks[i].checked = 0;
        }
    }

Colors in JavaScript console

You can use a custom stylesheet to color your debugger. You can put this code in C:\Documents and Settings\<User Name>\Local Settings\Application Data\Google\Chrome\User Data\Default\User StyleSheets\Custom.css if you are in WinXP, but the directory varies by OS.

.console-error-level .console-message-text{
    color: red;
}

.console-warning-level .console-message-text {
    color: orange;
}

.console-log-level .console-message-text {
    color:green;
}

Connecting to MySQL from Android with JDBC

If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.

kill a process in bash

It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.

smooth scroll to top

also used below:

  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;

How to enable Logger.debug() in Log4j

Put a file named log4j.xml into your classpath. Contents are e.g.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %t %c{1}:%L - %m%n"/>
        </layout>
    </appender>

    <root>
        <level value="debug"/>
        <appender-ref ref="stdout"/>
    </root>

</log4j:configuration>

Way to ng-repeat defined number of times instead of repeating over array?

angular gives a very sweet function called slice.. using this you can achieve what you are looking for. e.g. ng-repeat="ab in abc.slice(startIndex,endIndex)"

this demo :http://jsfiddle.net/sahilosheal/LurcV/39/ will help you out and tell you how to use this "making life easy" function. :)

html:

<div class="div" ng-app >
    <div ng-controller="Main">
        <h2>sliced list(conditional NG-repeat)</h2>
        <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc.slice(2,5)"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>
        <h2>unsliced list( no conditional NG-repeat)</h2>
         <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>

    </div>

CSS:

ul
{
list-style: none;
}
.div{
    padding:25px;
}
li{
    background:#d4d4d4;
    color:#052349;
}

ng-JS:

 function ctrlParent ($scope) {
    $scope.abc = [
     { "name": "What we do", url: "/Home/AboutUs" },
     { "name": "Photo Gallery", url: "/home/gallery" },
     { "name": "What we work", url: "/Home/AboutUs" },
     { "name": "Photo play", url: "/home/gallery" },
     { "name": "Where", url: "/Home/AboutUs" },
     { "name": "playground", url: "/home/gallery" },
     { "name": "What we score", url: "/Home/AboutUs" },
     { "name": "awesome", url: "/home/gallery" },
     { "name": "oscar", url: "/Home/AboutUs" },
     { "name": "american hustle", url: "/home/gallery" }
    ];
}
function Main($scope){
    $scope.items = [{sort: 1, name: 'First'}, 
                    {sort: 2, name: 'Second'}, 
                    {sort: 3, name: 'Third'}, 
                    {sort: 4, name:'Last'}];
    }

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

It is safer and neater to use an explicit starting point '19000101'

create function dbo.fnDateTime2FromParts(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int, @Nanosecond int)
returns datetime2
as
begin
    -- Note! SQL Server 2012 includes datetime2fromparts() function
    declare @output datetime2 = '19000101'
    set @output = dateadd(year      , @Year - 1900  , @output)
    set @output = dateadd(month     , @Month - 1    , @output)
    set @output = dateadd(day       , @Day - 1      , @output)
    set @output = dateadd(hour      , @Hour         , @output)
    set @output = dateadd(minute    , @Minute       , @output)
    set @output = dateadd(second    , @Second       , @output)
    set @output = dateadd(ns        , @Nanosecond   , @output)
    return @output
end

How to set cache: false in jQuery.get call

I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

How to wait for all threads to finish, using ExecutorService?


ExecutorService WORKER_THREAD_POOL 
  = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
    WORKER_THREAD_POOL.submit(() -> {
        try {
            // doSomething();
            latch.countDown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}

// wait for the latch to be decremented by the two remaining threads
latch.await();

If doSomething() throw some other exceptions, the latch.countDown() seems will not execute, so what should I do?

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

  <img
    src="pond1.jpg"
    alt="pic id code"
    onClick="window.open(this.src)"
    role="button"
    tabIndex="0"
  />

How to tell whether a point is to the right or left side of a line

Use the sign of the determinant of vectors (AB,AM), where M(X,Y) is the query point:

position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax))

It is 0 on the line, and +1 on one side, -1 on the other side.

How to set environment variables in Jenkins?

You can try something like this

stages {
        stage('Build') {
            environment { 
                    AOEU= sh (returnStdout: true, script: 'echo aoeu').trim()
                }
            steps {
                sh 'env'
                sh 'echo $AOEU'
            }
        }
    }

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

From your output:

no listening sockets available, shutting down

what basically means, that any port in which one apache is going to be listening is already being used by another application.

netstat -punta | grep LISTEN

Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill stop or do whatever you want to do with it.

After doing a nmap of your ip I can see that

80/tcp    open     http

so I guess you sorted it out.

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

2D array values C++

Like this:

int main()
{
    int arr[2][5] =
    {
        {1,8,12,20,25},
        {5,9,13,24,26}
    };
}

This should be covered by your C++ textbook: which one are you using?

Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

Difference between links and depends_on in docker_compose.yml

[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.

[Original answer]:

It is pretty clear in the documentation. depends_on decides the dependency and the order of container creation and links not only does these, but also

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

For example, assuming the following docker-compose.yml file:

web:
  image: example/my_web_app:latest
  links:
    - db
    - cache

db:
  image: postgres:latest

cache:
  image: redis:latest

With links, code inside web will be able to access the database using db:5432, assuming port 5432 is exposed in the db image. If depends_on were used, this wouldn't be possible, but the startup order of the containers would be correct.

What's the difference between a mock & stub?

following is my understanding...

  • if you create test objects locally and feed your local service with that, you are using mock object. this will give a test for the method you implemented in your local service. it is used to verify behaviors

  • when you get the test data from the real service provider, though from a test version of interface and get a test version of the object, you are working with stubs the stub can have logic to accept certain input and give corresponding output to help you perform state verification...

Short description of the scoping rules?

Python resolves your variables with -- generally -- three namespaces available.

At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: the innermost scope, which is searched first, contains the local names; the namespaces of any enclosing functions, which are searched starting with the nearest enclosing scope; the middle scope, searched next, contains the current module's global names; and the outermost scope (searched last) is the namespace containing built-in names.

There are two functions: globals and locals which show you the contents two of these namespaces.

Namespaces are created by packages, modules, classes, object construction and functions. There aren't any other flavors of namespaces.

In this case, the call to a function named x has to be resolved in the local name space or the global namespace.

Local in this case, is the body of the method function Foo.spam.

Global is -- well -- global.

The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global. That's it.

There are no other scopes. The for statement (and other compound statements like if and try) don't create new nested scopes. Only definitions (packages, modules, functions, classes and object instances.)

Inside a class definition, the names are part of the class namespace. code2, for instance, must be qualified by the class name. Generally Foo.code2. However, self.code2 will also work because Python objects look at the containing class as a fall-back.

An object (an instance of a class) has instance variables. These names are in the object's namespace. They must be qualified by the object. (variable.instance.)

From within a class method, you have locals and globals. You say self.variable to pick the instance as the namespace. You'll note that self is an argument to every class member function, making it part of the local namespace.

See Python Scope Rules, Python Scope, Variable Scope.

Regular expression to match balanced parentheses

[^\(]*(\(.*\))[^\)]*

[^\(]* matches everything that isn't an opening bracket at the beginning of the string, (\(.*\)) captures the required substring enclosed in brackets, and [^\)]* matches everything that isn't a closing bracket at the end of the string. Note that this expression does not attempt to match brackets; a simple parser (see dehmann's answer) would be more suitable for that.

Using Switch Statement to Handle Button Clicks

One way of achieving this is to make your class implement OnClickListener and then add it to your buttons like this:

Example:

//make your class implement OnClickListener
public class MyClass implements OnClickListener{

        ...

        //Create your buttons and set their onClickListener to "this"
        Button b1 = (Button) findViewById(R.id.buttonplay);   
        b1.setOnClickListener(this);

        Button b2 = (Button) findViewById(R.id.buttonstop);   
        b2.setOnClickListener(this);

        ...

        //implement the onClick method here
        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
            case R.id.buttonplay:
              //Play voicefile
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
              break;
            case R.id.buttonstop:
              //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
              break;
          }
       }
}

For more information see Android Developers > Handling UI Events.

How to make an installer for my C# application?

Why invent wheels yourself while there is a car ready for you? I just find this tools super easy and intuitive to use: Advanced Installer. This one minute video should be enough to impress you. Here is the illustrative user guide.

How to check file MIME type with javascript before upload?

If you just want to check if the file uploaded is an image you can just try to load it into <img> tag an check for any error callback.

Example:

var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();

reader.onload = function (e) {
    imageExists(e.target.result, function(exists){
        if (exists) {

            // Do something with the image file.. 

        } else {

            // different file format

        }
    });
};

reader.readAsDataURL(input.files[0]);


function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Eventviewer eventid for lock and unlock

To identify unlock screen I believe that you can use ID 4624. But then you also need to look at the Logon Type which in this case is 7: http://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4624

Event ID for Logoff is 4634

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

Find a file with a certain extension in folder

As per my understanding, this can be done in two ways :

1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.

Directory.GetFiles("your_folder_path)[i].Contains("*.txt")

2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.

Path.GetExtension(your_file_path).Equals(".json")

Note : Both the logic has to be inside a looping condition.

Routing with multiple Get methods in ASP.NET Web API

Also you will specify route on action for set route

[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
   //gets all customer logic
}

[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
     //gets some customer 
}

[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
  //gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
    //gets customer by its username
}

Example JavaScript code to parse CSV data

csvToArray v1.3

A compact (645 bytes), but compliant function to convert a CSV string into a 2D array, conforming to the RFC4180 standard.

https://code.google.com/archive/p/csv-to-array/downloads

Common Usage: jQuery

 $.ajax({
        url: "test.csv",
        dataType: 'text',
        cache: false
 }).done(function(csvAsString){
        csvAsArray=csvAsString.csvToArray();
 });

Common usage: JavaScript

csvAsArray = csvAsString.csvToArray();

Override field separator

csvAsArray = csvAsString.csvToArray("|");

Override record separator

csvAsArray = csvAsString.csvToArray("", "#");

Override Skip Header

csvAsArray = csvAsString.csvToArray("", "", 1);

Override all

csvAsArray = csvAsString.csvToArray("|", "#", 1);

java.time.format.DateTimeParseException: Text could not be parsed at index 21

If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT (implicitly):

final Instant parsed = Instant.parse(dateTime);

If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);

If neither is the case, you can construct a DateTimeFormatter in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME is constructed.


Your current pattern has several problems:

  • not using strict mode (ResolverStyle.STRICT);
  • using yyyy instead of uuuu (yyyy will not work in strict mode);
  • using 12-hour hh instead of 24-hour HH;
  • using only one digit S for fractional seconds, but input has three.

How to cherry pick a range of commits and merge into another branch?

All the above options will prompt you to resolve merge conflicts. If you are merging changes committed for a team, it is difficult to get resolved the merge conflicts from developers and proceed. However, "git merge" will do the merge in one shot but you can not pass a range of revisions as argument. we have to use "git diff" and "git apply" commands to do the merge range of revs. I have observed that "git apply" will fail if the patch file has diff for too many file, so we have to create a patch per file and then apply. Note that the script will not be able to delete the files that are deleted in source branch. This is a rare case, you can manually delete such files from target branch. The exit status of "git apply" is not zero if it is not able to apply the patch, however if you use -3way option it will fall back to 3 way merge and you don't have to worry about this failure.

Below is the script.

enter code here



  #!/bin/bash

    # This script will merge the diff between two git revisions to checked out branch
    # Make sure to cd to git source area and checkout the target branch
    # Make sure that checked out branch is clean run "git reset --hard HEAD"


    START=$1
    END=$2

    echo Start version: $START
    echo End version: $END

    mkdir -p ~/temp
    echo > /tmp/status
    #get files
    git --no-pager  diff  --name-only ${START}..${END} > ~/temp/files
    echo > ~/temp/error.log
    # merge every file
    for file in `cat  ~/temp/files`
    do
      git --no-pager diff --binary ${START}..${END} $file > ~/temp/git-diff
      if [ $? -ne 0 ]
      then
#      Diff usually fail if the file got deleted 
        echo Skipping the merge: git diff command failed for $file >> ~/temp/error.log
        echo Skipping the merge: git diff command failed for $file
        echo "STATUS: FAILED $file" >>  /tmp/status
        echo "STATUS: FAILED $file"
    # skip the merge for this file and continue the merge for others
        rm -f ~/temp/git-diff
        continue
      fi

      git apply  --ignore-space-change --ignore-whitespace  --3way --allow-binary-replacement ~/temp/git-diff

      if [ $? -ne 0 ]
       then
#  apply failed, but it will fall back to 3-way merge, you can ignore this failure
         echo "git apply command filed for $file"
       fi
       echo
       STATUS=`git status -s $file`


       if [ ! "$STATUS" ]
       then
#   status is null if the merged diffs are already present in the target file
         echo "STATUS:NOT_MERGED $file"
         echo "STATUS: NOT_MERGED $file$"  >>  /tmp/status
       else
#     3 way merge is successful
         echo STATUS: $STATUS
         echo "STATUS: $STATUS"  >>  /tmp/status
       fi
    done

    echo GIT merge failed for below listed files

    cat ~/temp/error.log

    echo "Git merge status per file is available in /tmp/status"

Set the maximum character length of a UITextField in Swift

Just in case, don't forget to guard range size before applying it to the string. Otherwise, you will get crash if the user will do this:

Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size)

Also, using iOS 13 users can accidentally trigger this by gestures

I suggest you add to your project this

extension String {
    func replace(with text: String, in range: NSRange) -> String? {
        guard range.location + range.length <= self.count else { return nil }
        return (self as NSString).replacingCharacters(in: range, with: text)
    }
}

And use it like this:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard let newText = textView.text.replace(with: text, in: range) else { return false }
    return newText.count < maxNumberOfCharacters
}

Otherwise, you will constantly be getting crashed in your app

python BeautifulSoup parsing table

Updated Answer

If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html.

Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries

Then following codes does the job perfectly (No need of beautifulsoup and fancy html):

import pandas as pd
import requests

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()

Output

First five lines of the table from the Website

How to empty a redis database?

tldr: flushdb clears one database and flushall clears all databases

Clear CURRENT

Delete default or currently selected database (usually `0) with

redis-cli flushdb

Clear SPECIFIC

Delete specific redis database with (e.g. 8 as my target database):

redis-cli -n 8 flushdb 

Clear ALL

Delete all redis databases with

redis-cli flushall

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

What is the shortcut to Auto import all in Android Studio?

File > Settings > Editor > General >Auto Import (Mac: Android Studio > Preferences > Editor > General >Auto Import).

Select all check boxes and set Insert imports on paste to All. Unambiguous imports are now added automatically to your files.

Reference

Deleting DataFrame row in Pandas based on column value

But for any future bypassers you could mention that df = df[df.line_race != 0] doesn't do anything when trying to filter for None/missing values.

Does work:

df = df[df.line_race != 0]

Doesn't do anything:

df = df[df.line_race != None]

Does work:

df = df[df.line_race.notnull()]

How to perform element-wise multiplication of two lists?

Use np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

Get the Query Executed in Laravel 3/4

There is very easy way to do it, from your laravel query just rename any column name, it will show you an error with your query.. :)

Converting VS2012 Solution to VS2010

Simple solution which worked for me.

  1. Install Vim editor for windows.
  2. Open VS 2012 project solution using Vim editor and modify the version targetting Visual studio solution 10.
  3. Open solution with Visual studio 2010.. and continue with your work ;)

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Exercises to improve my Java programming skills

You could try the problems at RosettaCode, many of which lack Java solutions at the moment. The problems are of many different difficulties, but each has a solution already in another language which should help with the algorithmic side.

Build android release apk on Phonegap 3.x CLI

just wondered around a lot because I got the same issue but in my installation the command "cordova" was never available and "phone gap build android --release" just ignored the platform/android/ant.properties.

so looking inside my platform filter I found a folder named "cordova" and inside of it there was an "build" binary that accepted the --release argument, it asked me for the key chains and I ended with a signed and ready for production APK.

this was never documented in any part of the phone gap site and frankly speaking now I kinda hate phonegap :( it was supposed to make the things easier but everything was just complicated :(

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

How to grep recursively, but only in files with certain extensions?

Since this is a matter of finding files, let's use find!

Using GNU find you can use the -regex option to find those files in the tree of directories whose extension is either .h or .cpp:

find -type f -regex ".*\.\(h\|cpp\)"
#            ^^^^^^^^^^^^^^^^^^^^^^^

Then, it is just a matter of executing grep on each of its results:

find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +

If you don't have this distribution of find you have to use an approach like Amir Afghani's, using -o to concatenate options (the name is either ending with .h or with .cpp):

find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And if you really want to use grep, follow the syntax indicated to --include:

grep "your pattern" -r --include=*.{cpp,h}
#                      ^^^^^^^^^^^^^^^^^^^

Difference between a class and a module

First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.

But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.

Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!

So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:

module Apple
  def a
    puts 'a'
  end
end

module Apple 
  def b
    puts 'b'
  end
end

class Fruit
  include Apple
end

 > f = Fruit.new
 => #<Fruit:0x007fe90c527c98> 
 > f.a
 => a
 > f.b
 => b

But there is no inheritance between modules:

module Apple
  module Green
    def green
      puts 'green'
    end
  end
end

class Fruit
  include Apple
end

> f = Fruit.new
 => #<Fruit:0x007fe90c462420> 
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>

The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.

So how do we gain access to the green method? You have to explicitly include it in your class:

class Fruit
  include Apple::Green
end
 => Fruit 
 > f.green
=> green

But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).

Bash: infinite sleep (infinite blocking)

Instead of killing the window manager, try running the new one with --replace or -replace if available.

How to convert data.frame column from Factor to numeric

breast$class <- as.numeric(as.character(breast$class))

If you have many columns to convert to numeric

indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))

Another option is to use stringsAsFactors=FALSE while reading the file using read.table or read.csv

Just in case, other options to create/change columns

 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

or

 breast <- transform(breast, class=as.numeric(as.character(breast)))

Eclipse - java.lang.ClassNotFoundException

I am using gradle with eclipse and faced the same challenge today and tried a number of ways to resolve but the only way which helped me was to run command gradlew clean .

P.S. => Don't combine the "build" with the above mentioned command.

Helped me, try your luck.

How to center an unordered list?

Let's say the list is:

<ul>
 <li>item1</li>
 <li>item2</li>
 <li>item3</li>
</ul>

For this example. If I understand correctly, you want the list items to be in the middle of the screen, but you want the text IN those list items to be centered to the left of the list item itself. Doing that is actually pretty easy. You just need some CSS:

ul {
    display: table; 
    margin: 0 auto;
    text-align: left;
}

And it works! Here is what is happening. First, we say we want to affect only unordered lists. Then, we do Rafael Herscovici's trick for centering the list items. Finally, we say to align the text to the left of the list items.

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

What is the difference between field, variable, attribute, and property in Java POJOs?

From here: http://docs.oracle.com/javase/tutorial/information/glossary.html


  • field

    • A data member of a class. Unless specified otherwise, a field is not static.

  • property

    • Characteristics of an object that users can set, such as the color of a window.

  • attribute

    • Not listed in the above glossary

  • variable

    • An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.

How to urlencode data for curl command?

Python 3 based on @sandro's good answer from 2010:

echo "Test & /me" | python -c "import urllib.parse;print (urllib.parse.quote(input()))"

Test%20%26%20/me

how to Call super constructor in Lombok

If child class has more members, than parent, it could be done not very clean, but short way:

@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
    private @NonNull String fullName;
    private @NonNull String email;
    ... 

    public User(Integer id, String fullName, String email, ....) {
        this(fullName, email, ....);
        this.id = id;
    }
}

@Data
@AllArgsConstructor
abstract public class BaseEntity {
   protected Integer id;

   public boolean isNew() {
      return id == null;
   }
}

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

check if a number already exist in a list in python

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: -

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSet recipe, which is referred to in Python Documentation

Hidden Features of C#?

Don't know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx

While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time.

Oh, I almost forgot the best class in the world when you can't optimize it any more. The BackgroundWorker!!!!

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

How can I remove a specific item from an array?

Using .indexOf() and .splice() - Mutable Pattern

There are two scenarios here:

  1. we know the index

_x000D_
_x000D_
const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id,  1);
console.log(removedDrink)
_x000D_
_x000D_
_x000D_

  1. we don’t know the index but know the value.
    _x000D_
    _x000D_
    const drinks =  ['Tea','Coffee', 'Milk'];
    const id = drinks.indexOf('Coffee'); // 1
    const removedDrink = drinks.splice(id,  1);
    // ["Coffee"]
    console.log(removedDrink);
    // ["Tea", "Milk"]
    console.log(drinks);
    _x000D_
    _x000D_
    _x000D_

Using .filter() - Immutable Pattern

The best way you can think about this is - instead of “removing” the item, you’ll be “creating” a new array that just does not include that item. So we must find it, and omit it entirely.

_x000D_
_x000D_
const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);

console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);
_x000D_
_x000D_
_x000D_

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

Use jQuery to get the file input's selected filename without the path

<script type="text/javascript">

    $('#upload').on('change',function(){
       // output raw value of file input
       $('#filename').html($(this).val().replace(/.*(\/|\\)/, '')); 

        // or, manipulate it further with regex etc.
        var filename = $(this).val().replace(/.*(\/|\\)/, '');
        // .. do your magic

        $('#filename').html(filename);
    });
</script>

How do I specify the platform for MSBuild?

If you want to build your solution for x86 and x64, your solution must be configured for both platforms. Actually you just have an Any CPU configuration.

How to check the available configuration for a project

To check the available configuration for a given project, open the project file (*.csproj for example) and look for a PropertyGroup with the right Condition.

If you want to build in Release mode for x86, you must have something like this in your project file:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
  ...
</PropertyGroup>

How to create and edit the configuration in Visual Studio

Configuration Manager panel
(source: microsoft.com)

New solution platform button
(source: msdn.com)

New solution platform panel
(source: msdn.com)

How to create and edit the configuration (on MSDN)

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

Which OS you are using ? For Windows : Go to Command Prompt

set path to www/{ur project}

For me : www/laravel5

Then type this command : composer install

It will automatically install all dependency in vendor/

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here:

http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

Description:  
    Mailbox of message author  
[...]  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

Description:  
    Mailbox of message sender  
[...]  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

Description:
    Message return path
[...]  
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

How to get just one file from another branch

Or if you want all the files from another branch:

git checkout <branch name> -- .

How to set top-left alignment for UILabel for iOS application?

In my case, it was bottom space constraint issue. I had set it to = 16.

When I set it to bottom to >= 16, this issue got solved.

Also, if you have any height constraint in the label, then you need to remove it.

Here's my label's constraint view in the size inspector:

constraint

How to create enum like type in TypeScript?

Update:

As noted by @iX3, Typescript 2.4 has support for enum strings.

See:Create an enum with string values in Typescript


Original answer:

For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;

Solution 1:

copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/

There is a simple solution: Just cast the string literal to any before assigning:

export enum Language {
    English = <any>"English",
    German = <any>"German",
    French = <any>"French",
    Italian = <any>"Italian"
}

solution 2:

copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html

You can use a string literal as a type. For example:

let foo: 'Hello';

Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:

let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"

They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:

type CardinalDirection =
    "North"
    | "East"
    | "South"
    | "West";

function move(distance: number, direction: CardinalDirection) {
    // ...
}

move(1,"North"); // Okay
move(1,"Nurth"); // Error!

SQL changing a value to upper or lower case

SELECT UPPER(firstname) FROM Person

SELECT LOWER(firstname) FROM Person

diff to output only the file names

If you want to get a list of files that are only in one directory and not their sub directories and only their file names:

diff -q /dir1 /dir2 | grep /dir1 | grep -E "^Only in*" | sed -n 's/[^:]*: //p'

If you want to recursively list all the files and directories that are different with their full paths:

diff -rq /dir1 /dir2 | grep -E "^Only in /dir1*" | sed -n 's/://p' | awk '{print $3"/"$4}'

This way you can apply different commands to all the files.

For example I could remove all the files and directories that are in dir1 but not dir2:

diff -rq /dir1 /dir2 | grep -E "^Only in /dir1*" | sed -n 's/://p' | awk '{print $3"/"$4}' xargs -I {} rm -r {}

Getting current unixtimestamp using Moment.js

for UNIX time-stamp in milliseconds

moment().format('x') // lowerCase x

for UNIX time-stamp in seconds moment().format('X') // capital X

How do you check if a certain index exists in a table?

-- Delete index if exists
IF EXISTS(SELECT TOP 1 1 FROM sys.indexes indexes INNER JOIN sys.objects 
objects ON indexes.object_id = objects.object_id WHERE indexes.name 
='Your_Index_Name' AND objects.name = 'Your_Table_Name')
BEGIN
    PRINT 'DROP INDEX [Your_Index_Name] ON [dbo].[Your_Table_Name]'
    DROP INDEX [our_Index_Name] ON [dbo].[Your_Table_Name]
END
GO

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

How to set index.html as root file in Nginx?

in your location block you can do:

location / {
  try_files $uri $uri/index.html;
}

which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html

failed to find target with hash string android-23

Mine was complaining about 26. I looked in my folders and found a folder for 27, but not 26. So I modified my build.gradle file, replacing 26 with 27. compileSdkVersion, targetSdkVersion, and implementation (changed those numbers to v:7:27.02). That changed my error message. Then I added buildToolsVersion "27.0.3" to the android bracket section right under compileSdkVersion.

Now the make project button works with 0 messages.

Next up, how to actually select a module in my configuration so I can run this.

docker cannot start on windows

Faced the similar issue, having installed docker desktop on a Windows VM, running on WSL2.

Solution:

Updated the Windows to latest build and VMTools to the latest(11.2) version, fixed the issue, now docker is running non-stop.

Finding all positions of substring in a larger string in C#

I noticed that at least two proposed solutions don't handle overlapping search hits. I didn't check the one marked with the green checkmark. Here is one that handles overlapping search hits:

    public static List<int> GetPositions(this string source, string searchString)
    {
        List<int> ret = new List<int>();
        int len = searchString.Length;
        int start = -1;
        while (true)
        {
            start = source.IndexOf(searchString, start +1);
            if (start == -1)
            {
                break;
            }
            else
            {
                ret.Add(start);
            }
        }
        return ret;
    }

How could I create a list in c++?

We are already in 21st century!! Don't try to implement the already existing data structures. Try to use the existing data structures.

Use STL or Boost library

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How to get first element in a list of tuples?

Those are tuples, not sets. You can do this:

l1 = [(1, u'abc'), (2, u'def')]
l2 = [(tup[0],) for tup in l1]
l2
>>> [(1,), (2,)]

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

Dynamic function name in javascript?

the best way it is create object with list of dynamic functions like:

const USER = 'user';

const userModule = {
  [USER + 'Action'] : function () { ... }, 
  [USER + 'OnClickHandler'] : function () { ... }, 
  [USER + 'OnCreateHook'] : function () { ... }, 
}

What Are Some Good .NET Profilers?

I've worked with RedGate's profiler in the past. Did the job for me.

How to print object array in JavaScript?

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Display JSON as HTML

Here's a light-weight solution, doing only what OP asked, including highlighting but nothing else: How can I pretty-print JSON using JavaScript?

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

Can you force Visual Studio to always run as an Administrator in Windows 8?

NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.


You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)

enter image description here

Update

One can install the commands from the Visual Studio menu bar using Tools->Extensions and Updates selecting Online and searching for vscommands where then one selects VSCommands for Visual Studio 20XX depending on whether using 2012 or 2013 (or greater going forward) and download and install.

What is the order of precedence for CSS?

First of all, based on your @extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.

Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.

However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:

  1. The current media type;
  2. Importance;
  3. Origin;
  4. Specificity of the selector, and finally our well-known rule:
  5. Which one is latter specified.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Swift 4

Here in my case I have to pass data into that custom view, so I create static function to instantiate the view.

  1. Create UIView extension

    extension UIView {
        class func initFromNib<T: UIView>() -> T {
            return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)?[0] as! T
        }
    }
    
  2. Create MyCustomView

    class MyCustomView: UIView {
    
        @IBOutlet weak var messageLabel: UILabel!
    
        static func instantiate(message: String) -> MyCustomView {
            let view: MyCustomView = initFromNib()
            view.messageLabel.text = message
            return view
        }
    }
    
  3. Set custom class to MyCustomView in .xib file. Connect outlet if necessary as usual. enter image description here

  4. Instantiate view

    let view = MyCustomView.instantiate(message: "Hello World.")
    

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python foo.py | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported.

This app won't run unless you update Google Play Services (via Bazaar)

I spent about one day to configure the new gmaps API (Google Maps Android API v2) on the Android emulator. None of the methods of those I found on the Internet was working correctly for me. But still I did it. Here is how:

  1. Create a new emulator with the following configuration:

Enter image description here

On the other versions I could not configure because of various errors when I installed the necessary applications.

2) Start the emulator and install the following applications:

  • GoogleLoginService.apk
  • GoogleServicesFramework.apk
  • Phonesky.apk

You can do this with following commands:

2.1) adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
2.2) adb shell chmod 777 /system/app
2.3-2.5) adb push Each_of_the_3_apk_files.apk /system/app/

Links to download APK files. I have copied them from my rooted Android device.

3) Install Google Play Services and Google Maps on the emulator. I have an error 491, if I install them from Google Play store. I uploaded the apps to the emulator and run the installation locally. (You can use adb to install this). Links to the apps:

4) I successfully run a demo sample on the emulator after these steps. Here is a screenshot:

Google Maps

What does "exited with code 9009" mean during this build?

tfa's answer has been downvoted, but actually can cause this issue. Thanks to hanzolo, I looked in the output window and found the following:

3>'gulp' is not recognized as an internal or external command,
3>operable program or batch file.
3>D:\dev\<filepath>\Web.csproj(4,5): error MSB3073: The command "gulp clean" exited with code 9009.

After running npm install -g gulp, I stopped getting this error. If you're getting this error in Visual Studio, check the output window and see if the issue is an unset environment variable.

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

How to change the status bar background color and text color on iOS 7?

Write this in your ViewDidLoad Method:

if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
}

It fixed status bar color for me and other UI misplacements also to a extent.

How to get key names from JSON using jq

In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:

     cat input.json | jq -r 'keys'

From jq help:

     -r     output raw strings, not JSON texts;

How to align checkboxes and their labels consistently cross-browsers

Hardcode the checkbox's height and width, remove its padding, and make its height plus vertical margins equal to the label's line-height. If the label text is inline, float the checkbox. Firefox, Chrome, and IE7+ all render the following example identically: http://www.kornea.com/css-checkbox-align

Intersection and union of ArrayLists in Java

Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

        System.out.println(new Test().intersection(list1, list2));
        System.out.println(new Test().union(list1, list2));
    }

    public <T> List<T> union(List<T> list1, List<T> list2) {
        Set<T> set = new HashSet<T>();

        set.addAll(list1);
        set.addAll(list2);

        return new ArrayList<T>(set);
    }

    public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
}

Get product id and product type in magento?

Try below code to get currently loaded product id:

$product_id = $this->getProduct()->getId();

When you don’t have access to $this, you can use Magento registry:

$product_id = Mage::registry('current_product')->getId();

Also for product type i think

$product = Mage::getModel('catalog/product')->load($product_id); 

$productType = $product->getTypeId();

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How do you get the file size in C#?

It returns the file contents length

Proper way to declare custom exceptions in modern Python?

See a very good article "The definitive guide to Python exceptions". The basic principles are:

  • Always inherit from (at least) Exception.
  • Always call BaseException.__init__ with only one argument.
  • When building a library, define a base class inheriting from Exception.
  • Provide details about the error.
  • Inherit from builtin exceptions types when it makes sense.

There is also information on organizing (in modules) and wrapping exceptions, I recommend to read the guide.

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Correctly determine if date string is a valid date in that format

/*********************************************************************************
Returns TRUE if the input parameter is a valid date string in "YYYY-MM-DD" format (aka "MySQL date format")
The date separator can be only the '-' character.
*********************************************************************************/
function isMysqlDate($yyyymmdd)
{
    return checkdate(substr($yyyymmdd, 5, 2), substr($yyyymmdd, 8), substr($yyyymmdd, 0, 4)) 
        && (substr($yyyymmdd, 4, 1) === '-') 
        && (substr($yyyymmdd, 7, 1) === '-');
}

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

Just found a quick and simple solution to discover type of a variable.

ES6

export const isType = (type, val) => val.constructor.name.toLowerCase() === type.toLowerCase();

ES5

function isType(type, val) {
  return val.constructor.name.toLowerCase() === type.toLowerCase();
}

Examples:

isType('array', [])
true
isType('array', {})
false
isType('string', '')
true
isType('string', 1)
false
isType('number', '')
false
isType('number', 1)
true
isType('boolean', 1)
false
isType('boolean', true)
true

EDIT

Improvment to prevent 'undefined' and 'null' values:

ES6

export const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());

ES5

function isType(type, val) {
  return !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
}

Powershell script to locate specific file/file name?

From a powershell prompt, use the gci cmdlet (alias for Get-ChildItem) and -filter option:

gci -recurse -filter "hosts"

This will return an exact match to filename "hosts".


SteveMustafa points out with current versions of powershell you can use the -File switch to give the following to recursively search for only files named "hosts" (and not directories or other miscellaneous file-system entities):

gci -recurse -filter "hosts" -File 


The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.".

If you want to avoid the error messages then set the -ErrorAction to be silent.

gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue


An additional helper is that you can set the root to search from using -Path. The resulting command to search explicitly search from, for example, the root of the C drive would be

gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Loop Through Each HTML Table Column and Get the Data using jQuery

Using a nested .each() means that your inner loop is doing one td at a time, so you can't set the productId and product and quantity all in the inner loop.

Also using function(key, val) and then val[key].innerHTML isn't right: the .each() method passes the index (an integer) and the actual element, so you'd use function(i, element) and then element.innerHTML. Though jQuery also sets this to the element, so you can just say this.innerHTML.

Anyway, here's a way to get it to work:

    table.find('tr').each(function (i, el) {
        var $tds = $(this).find('td'),
            productId = $tds.eq(0).text(),
            product = $tds.eq(1).text(),
            Quantity = $tds.eq(2).text();
        // do something with productId, product, Quantity
    });

Demo: http://jsfiddle.net/bqX7Q/

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

Google OAuth 2 authorization - Error: redirect_uri_mismatch

In my case I added

https://websitename.com/sociallogin/social/callback/?hauth.done=Google

in Authorized redirect URIs section and it worked for me

Twitter bootstrap modal-backdrop doesn't disappear

.modal('hide')

Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs).

So instead of

$('#myModal').modal('hide');
$('#someOtherSelector').trigger('click');

do

$('#myModal').modal('hide');
$('#myModal').on('hidden.bs.modal', function() {
   $('#someOtherSelector').trigger('click');
});

So you are sure to wait till the "hide" event is finished.

Writing/outputting HTML strings unescaped

Supposing your content is inside a string named mystring...

You can use:

@Html.Raw(mystring)

Alternatively you can convert your string to HtmlString or any other type that implements IHtmlString in model or directly inline and use regular @:

@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString

Keeping ASP.NET Session Open / Alive

If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:

[HttpPost]
public JsonResult KeepSessionAlive() {
    return new JsonResult {Data = "Success"};
}

, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):

var keepSessionAlive = false;
var keepSessionAliveUrl = null;

function SetupSessionUpdater(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    var container = $("#body");
    container.mousemove(function () { keepSessionAlive = true; });
    container.keydown(function () { keepSessionAlive = true; });
    CheckToKeepSessionAlive();
}

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 5*60*1000);
}

function KeepSessionAlive() {
    if (keepSessionAlive && keepSessionAliveUrl != null) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function () { keepSessionAlive = false; }
        });
    }
    CheckToKeepSessionAlive();
}

, and initialize this functionality by calling a JavaScript function:

SetupSessionUpdater('/Home/KeepSessionAlive');

Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).

"Default Activity Not Found" on Android Studio upgrade

In case your application doesn't have an Activity (only a service for example), change the run/debug configuration 'Launch' option to Nothing.

How can I get key's value from dictionary in Swift?

For finding value use below

if let a = companies["AAPL"] {
   // a is the value
}

For traversing through the dictionary

for (key, value) in companies {
    print(key,"---", value)
}

Finally for searching key by value you firstly add the extension

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

Then just call

companies.findKey(val : "Apple Inc")

How to configure log4j.properties for SpringJUnit4ClassRunner?

I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:

  1. Open run dialog (click the little arrow next to the play button and go to run configurations)
  2. Go to the "classpath" tab
  3. Select the "User Entries" and click the "Advanced" button on the right side.
  4. Now select the "Add External folder" radio button.
  5. Select the resources folder

How to loop through all enum values in C#?

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

What are naming conventions for MongoDB?

Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id.

For example, in a dogs collection, a document would have manual references to external documents named like this:

{
  name: 'fido',
  owner_id: '5358e4249611f4a65e3068ab',
  race_id: '5358ee549611f4a65e3068ac',
  colour: 'yellow'
  ...
}

This follows the Mongo convention of naming _id the identifier for every document.

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Spring Boot: Cannot access REST Controller on localhost (404)

Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Print series of prime numbers in python

How about this? Reading all the suggestions I used this:

prime=[2]+[num for num in xrange(3,m+1,2) if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1))]

Prime numbers up to 1000000

root@nfs:/pywork# time python prime.py

78498

real 0m6.600s

user 0m6.532s

sys 0m0.036s

Installing specific laravel version with composer create-project

To install specific version of laravel try this & simply command on terminal

composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Setup for Linux/Ubuntu/Mint

  1. download Android Studio or SDK only
  2. install
  3. set PATH

3.1) Open terminal and edit ~/.bashrc

sudo su
vim ~/.bashrc

3.2) Export ANDROID_HOME and add folders with binaries to your PATH

Common default install folders:

  • /root/Android/Sdk
  • ~/Android/Sdk

Example .bashrc

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools

3.3) Refresh your PATH

source ~/.bashrc

4) Install correct SDK

When ionic build android still fails it could be because of wrong sdk version. To install correct versions and images run android from command line. Since it is now in your PATH you should be able to run it from anywhere.

Getting Textbox value in Javascript

        <script type="text/javascript">
            function MyFunction() {
                var FNumber = Number(document.getElementById('txtFirstNumber').value);
                var SNumber = Number(document.getElementById("txtSecondNumber").value);
                var Sum = FNumber + SNumber;
                alert(Sum);
            }

        </script>

        <table class="auto-style1">
            <tr>
                <td>FirstNaumber</td>
                <td>
                    <asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>SecondNumber</td>
                <td>
                    <asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
                </td>
            </tr>
        </table>
    </div>
</form>

Show a popup/message box from a Windows batch file

Few more ways.

1) The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages). Works on EVERY windows from XP and above:

;@echo off
;setlocal

;set ppopup_executable=popupe.exe
;set "message2=click OK to continue"
;
;del /q /f %tmp%\yes >nul 2>&1
;
;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1

;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
;
;iexpress /n /q /m %temp%\popup.sed
;%ppopup_executable%
;rem del /q /f %ppopup_executable% >nul 2>&1

;pause

;endlocal
;exit /b 0


[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=0
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=C:\Windows\System32\
[SourceFiles0]
%FILE0%=


[Strings]
AppLaunched=subst.exe
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
FILE0="subst.exe"
DisplayLicense=
InstallPrompt=

2) Using MSHTA. Also works on every windows machine from XP and above (despite the OP do not want "external" languages the JavaScript here is minimized). Should be saved as .bat:

@if (true == false) @end /*!
@echo off
mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
goto :EOF */

alert("Hello, world!");

or in one line:

mshta "about:<script>alert('Hello, world!');close()</script>"

or

mshta "javascript:alert('message');close()"

or

mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")

3) Here's parameterized .bat/jscript hybrid (should be saved as bat). It again uses JavaScript despite the OP request but as it is a bat it can be called as a bat file without worries. It uses POPUP which allows a little bit more control than the more popular MSGBOX. It uses WSH, but not MSHTA like in the example above.

 @if (@x)==(@y) @end /***** jscript comment ******
     @echo off

     cscript //E:JScript //nologo "%~f0" "%~nx0" %*
     exit /b 0

 @if (@x)==(@y) @end ******  end comment *********/


var wshShell = WScript.CreateObject("WScript.Shell");
var args=WScript.Arguments;
var title=args.Item(0);

var timeout=-1;
var pressed_message="button pressed";
var timeout_message="timed out";
var message="";

function printHelp() {
    WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"]  [-message \"pop-up message\"]");
}

if (WScript.Arguments.Length==1){
    runPopup();
    WScript.Quit(0);
}

if (args.Item(1).toLowerCase() == "-help" || args.Item(1).toLowerCase() == "-h" ) {
    printHelp();
    WScript.Quit(0);
}

if (WScript.Arguments.Length % 2 == 0 ) {
    WScript.Echo("Illegal arguments ");
    printHelp();
    WScript.Quit(1);
}

for (var arg = 1 ; arg<args.Length;arg=arg+2) {

    if (args.Item(arg).toLowerCase() == "-title") {
        title = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-timeout") {
        timeout = parseInt(args.Item(arg+1));
        if (isNaN(timeout)) {
            timeout=-1;
        }
    }

    if (args.Item(arg).toLowerCase() == "-tom") {
        timeout_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-pbm") {
        pressed_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-message") {
        message = args.Item(arg+1);
    }
}

function runPopup(){
    var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);

    switch(btn) {
        // button pressed.
        case 1:
            WScript.Echo(pressed_message);
            break;

        // Timed out.
        case -1:
           WScript.Echo(timeout_message);
           break;
    }
}

runPopup();

4) and one jscript.net/.bat hybrid (should be saved as .bat) .This time it uses .NET and compiles a small .exe file that could be deleted:

@if (@X)==(@Y) @end /****** silent jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal


::if exist "%~n0.exe" goto :skip_compilation

:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop



call %jsc% /nologo /out:"%~n0.exe" "%~f0" 
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0

****** end of jscript comment ******/

import System;
import System.Windows;
import System.Windows.Forms

var arguments:String[] = Environment.GetCommandLineArgs();
MessageBox.Show(arguments[1],arguments[0]);

5) and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):

powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")

6) And the dbenham's approach seen here

start "" cmd /c "echo(&echo(&echo              Hello world!     &echo(&pause>nul"

7) For a system tray notifications you can try this:

call SystemTrayNotification.bat  -tooltip warning -time 3000 -title "Woow" -text "Boom" -icon question

How does Facebook disable the browser's integrated Developer Tools?

I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false
});

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    }
    throw "Console is disabled";
}

var l, n = {
        set: function (o) {
            l = o;
        },
        get: function () {
            showWarningAndThrow();
            return l;
        }
    };
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).

References:

removing table border

Use table style Border-collapse at the table level

How to find a user's home directory on linux or unix?

Normally you use the statement

String userHome = System.getProperty( "user.home" );

to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)

How to switch databases in psql?

You can select the database when connecting with psql. This is handy when using it from a script:

sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test

Javascript Iframe innerHTML

You can get html out of an iframe using this code iframe = document.getElementById('frame'); innerHtml = iframe.contentDocument.documentElement.innerHTML

Sum the digits of a number

n = str(input("Enter the number\n"))

list1 = []

for each_number in n:

        list1.append(int(each_number))

print(sum(list1))

How to load CSS Asynchronously

The trick to triggering an asynchronous stylesheet download is to use a <link> element and set an invalid value for the media attribute (I'm using media="none", but any value will do). When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.

<link rel="stylesheet" href="css.css" media="none">

Once the stylesheet has finished downloading the media attribute must be set to a valid value so the style rules will be applied to the document. The onload event is used to switch the media property to all:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'">

This method of loading CSS will deliver useable content to visitors much quicker than the standard approach. Critical CSS can still be served with the usual blocking approach (or you can inline it for ultimate performance) and non-critical styles can be progressively downloaded and applied later in the parsing / rendering process.

This technique uses JavaScript, but you can cater for non-JavaScript browsers by wrapping the equivalent blocking <link> elements in a <noscript> element:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="css.css"></noscript>

You can see the operation in www.itcha.edu.sv

enter image description here

Source in http://keithclark.co.uk/

PSQLException: current transaction is aborted, commands ignored until end of transaction block

In Ruby on Rails PG, I had created a migration, migrated my DB, but forgot to restart my development server. I restarted my server and it worked.

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

What is a regular expression for a MAC Address?

delimiter: ":","-","."

double or single: 00 = 0, 0f = f

/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i

or

/^([0-9a-F]{1,2}[\.:-]){5}([0-9a-F]{1,2})$/


exm: 00:27:0e:2a:b9:aa, 00-27-0E-2A-B9-AA, 0.27.e.2a.b9.aa ...

How to create a sticky footer that plays well with Bootstrap 3

The answer, as Schmalzy points out, can be found here in the examples section of the getbootstrap site.

But that example does not include a top nav. For fixed top nav with sticky footer, see this plnkr, or code below.

Style CSS:

/* Styles go here */

/* Sticky footer styles
-------------------------------------------------- */

html,
body {
  height: 100%;
  /* The html and body elements cannot have any padding or margin. */
}

/* Wrapper for page content to push down footer */
#wrap {
  min-height: 100%;
  height: auto;
  /* Negative indent footer by its height */
  margin: 0 auto -60px;
  /* Pad bottom by footer height */
  padding: 0 0 60px;
}

/* Set the fixed height of the footer here */
#footer {
  height: 60px;
  background-color: #f5f5f5;
}


/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

.container {
  width: auto;
  max-width: 680px;
  padding: 0 15px;
}
.container .credit {
  margin: 20px 0;
}

Index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">

    <title>Sticky Footer Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="style.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <!-- Wrap all page content here -->
    <div id="wrap">

<nav class="navbar navbar-default" role="navigation">
  <!-- Brand and toggle get grouped for better mobile display -->
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- Collect the nav links, forms, and other content for toggling -->
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Link</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
          <li class="divider"></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left" role="search">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div><!-- /.navbar-collapse -->
</nav>

      <!-- Begin page content -->
      <div class="container">

        <div class="page-header">
          <h1>Sticky footer</h1>
        </div>
        <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
        <p>Use <a href="../sticky-footer-navbar">the sticky footer with a fixed navbar</a> if need be, too.</p>
      </div>
    </div><!-- Wrap Div end -->

    <div id="footer">
      <div class="container">
        <p class="text-muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
      </div>
    </div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
  </body>
</html>

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I had almost the same problem but it was just because some .jar library wasn't updated.

I couldn't use @RequestMapping cause that, just "mouse over @RequestMapping" and click on "Fix ..." and the .jar library will be downloading and installing.

How do I detect the Python version at runtime?

Here's some code I use with sys.version_info to check the Python installation:

def check_installation(rv):
    current_version = sys.version_info
    if current_version[0] == rv[0] and current_version[1] >= rv[1]:
        pass
    else:
        sys.stderr.write( "[%s] - Error: Your Python interpreter must be %d.%d or greater (within major version %d)\n" % (sys.argv[0], rv[0], rv[1], rv[0]) )
        sys.exit(-1)
    return 0

...

# Calling the 'check_installation' function checks if Python is >= 2.7 and < 3
required_version = (2,7)
check_installation(required_version)

.NET NewtonSoft JSON deserialize map to a different property name

Json.NET has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:

public class TeamScore
{
    [JsonProperty("eighty_min_score")]
    public string EightyMinScore { get; set; }
    [JsonProperty("home_or_away")]
    public string HomeOrAway { get; set; }
    [JsonProperty("score ")]
    public string Score { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    [JsonProperty("attributes")]
    public TeamScore TeamScores { get; set; }
}

public class RootObject
{
    public List<Team> Team { get; set; }
}

Documentation: Serialization Attributes

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

Linux shell sort file according to the second column?

sort -nk2 file.txt

Accordingly you can change column number.

Can I run a 64-bit VMware image on a 32-bit machine?

It boils down to whether the CPU in your machine has the the VT bit (Virtualization), and the BIOS enables you to turn it on. For instance, my laptop is a Core 2 Duo which is capable of using this. However, my BIOS doesn't enable me to turn it on.

Note that I've read that turning on this feature can slow normal operations down by 10-12%, which is why it's normally turned off.

How to uninstall Ruby from /usr/local?

sudo make uninstall did the trick for me using the Ruby 2.4 tar from the official downloads page.

How display only years in input Bootstrap Datepicker?

For bootstrap 3 datepicker. (Note the capital letters)

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

Read CSV with Scanner()

Scanner.next() does not read a newline but reads the next token, delimited by whitespace (by default, if useDelimiter() was not used to change the delimiter pattern). To read a line use Scanner.nextLine().

Once you read a single line you can use String.split(",") to separate the line into fields. This enables identification of lines that do not consist of the required number of fields. Using useDelimiter(","); would ignore the line-based structure of the file (each line consists of a list of fields separated by a comma). For example:

while (inputStream.hasNextLine())
{
    String line = inputStream.nextLine();
    String[] fields = line.split(",");
    if (fields.length >= 4) // At least one address specified.
    {
        for (String field: fields) System.out.print(field + "|");
        System.out.println();
    }
    else
    {
        System.err.println("Invalid record: " + line);
    }
}

As already mentioned, using a CSV library is recommended. For one, this (and useDelimiter(",") solution) will not correctly handle quoted identifiers containing , characters.

How to convert java.lang.Object to ArrayList?

    Object object = new Object();

    // First way
    List objects1 = new ArrayList<Object>();
    objects1.add(object);

    // second way
    List<Object> objects2 = Arrays.asList(object);

    // Third way
    List<Object> objects3 = Collections.singletonList(object);

Why is my JavaScript function sometimes "not defined"?

I think your javascript code should be placed between tag,there is need of document load

How to generate random colors in matplotlib?

enter code here

import numpy as np

clrs = np.linspace( 0, 1, 18 )  # It will generate 
# color only for 18 for more change the number
np.random.shuffle(clrs)
colors = []
for i in range(0, 72, 4):
    idx = np.arange( 0, 18, 1 )
    np.random.shuffle(idx)
    r = clrs[idx[0]]
    g = clrs[idx[1]]
    b = clrs[idx[2]]
    a = clrs[idx[3]]
    colors.append([r, g, b, a])

Email validation using jQuery

You can create your own function

function emailValidate(email){
    var check = "" + email;
    if((check.search('@')>=0)&&(check.search(/\./)>=0))
        if(check.search('@')<check.split('@')[1].search(/\./)+check.search('@')) return true;
        else return false;
    else return false;
}

alert(emailValidate('[email protected]'));

Can a constructor in Java be private?

Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.

As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.

public class MyClass {
     private final String value;
     private final String type;

     public MyClass(int x){
         this(Integer.toString(x), "int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x), "boolean");
     }

     public String toString(){
         return value;
     }

     public String getType(){
         return type;
     }

     private MyClass(String value, String type){
         this.value = value;
         this.type = type;
     }
}

Edit
Looking at this answer from several years later, I would like to note that this answer is both incomplete and also a little bit extreme. Singletons are indeed an anti-pattern and should generally be avoided where possible; however, there are many uses of private constructors besides singletons, and my answer names only one.

To give a couple more cases where private constructors are used:

  1. To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context).

  2. When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you new ArrayList(5) or ArrayList.createWithCapacity(5), ArrayList.createWithContents(5), ArrayList.createWithInitialSize(5)). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example:

    MyClass myVar = MyClass
        .newBuilder()
        .setOption1(option1)
        .setOption2(option2)
        .build();
    

resource error in android studio after update: No Resource Found

compileSDK should match appCompat version. TargetSDK can still be 22 (e.g. in case you didn't update to the new permission model yet)

How to append a newline to StringBuilder

It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()

Share variables between files in Node.js?

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

How do I remove objects from a JavaScript associative array?

It's very straightforward if you have an Underscore.js dependency in your project -

_.omit(myArray, "lastname")

Restore LogCat window within Android Studio

If all of the above methods does not work then try the below mechanism. Sometimes, the android studio does not show logcat options because of the project you select is not an android project. If you want to debug an APK, create an empty android project then it will start showing the logcat option.

How to invoke the super constructor in Python?

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

Java SSLHandshakeException "no cipher suites in common"

You're initialising your SSLContext with a null KeyManager array.

The key manager is what handles the server certificate (on the server side), and this is what you're probably aiming to set when using javax.net.ssl.keyStore.

However, as described in the JSSE Reference Guide, using null for the first parameter doesn't do what you seem to think it does:

If the KeyManager[] parameter is null, then an empty KeyManager will be defined for this context. If the TrustManager[] parameter is null, the installed security providers will be searched for the highest-priority implementation of the TrustManagerFactory, from which an appropriate TrustManager will be obtained. Likewise, the SecureRandom parameter may be null, in which case a default implementation will be used.

An empty KeyManager doesn't contain any RSA or DSA certificates. Therefore, all the default cipher suites that would rely on such a certificate are disabled. This is why you get all these "Ignoring unavailable cipher suite" messages, which ultimately result in a "no cipher suites in common" message.

If you want your keystore to be used as a keystore, you'll need to load it and initialise a KeyManagerFactory with it:

    KeyStore ks = KeyStore.getInstance("JKS");
    InputStream ksIs = new FileInputStream("...");
    try {
        ks.load(ksIs, "password".toCharArray());
    } finally {
        if (ksIs != null) {
            ksIs.close();
        }
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
            .getDefaultAlgorithm());
    kmf.init(ks, "keypassword".toCharArray());

The use kmf.getKeyManagers() as the first parameter to SSLContext.init().

For the other two parameters, since you're visibly not requesting client-certificate authentication, you should leave the trust manager to its default value (null) instead of copying/pasting a trust manager that's a potential cause of vulnerability, and you can also use the default null SecureRandom.

How to append something to an array?

If you are using the ES6 you can use spread operator to do it.

var arr = [
    "apple",
    "banana",
    "cherry"
];

var arr2 = [
    "dragonfruit",
    "elderberry",
    "fig"
];

arr.push(...arr2);

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

Delete %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache and restart Visual Studio.

Alternatively, use the Clear MEF Component Cache extension.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

java -version
java -showversion

Both commands work In Linux 16.04 LTS

What's the difference between RANK() and DENSE_RANK() functions in oracle?

RANK gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.

DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.

As for nulls, it depends on the ORDER BY clause. Here is a simple test script you can play with to see what happens:

with q as (
select 10 deptno, 'rrr' empname, 10000.00 sal from dual union all
select 11, 'nnn', 20000.00 from dual union all
select 11, 'mmm', 5000.00 from dual union all
select 12, 'kkk', 30000 from dual union all
select 10, 'fff', 40000 from dual union all
select 10, 'ddd', 40000 from dual union all
select 10, 'bbb', 50000 from dual union all
select 10, 'xxx', null from dual union all
select 10, 'ccc', 50000 from dual)
select empname, deptno, sal
     , rank() over (partition by deptno order by sal nulls first) r
     , dense_rank() over (partition by deptno order by sal nulls first) dr1
     , dense_rank() over (partition by deptno order by sal nulls last) dr2
 from q; 

EMP     DEPTNO        SAL          R        DR1        DR2
--- ---------- ---------- ---------- ---------- ----------
xxx         10                     1          1          4
rrr         10      10000          2          2          1
fff         10      40000          3          3          2
ddd         10      40000          3          3          2
ccc         10      50000          5          4          3
bbb         10      50000          5          4          3
mmm         11       5000          1          1          1
nnn         11      20000          2          2          2
kkk         12      30000          1          1          1

9 rows selected.

Here's a link to a good explanation and some examples.

jQuery selector for id starts with specific text

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

Checkout one file from Subversion

I wanted to checkout a single file to a directory, which was not part of a working copy.

Let's get the file at the following URL: http://subversion.repository.server/repository/module/directory/myfile

svn co  http://subversion.repository.server/repository/module/directory/myfile /**directoryb**

So I checked out the given directory containing the target file I wanted to get to a dummy directory, (say etcb for the URL ending with /etc).

Then I emptied the file .svn/entries from all files of the target directory I didn't needed, to leave just the file I wanted. In this .svn/entries file, you have a record for each file with its attributes so leave just the record concerning the file you want to get and save.

Now you need just to copy then ''.svn'' to the directory which will be a new "working copy". Then you just need to:

cp .svn /directory
cd /directory
svn update myfile

Now the directory directory is under version control. Do not forget to remove the directory directoryb which was just a ''temporary working copy''.

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

Switch case in C# - a constant value is expected

Johnnie, Please go through msdn guide on switch. Also, the C# language specification clearly defines the compile time error case:

• If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, bool, char, string, or an enum-type, or if it is the nullable type corresponding to one of these types, then that is the governing type of the switch statement.

• Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.

• Otherwise, if no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.

Hope this helps.

Calling another different view from the controller using ASP.NET MVC 4

            public ActionResult Index()
            {
                return View();
            }


            public ActionResult Test(string Name)
            {
                return RedirectToAction("Index");
            }

Return View Directly displays your view but

Redirect ToAction Action is performed

Convert a String to int?

You can directly convert to an int using the str::parse::<T>() method.

let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();

You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

let my_int: i32 = my_string.parse().unwrap();

As mentioned in the comments, parse() returns a Result. This result will be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32).

jquery animate .css

You can actually still use ".css" and apply css transitions to the div being affected. So continue using ".css" and add the below styles to your stylesheet for "#hfont1". Since ".css" allows for a lot more properties than ".animate", this is always my preferred method.

#hfont1 {
    -webkit-transition: width 0.4s;
    transition: width 0.4s;
}

How to access site through IP address when website is on a shared host?

Include the port number with the IP address.

For example:

http://19.18.20.101:5566

where 5566 is the port number.

AngularJS ng-style with a conditional expression

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

CURL alternative in Python

import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content

This is the simplest I've been able to get it.

Combine Date and Time columns using python pandas

First make sure to have the right data types:

df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_timedelta(df["Time"])

Then you easily combine them:

df["DateTime"] = df["Date"] + df["Time"]

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem.

To find out the exact source of it I switched on logging in web.config file:

<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />

and created logs subfolder in MyWebService root folder.

After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.

How to get a enum value from string in C#?

var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);

This code snippet illustrates obtaining an enum value from a string. To convert from a string, you need to use the static Enum.Parse() method, which takes 3 parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof() followed by the name of the enum class in brackets. The second parameter is the string to be converted, and the third parameter is a bool indicating whether you should ignore case while doing the conversion.

Finally, note that Enum.Parse() actually returns an object reference, that means you need to explicitly convert this to the required enum type(string,int etc).

Thank you.

How to solve "Connection reset by peer: socket write error"?

I had the same problem with small difference:

Exception was raised at the moment of flushing

It is a different stackoverflow issue. The brief explanation was a wrong response header setting:

response.setHeader("Content-Encoding", "gzip");

despite uncompressed response data content.

So the the connection was closed by the browser.

Numpy: Checking if a value is NaT

This approach avoids the warnings while preserving the array-oriented evaluation.

import numpy as np
def isnat(x):
    """ 
    datetime64 analog to isnan.
    doesn't yet exist in numpy - other ways give warnings
    and are likely to change.  
    """
    return x.astype('i8') == np.datetime64('NaT').astype('i8')

How do I disable orientation change on Android?

You can simply use like below in the application class if you want only PORTRAIT mode for all activities in your app.

class YourApplicationName : Application() {

override fun onCreate() {
    super.onCreate()

    registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }

        override fun onActivityStarted(activity: Activity) {

        }

        override fun onActivityResumed(activity: Activity) {

        }

        override fun onActivityPaused(activity: Activity) {

        }

        override fun onActivityStopped(activity: Activity) {

        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

        }

        override fun onActivityDestroyed(activity: Activity) {

        }

    })

}

}

foreach with index

This is your collection

var values = new[] {6, 2, 8, 45, 9, 3, 0};

Make a range of indexes for this collection

var indexes = Enumerable.Range(0, values.Length).ToList();

Use the range to iterate with index

indexes.ForEach(i => values[i] += i);
indexes.ForEach(i => Console.Write("[{0}] = {1}", i, values[i]));

Is there a way that I can check if a data attribute exists?

This is the easiest solution in my opinion is to select all the element which has certain data attribute:

var data = $("#dataTable[data-timer]");
var diffs = [];

for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));

Here is the screenshot of how it works.

console log of the jquery selector

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

In my case I forgot to add @RequestBody annotation to the method argument:

public TestController(@RequestBody KeeperClient testClient) {
        TestController.testClient = testClient;
    }

Adding a dictionary to another

The most obvious way is:

foreach(var kvp in NewAnimals)
   Animals.Add(kvp.Key, kvp.Value); 
  //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue

Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;

foreach(var kvp in NewAnimals)
   animalsAsCollection.Add(kvp);

It's a pity the class doesn't have anAddRangemethod likeList<T> does.

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

Android/Eclipse: how can I add an image in the res/drawable folder?

Copy the image CTRL + C then in Eclipse select drawable folder, right click -> Paste

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());