Programs & Examples On #Convention over configur

ps1 cannot be loaded because running scripts is disabled on this system

The following three steps are used to fix Running Scripts is disabled on this System error

Step1 : To fix this kind of problem, we have to start power shell in administrator mode.

Step2 : Type the following command set-ExecutionPolicy RemoteSigned Step3: Press Y for your Confirmation.

Visit the following for more information https://youtu.be/J_596H-sWsk

How to get URI from an asset File?

try this :

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

I had did it and it worked

What does `m_` variable prefix mean?

The m_ prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:

int m_something

public int Something => this.m_something; 

It can help to have a consistent naming convention for backing variables, and the m_ prefix is one way of doing that - one that works in case-insensitive languages.

How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

bootstrap button shows blue outline when clicked

Even after removing the outline from the button by setting its value to 0, There is still a funny behaviour on the button when clicked, its size shrinks a bit. So i came up with an optimal solution:

.btn:focus {
   outline: none !important;
   box-shadow: 0 0 0 0;
}

Hope this helps...

Byte Array to Image object

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

Pointer arithmetic for void pointer in C

The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

C11 standard §6.2.5

Paragraph - 19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Following program is working fine in GCC compiler.

#include<stdio.h>

int main()
{
    int arr[2] = {1, 2};
    void *ptr = &arr;
    ptr = ptr + sizeof(int);
    printf("%d\n", *(int *)ptr);
    return 0;
}

May be other compilers generate an error.

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...: 
   ...:     print 'Doing stuff!!!'
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

Configuration with name 'default' not found. Android Studio

You are better off running the command in the console to get a better idea on what is wrong with the settings. In my case, when I ran gradlew check it actually tells me which referenced project was missing.

* What went wrong:
Could not determine the dependencies of task ':test'.
Could not resolve all task dependencies for configuration ':testRuntimeClasspath'.
Could not resolve project :lib-blah.
 Required by:
     project :
  > Unable to find a matching configuration of project :lib-blah: None of the consumable configurations have attributes.

The annoying thing was that, it would not show any meaningful error message during the import failure. And if I commented out all the project references, sure it let me import it, but then once I uncomment it out, it would only print that ambiguous message and not tell you what is wrong.

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Using async/await for multiple tasks

I was curious to see the results of the methods provided in the question as well as the accepted answer, so I put it to the test.

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public async Task DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart-testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd-workerStart).TotalSeconds.ToString("F2"), (workerEnd-testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart).Wait());
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWork(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWork(testStart)));
        }
    }
}

And the resulting output:

Starting test: Parallel.ForEach...
Worker 1 started on thread 1, beginning 0.21 seconds after test start.
Worker 4 started on thread 5, beginning 0.21 seconds after test start.
Worker 2 started on thread 3, beginning 0.21 seconds after test start.
Worker 5 started on thread 6, beginning 0.21 seconds after test start.
Worker 3 started on thread 4, beginning 0.21 seconds after test start.
Worker 1 stopped; the worker took 1.90 seconds, and it finished 2.11 seconds after the test start.
Worker 2 stopped; the worker took 3.89 seconds, and it finished 4.10 seconds after the test start.
Worker 3 stopped; the worker took 5.89 seconds, and it finished 6.10 seconds after the test start.
Worker 4 stopped; the worker took 5.90 seconds, and it finished 6.11 seconds after the test start.
Worker 5 stopped; the worker took 8.89 seconds, and it finished 9.10 seconds after the test start.
Test finished after 9.10 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 1, beginning 0.01 seconds after test start.
Worker 2 started on thread 1, beginning 0.01 seconds after test start.
Worker 3 started on thread 1, beginning 0.01 seconds after test start.
Worker 4 started on thread 1, beginning 0.01 seconds after test start.
Worker 5 started on thread 1, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 1, beginning 0.00 seconds after test start.
Worker 2 started on thread 1, beginning 0.00 seconds after test start.
Worker 3 started on thread 1, beginning 0.00 seconds after test start.
Worker 4 started on thread 1, beginning 0.00 seconds after test start.
Worker 5 started on thread 1, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.00 seconds after the test start.
Test finished after 5.00 seconds.

How do you deploy Angular apps?

If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :

Step 1: ng build --prod --env=prod

Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.

Step 3. Creates .htaccess file in root folder and paste this in the .htaccess

 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Best XML Parser for PHP

Hi I think the SimpleXml is very useful . And with it I am using xpath;

$xml = simplexml_load_file("som_xml.xml");

$blocks  = $xml->xpath('//block'); //gets all <block/> tags
$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are   <layout/>  tags

I use many xml configs and this helps me to parse them really fast. SimpleXml is written on C so it's very fast.

Char Comparison in C

I believe you are trying to compare two strings representing values, the function you are looking for is:

int atoi(const char *nptr);

or

long int strtol(const char *nptr, char **endptr, int base);

these functions will allow you to convert a string to an int/long int:

int val = strtol("555", NULL, 10);

and compare it to another value.

int main (int argc, char *argv[])
{
    long int val = 0;
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s number\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    val = strtol(argv[1], NULL, 10);
    printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");

    return 0;
}

How to get autocomplete in jupyter notebook without using tab?

As mentioned by @physicsGuy above, You can use the hinterland extension. Simple steps to do it.

Installing nbextension using conda forge channel. Simply run the below command in conda terminal:

conda install -c conda-forge jupyter_nbextensions_configurator

Next Step enabling the hinterland extension. Run the below command in conda terminal:

jupyter nbextension enable hinterland/hinterland

That's it, done.

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

Length of array in function argument

sizeof only works to find the length of the array if you apply it to the original array.

int a[5]; //real array. NOT a pointer
sizeof(a); // :)

However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.

int a[5];
int * p = a;
sizeof(p); // :(

As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)

There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?

A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)

A second idea is storing the array length next to the array, just like any modern programming language does:

a -> [5];[0,0,0,0,0]

But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:

struct {
    size_t length;
    int * elements;
}

Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?

Android studio - Failed to find target android-18

Thank you RobertoAV96.

You're my hero. But it's not enough. In my case, I changed both compileSdkVersion, and buildToolsVersion. Now it work. Hope this help

buildscript {
       repositories {
           mavenCentral()
       }
       dependencies {
          classpath 'com.android.tools.build:gradle:0.6.+'
       }
   }
   apply plugin: 'android'

   dependencies {
       compile fileTree(dir: 'libs', include: '*.jar')
   }

   android {
       compileSdkVersion 19
       buildToolsVersion "19"

       sourceSets {
           main {
               manifest.srcFile 'AndroidManifest.xml'
               java.srcDirs = ['src']
               resources.srcDirs = ['src']
               aidl.srcDirs = ['src']
               renderscript.srcDirs = ['src']
               res.srcDirs = ['res']
               assets.srcDirs = ['assets']
           }

           // Move the tests to tests/java, tests/res, etc...
           instrumentTest.setRoot('tests')
           // Move the build types to build-types/<type>
           // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ..
           // This moves them out of them default location under src/<type>/... which would
           // conflict with src/ being used by the main source set.
           // Adding new build types or product flavors should be accompanied
           // by a similar customization.
           debug.setRoot('build-types/debug')
           release.setRoot('build-types/release')
       }
   }

How to enable relation view in phpmyadmin

Change your storage engine to InnoDB by going to Operation

'cannot find or open the pdb file' Visual Studio C++ 2013

No problem. You're running your code under the debugger, and the debugger is telling you that it doesn't have debugging information for the system libraries.

If you really need that (usually for stack traces), you can download it from Microsoft's symbol servers, but for now you don't need to worry.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

One way to solve this problem is by turning the warnings off.

SET ANSI_WARNINGS OFF;
GO

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Bootstrap onClick button event

If, like me, you had dynamically created buttons on your page, the

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow here and here.

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

Appending a line break to an output file in a shell script

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

INSERT INTO vs SELECT INTO

  1. Which statement is preferable? Depends on what you are doing.

  2. Are there other performance implications? If the table is a permanent table, you can create indexes at the time of table creation which has implications for performance both negatively and positiviely. Select into does not recreate indexes that exist on current tables and thus subsequent use of the table may be slower than it needs to be.

  3. What is a good use case for SELECT...INTO over INSERT INTO ...? Select into is used if you may not know the table structure in advance. It is faster to write than create table and an insert statement, so it is used to speed up develoment at times. It is often faster to use when you are creating a quick temp table to test things or a backup table of a specific query (maybe records you are going to delete). It should be rare to see it used in production code that will run multiple times (except for temp tables) because it will fail if the table was already in existence.

It is sometimes used inappropriately by people who don't know what they are doing. And they can cause havoc in the db as a result. I strongly feel it is inappropriate to use SELECT INTO for anything other than a throwaway table (a temporary backup, a temp table that will go away at the end of the stored proc ,etc.). Permanent tables need real thought as to their design and SELECT INTO makes it easy to avoid thinking about anything even as basic as what columns and what datatypes.

In general, I prefer the use of the create table and insert statement - you have more controls and it is better for repeatable processes. Further, if the table is a permanent table, it should be created from a separate create table script (one that is in source control) as creating permanent objects should not, in general, in code are inserts/deletes/updates or selects from a table. Object changes should be handled separately from data changes because objects have implications beyond the needs of a specific insert/update/select/delete. You need to consider the best data types, think about FK constraints, PKs and other constraints, consider auditing requirements, think about indexing, etc.

Origin <origin> is not allowed by Access-Control-Allow-Origin

I was facing a problem while calling cross origin resource using ajax from chrome.

I have used node js and local http server to deploy my node js app.

I was getting error response, when I access cross origin resource

I found one solution on that ,

1) I have added below code to my app.js file

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

2) In my html page called cross origin resource using $.getJSON();

$.getJSON("http://localhost:3000/users", function (data) {
    alert("*******Success*********");
    var response=JSON.stringify(data);
    alert("success="+response);
    document.getElementById("employeeDetails").value=response;
});

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Get ID from URL with jQuery

var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

How can I use Python to get the system hostname?

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

Variable not accessible when initialized outside function

Make sure you declare the variable on "root" level, outside any code blocks.

You could also remove the var altogether, although that is not recommended and will throw a "strict" warning.

According to the documentation at MDC, you can set global variables using window.variablename.

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

How do I make the scrollbar on a div only visible when necessary?

try

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

Postgres: How to convert a json string to text?

Mr. Curious was curious about this as well. In addition to the #>> '{}' operator, in 9.6+ one can get the value of a jsonb string with the ->> operator:

select to_jsonb('Some "text"'::TEXT)->>0;
  ?column?
-------------
 Some "text"
(1 row)

If one has a json value, then the solution is to cast into jsonb first:

select to_json('Some "text"'::TEXT)::jsonb->>0;
  ?column?
-------------
 Some "text"
(1 row)

EXEC sp_executesql with multiple parameters

This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.

DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1  nvarchar (100) = 'test1'
DECLARE @xTxt2  nvarchar (500) = 'test2' 
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2

Test if number is odd or even

(bool)($number & 1)

or

(bool)(~ $number & 1)

How do you change the server header returned by nginx?

The last update was a while ago, so here is what worked for me on Ubuntu:

sudo apt-get update
sudo apt-get install nginx-extras

Then add the following two lines to the http section of nginx.conf, which is usually located at /etc/nginx/nginx.conf:

sudo nano /etc/nginx/nginx.conf
server_tokens off; # removed pound sign
more_set_headers 'Server: Eff_You_Script_Kiddies!';

Also, don't forget to restart nginx with sudo service nginx restart.

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

called_from must be null. Add a test against that condition like

if (called_from != null && called_from.equalsIgnoreCase("add")) {

or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)

if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null

Node.js - Find home directory in platform agnostic way

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

How to solve WAMP and Skype conflict on Windows 7?

A small update for the new Skype options window. Please follow this:

Go to Tools ? Options ? Advanced ? Connection and uncheck the box use port 80 and 443 as alternatives for incoming connections.

writing to serial port from linux command line

echo '\x12\x02'

will not be interpreted, and will literally write the string \x12\x02 (and append a newline) to the specified serial port. Instead use

echo -n ^R^B

which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.

The stty command should work, unless another program is interfering. A common culprit is gpsd which looks for GPS devices being plugged in.

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

ImportError: No module named PyQt4

After brew install pyqt, you can brew test pyqt which will use the python you have got in your PATH in oder to do the test (show a Qt window).

For non-brewed Python, you'll have to set your PYTHONPATH as brew info pyqt will tell.

Sometimes it is necessary to open a new shell or tap in order to use the freshly brewed binaries.

I frequently check these issues by printing the sys.path from inside of python: python -c "import sys; print(sys.path)" The $(brew --prefix)/lib/pythonX.Y/site-packages have to be in the sys.path in order to be able to import stuff. As said, for brewed python, this is default but for any other python, you will have to set the PYTHONPATH.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

A more general answer would be to import java.util.Date, then when you need to set a timestamp equal to the current date, simply set it equal to new Date().

Measuring elapsed time with the Time module

You need to import time and then use time.time() method to know current time.

import time

start_time=time.time() #taking current time as starting time

#here your code

elapsed_time=time.time()-start_time #again taking current time - starting time 

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

You can try it like this

  Calendar c= Calendar.getInstance();

  SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
  String str=sdf.format(c.getTime());

What is the default access modifier in Java?

Yes, it is visible in the same package. Anything outside that package will not be allowed to access it.

javascript: Disable Text Select

Simple Copy this text and put on the before </body>

function disableselect(e) {
  return false
}

function reEnable() {
  return true
}

document.onselectstart = new Function ("return false")

if (window.sidebar) {
  document.onmousedown = disableselect
  document.onclick = reEnable
}

Select a random sample of results from a query result

Sample function is used for sample data in ORACLE. So you can try like this:-

SELECT * FROM TABLE_NAME SAMPLE(50);

Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:

SELECT * FROM TABLE_NAME SAMPLE(1);

Hope this can help you.

How do I skip an iteration of a `foreach` loop?

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

This is a MultiThreading Issue and Using Properly Synchronized Blocks This can be prevented. Without putting extra things on UI Thread and causing loss of responsiveness of app.

I also faced the same. And as the most accepted answer suggests making change to adapter data from UI Thread can solve the issue. That will work but is a quick and easy solution but not the best one.

As you can see for a normal case. Updating data adapter from background thread and calling notifyDataSetChanged in UI thread works.

This illegalStateException arises when a ui thread is updating the view and another background thread changes the data again. That moment causes this issue.

So if you will synchronize all the code which is changing the adapter data and making notifydatasetchange call. This issue should be gone. As gone for me and i am still updating the data from background thread.

Here is my case specific code for others to refer.

My loader on the main screen loads the phone book contacts into my data sources in the background.

    @Override
    public Void loadInBackground() {
        Log.v(TAG, "Init loadings contacts");
        synchronized (SingleTonProvider.getInstance()) {
            PhoneBookManager.preparePhoneBookContacts(getContext());
        }
    }

This PhoneBookManager.getPhoneBookContacts reads contact from phonebook and fills them in the hashmaps. Which is directly usable for List Adapters to draw list.

There is a button on my screen. That opens a activity where these phone numbers are listed. If i directly setAdapter over the list before the previous thread finishes its work which is fast naviagtion case happens less often. It pops up the exception .Which is title of this SO question. So i have to do something like this in the second activity.

My loader in the second activity waits for first thread to complete. Till it shows a progress bar. Check the loadInBackground of both the loaders.

Then it creates the adapter and deliver it to the activity where on ui thread i call setAdapter.

That solved my issue.

This code is a snippet only. You need to change it to compile well for you.

@Override
public Loader<PhoneBookContactAdapter> onCreateLoader(int arg0, Bundle arg1) {
    return new PhoneBookContactLoader(this);
}

@Override
public void onLoadFinished(Loader<PhoneBookContactAdapter> arg0, PhoneBookContactAdapter arg1) {
    contactList.setAdapter(adapter = arg1);
}

/*
 * AsyncLoader to load phonebook and notify the list once done.
 */
private static class PhoneBookContactLoader extends AsyncTaskLoader<PhoneBookContactAdapter> {

    private PhoneBookContactAdapter adapter;

    public PhoneBookContactLoader(Context context) {
        super(context);
    }

    @Override
    public PhoneBookContactAdapter loadInBackground() {
        synchronized (SingleTonProvider.getInstance()) {
            return adapter = new PhoneBookContactAdapter(getContext());    
        }
    }

}

Hope this helps

How to tackle daylight savings using TimeZone in Java

public static float calculateTimeZone(String deviceTimeZone) {
    float ONE_HOUR_MILLIS = 60 * 60 * 1000;

    // Current timezone and date
    TimeZone timeZone = TimeZone.getTimeZone(deviceTimeZone);
    Date nowDate = new Date();
    float offsetFromUtc = timeZone.getOffset(nowDate.getTime()) / ONE_HOUR_MILLIS;

    // Daylight Saving time
    if (timeZone.useDaylightTime()) {
        // DST is used
        // I'm saving this is preferences for later use

        // save the offset value to use it later
        float dstOffset = timeZone.getDSTSavings() / ONE_HOUR_MILLIS;
        // DstOffsetValue = dstOffset
        // I'm saving this is preferences for later use
        // save that now we are in DST mode
        if (timeZone.inDaylightTime(nowDate)) {
            Log.e(Utility.class.getName(), "in Daylight Time");
            return -(ONE_HOUR_MILLIS * dstOffset);
        } else {
            Log.e(Utility.class.getName(), "not in Daylight Time");
            return 0;
        }
    } else
        return 0;
}

What is the size of column of int(11) in mysql in bytes?

An INT will always be 4 bytes no matter what length is specified.

  • TINYINT = 1 byte (8 bit)
  • SMALLINT = 2 bytes (16 bit)
  • MEDIUMINT = 3 bytes (24 bit)
  • INT = 4 bytes (32 bit)
  • BIGINT = 8 bytes (64 bit).

The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as int(3) will still show as 12345, but if it was stored as int(10) it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added ZEROFILL it would display as 0000012345.

... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)

Disable same origin policy in Chrome

Don't do this! You're opening your accounts to attacks. Once you do this any 3rd party site can start issuing requests to other websites, sites that you are logged into.

Instead run a local server. It's as easy as opening a shell/terminal/commandline and typing

cd path/to/files
python -m SimpleHTTPServer

Then pointing your browser to

http://localhost:8000

If you find it's too slow consider this solution

Update

People downvoting this answer should go over here and downvote this one too to be consistent. No idea why my answer is so downvoted and the same answer over here is the top voted answer.

You are opening yourself to attacks. Every single 3rd party script you include on your site remotely or locally like via npm can now upload your data or steal your credentials. You are doing something you have no need to do. The suggested solution is not hard, takes 30 seconds, doesn't leave you open attack. Why would you choose to make yourself vulnerable when the better thing to do is so simple?

Telling people to disable security is like telling your friends to leave their front door unlocked and/or a key under the doormat. Sure the odds might be low but if they do get burgled, without proof of forced entry they might have a hard time collecting insurance. Similarly if you disable security you are doing just that disabling security. It's irresponsible to do this when you can solve the issue so simply without disabling security. I'd be surprised if you couldn't be fired at some companies for disabling security.

Manifest Merger failed with multiple errors in Android Studio

In my case my application tag includes:

 <application
    android:name=".common.MyApplication"
    android:allowBackup="false"
    android:extractNativeLibs="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true"
    tools:ignore="GoogleAppIndexingWarning"
    tools:replace="android:appComponentFactory">

I resolved this issue my adding new param as android:appComponentFactory=""

So my final application tag becomes:

<application
    android:name=".common.MyApplication"
    android:allowBackup="false"
    android:extractNativeLibs="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true"
    tools:ignore="GoogleAppIndexingWarning"
    tools:replace="android:appComponentFactory"
    android:appComponentFactory="">

I encountered above issue when I tired using firebase-auth latest version as "19.3.1". Whereas in my project I was already using firebase but version was "16.0.6".

How do I convert a decimal to an int in C#?

I prefer using Math.Round, Math.Floor, Math.Ceiling or Math.Truncate to explicitly set the rounding mode as appropriate.

Note that they all return Decimal as well - since Decimal has a larger range of values than an Int32, so you'll still need to cast (and check for overflow/underflow).

 checked {
   int i = (int)Math.Floor(d);
 }

What is the difference between 'git pull' and 'git fetch'?

Bonus:

In speaking of pull & fetch in the above answers, I would like to share an interesting trick,

git pull --rebase

This above command is the most useful command in my git life which saved a lots of time.

Before pushing your new commits to server, try this command and it will automatically sync latest server changes (with a fetch + merge) and will place your commit at the top in git log. No need to worry about manual pull/merge.

Find details at: http://gitolite.com/git-pull--rebase

What data is stored in Ephemeral Storage of Amazon EC2 instance?

ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store

So Everything will be stored on ephemeral.

if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.

Why can I not create a wheel in python?

Update your pip first:

pip install --upgrade pip

for Python 3:

pip3 install --upgrade pip

Running stages in parallel with Jenkins workflow / pipeline

that syntax is now deprecated, you will get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
       parallel firstTask: {
       ^

WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
       parallel secondTask: {
       ^

2 errors

You should do something like:

stage("Parallel") {
    steps {
        parallel (
            "firstTask" : {
                //do some stuff
            },
            "secondTask" : {
                // Do some other stuff in parallel
            }
        )
    }
}

Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:

pipeline {
  stages {
    stage("Work 1"){
     steps{
      parallel ( "Build common Library":   
            {
              node('<Label>'){
                  /// your stuff
                  }
            },

        "Build Utilities" : {
            node('<Label>'){
               /// your stuff
              }
           }
         )
    }
}

All VMs should be labelled as to use as a pool.

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

jQuery validate: How to add a rule for regular expression validation?

You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use

_x000D_
_x000D_
$("#frm").validate({_x000D_
    rules: {_x000D_
        Textbox: {_x000D_
            pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
        },_x000D_
    },_x000D_
    messages: {_x000D_
        Textbox: {_x000D_
            pattern: 'The Textbox string format is invalid'_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>_x000D_
<form id="frm" method="get" action="">_x000D_
    <fieldset>_x000D_
        <p>_x000D_
            <label for="fullname">Textbox</label>_x000D_
            <input id="Textbox" name="Textbox" type="text">_x000D_
        </p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

In Perl, how do I create a hash whose keys come from a given array?

You could also use Perl6::Junction.

use Perl6::Junction qw'any';

my @arr = ( 1, 2, 3 );

if( any(@arr) == 1 ){ ... }

How do you check if a selector matches something in jQuery?

For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}

How to open a new window on form submit

No need for Javascript, you just have to add a target="_blank" attribute in your form tag.

<form target="_blank" action="http://example.com"
      method="post" id="mc-embedded-subscribe-form"
      name="mc-embedded-subscribe-form" class="validate"
>

Angular2 set value for formGroup

Yes you can use setValue to set value for edit/update purpose.

this.personalform.setValue({
      name: items.name,
      address: {
        city: items.address.city,
        country: items.address.country
      }
    });

You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time

Listing available com ports with Python

Works only on Windows:

import winreg
import itertools

def serial_ports() -> list:
    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)

    ports = []
    for i in itertools.count():
        try:
            ports.append(winreg.EnumValue(key, i)[1])
        except EnvironmentError:
            break

    return ports

if __name__ == "__main__":
    ports = serial_ports()

Android 6.0 multiple permissions

Just include all 4 permissions in the ActivityCompat.requestPermissions(...) call and Android will automatically page them together like you mentioned.

I have a helper method to check multiple permissions and see if any of them are not granted.

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

Or in Kotlin:

fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
    ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}

Then just send it all of the permissions. Android will ask only for the ones it needs.

// The request code used in ActivityCompat.requestPermissions()
// and returned in the Activity's onRequestPermissionsResult()
int PERMISSION_ALL = 1; 
String[] PERMISSIONS = {
  android.Manifest.permission.READ_CONTACTS, 
  android.Manifest.permission.WRITE_CONTACTS, 
  android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
  android.Manifest.permission.READ_SMS, 
  android.Manifest.permission.CAMERA
};

if (!hasPermissions(this, PERMISSIONS)) {
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}

'tuple' object does not support item assignment

PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:

pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)

Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel[0] + 20, 255) or int(255 * (pixel[0] / 255.) ** 0.9) instead of pixel[0] + 20.

And, to be able to handle images in lots of different formats, do image = image.convert("RGB") after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.

Can not get a simple bootstrap modal to work

I was having this same problem using Angular CLI. I needed to import the bootstrap.js.min file in the .angular-cli.json file:

  "scripts": ["../node_modules/jquery/dist/jquery.min.js",
              "../node_modules/bootstrap/dist/js/bootstrap.min.js"],

How to use custom packages

For a project hosted on GitHub, here's what people usually do:

github.com/
  laike9m/
    myproject/
      mylib/
        mylib.go
        ...
      main.go

mylib.go

package mylib

...

main.go

import "github.com/laike9m/myproject/mylib"

...

Parse JSON String into a Particular Object Prototype in JavaScript

See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:

function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
    this.a = 3;
    this.b = 2;
    this.test = function() {return this.a*this.b;};

    // IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
    for (var prop in obj) this[prop] = obj[prop];
}

var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6

// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));

alert(fooJSON.test() ); //Prints 12

Do you recommend using semicolons after every statement in JavaScript?

JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

return
5

JavaScript Interpretation:

return;
5;

Thus, nothing is returned, because of JavaScript's auto semicolon insertion

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Download "PuttyGEN" get publickey and privatekey use gcloud SSH edit and paste your publickey located in /home/USER/.ssh/authorized_keys

sudo vim ~/.ssh/authorized_keys

Tap the i key to paste publicKEY. To save, tap Esc, :, w, q, Enter. Edit the /etc/ssh/sshd_config file.

sudo vim /etc/ssh/sshd_config

Change

PasswordAuthentication no [...] ChallengeResponseAuthentication to no. [...] UsePAM no [...] Restart ssh

/etc/init.d/ssh restart.

the rest config your putty as tutorial NB:choose the pageant add keys and start session would be better

How to execute XPath one-liners from shell?

Install the BaseX database, then use it's "standalone command-line mode" like this:

basex -i - //element@attribute < filename.xml

or

basex -i filename.xml //element@attribute

The query language is actually XQuery (3.0), not XPath, but since XQuery is a superset of XPath, you can use XPath queries without ever noticing.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

How to change title of Activity in Android?

If you're using onCreateOptionsMenu, you can also add setTitle code in onCreateOptionsMenu.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);

    setTitle("Neue Aktivität");
    return true;
}

DataGridView checkbox column - value and functionality

If you have a gridview containing more than one checkbox .... you should try this ....

Object[] o=new Object[6];

for (int i = 0; i < dgverlist.RowCount; i++)
{
    for (int j = 2; j < dgverlist.ColumnCount; j++)
    {
        DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
        ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];

        if (ch1.Value != null)
        {
           o[i] = ch1.OwningColumn.HeaderText.ToString();

            MessageBox.Show(o[i].ToString());
        }
    }
}

How can one tell the version of React running at runtime in the browser?

React.version is what you are looking for.

It is undocumented though (as far as I know) so it may not be a stable feature (i.e. though unlikely, it may disappear or change in future releases).

Example with React imported as a script

_x000D_
_x000D_
const REACT_VERSION = React.version;

ReactDOM.render(
  <div>React version: {REACT_VERSION}</div>,
  document.getElementById('root')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
_x000D_
_x000D_
_x000D_

Example with React imported as a module

import React from 'react';

console.log(React.version);

Obviously, if you import React as a module, it won't be in the global scope. The above code is intended to be bundled with the rest of your app, e.g. using webpack. It will virtually never work if used in a browser's console (it is using bare imports).

This second approach is the recommended one. Most websites will use it. create-react-app does this (it's using webpack behind the scene). In this case, React is encapsulated and is generally not accessible at all outside the bundle (e.g. in a browser's console).

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

Check if password you are using is correct one by running below command

keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit

If you are getting below error then your password is wrong

keytool error: java.security.UnrecoverableKeyException: Cannot recover key

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

Add a summary row with totals

If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

SELECT
  Type = ISNULL(Type, 'Total'),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

SELECT
  Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Command not found after npm install in zsh

For anyone who is still having problem. Don't forget to logout and login again.

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

How to update gradle in android studio?

Open File > Project Structure > Project Tab

enter image description here

Android Studio has built in project structure menu to check and update gradle and plugin used in the current project.

Below Website gives a detailed explanation on how to update gradle and gradle plugin of Android Studio.

Update gradle plugin Android Studio

Testing if value is a function

form.onsubmit will always be a function when defined as an attribute of HTML the form element. It's some sort of anonymous function attached to an HTML element, which has the this pointer bound to that FORM element and also has a parameter named event which will contain data about the submit event.

Under these circumstances I don't understand how you got a string as a result of a typeof operation. You should give more details, better some code.

Edit (as a response to your second edit):

I believe the handler attached to the HTML attribute will execute regardless of the above code. Further more, you could try to stop it somehow, but, it appears that FF 3, IE 8, Chrome 2 and Opera 9 are executing the HTML attribute handler in the first place and then the one attached (I didn't tested with jQuery though, but with addEventListener and attachEvent). So... what are you trying to accomplish exactly?

By the way, your code isn't working because your regular expression will extract the string "valid();", which is definitely not a function.

how to change text box value with jQuery?

If .val() is not working, I would suggest you to use the .attr() attribute

<script>
  $(function() {
    $("your_button").on("click", function() {
      $("your_textbox").val("your value");
    });
  });
</script>

Issue with virtualenv - cannot activate

If wants to open virtual environment on Windows then just remember one thing on giving path use backwards slash not forward.

This is right:

D:\xampp\htdocs\htmldemo\python-virtual-environment>env\Scripts\activate

This is wrong:

D:\xampp\htdocs\htmldemo\python-virtual-environment>env/Scripts/activate

How can I easily add storage to a VirtualBox machine with XP installed?

Newer versions of VirtualBox add an option for VBoxManage clonehd that allows you to clone to an existing (larger) virtual disk.

The process is detailed here: Expanding VirtualBox Dynamic VDIs

Continue For loop

You can use a GoTo:

Do

    '... do stuff your loop will be doing

    ' skip to the end of the loop if necessary:
    If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop 

    '... do other stuff if the condition is not met

ContinueLoop:
Loop

How do I determine k when using k-means clustering?

If you use MATLAB, any version since 2013b that is, you can make use of the function evalclusters to find out what should the optimal k be for a given dataset.

This function lets you choose from among 3 clustering algorithms - kmeans, linkage and gmdistribution.

It also lets you choose from among 4 clustering evaluation criteria - CalinskiHarabasz, DaviesBouldin, gap and silhouette.

How to open a website when a Button is clicked in Android application?

Add this to your button's click listener:

  Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
    try {
        intent.setData(Uri.parse(url));
        startActivity(intent);
    } catch (ActivityNotFoundException exception) {
        Toast.makeText(getContext(), "Error text", Toast.LENGTH_SHORT).show();
    }

If you have a website url as a variable instead of hardcoded string then don't forget to handle an ActivityNotFoundException and show error. Or you may receive invalid url and app will simply crash. (Pass random string instead of url variable and see for youself )

Using AES encryption in C#

You can use password from text box like key... With this code you can encrypt/decrypt text, picture, word document, pdf....

 public class Rijndael
{
    private byte[] key;
    private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };

    ICryptoTransform EnkValue, DekValue;

    public Rijndael(byte[] key)
    {
        this.key = key;
        RijndaelManaged rm = new RijndaelManaged();
        rm.Padding = PaddingMode.PKCS7;
        EnkValue = rm.CreateEncryptor(key, vector);
        DekValue = rm.CreateDecryptor(key, vector);
    }

    public byte[] Encrypt(byte[] byte)
    {

        byte[] enkByte= byte;
        byte[] enkNewByte;
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))
            {
                cs.Write(enkByte, 0, enkByte.Length);
                cs.FlushFinalBlock();

                ms.Position = 0;
                enkNewByte= new byte[ms.Length];
                ms.Read(enkNewByte, 0, enkNewByte.Length);
            }
        }
        return enkNeyByte;
    }

    public byte[] Dekrypt(byte[] enkByte)
    {
        byte[] dekByte;
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))
            {
                cs.Write(enkByte, 0, enkByte.Length);
                cs.FlushFinalBlock();

                ms.Position = 0;
                dekByte= new byte[ms.Length];
                ms.Read(dekByte, 0, dekByte.Length);
            }
        }
        return dekByte;
    }
}

Convert password from text box to byte array...

private byte[] ConvertPasswordToByte(string password)
    {
        byte[] key = new byte[32];
        for (int i = 0; i < passwprd.Length; i++)
        {
            key[i] = Convert.ToByte(passwprd[i]);
        }
        return key;
    }

CSS - Expand float child DIV height to parent's height

For the parent element, add the following properties:

.parent {
    overflow: hidden;
    position: relative;
    width: 100%;
}

then for .child-right these:

.child-right {
    background:green;
    height: 100%;
    width: 50%;
    position: absolute;
    right: 0;
    top: 0;
}

Find more detailed results with CSS examples here and more information about equal height columns here.

How to dynamically create a class?

You can also dynamically create a class by using DynamicObject.

public class DynamicClass : DynamicObject
{
    private Dictionary<string, KeyValuePair<Type, object>> _fields;

    public DynamicClass(List<Field> fields)
    {
        _fields = new Dictionary<string, KeyValuePair<Type, object>>();
        fields.ForEach(x => _fields.Add(x.FieldName,
            new KeyValuePair<Type, object>(x.FieldType, null)));
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_fields.ContainsKey(binder.Name))
        {
            var type = _fields[binder.Name].Key;
            if (value.GetType() == type)
            {
                _fields[binder.Name] = new KeyValuePair<Type, object>(type, value);
                return true;
            }
            else throw new Exception("Value " + value + " is not of type " + type.Name);
        }
        return false;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _fields[binder.Name].Value;
        return true;
    }
}

I store all class fields in a dictionary _fields together with their types and values. The both methods are to can get or set value to some of the properties. You must use the dynamic keyword to create an instance of this class.

The usage with your example:

var fields = new List<Field>() { 
    new Field("EmployeeID", typeof(int)),
    new Field("EmployeeName", typeof(string)),
    new Field("Designation", typeof(string)) 
};

dynamic obj = new DynamicClass(fields);

//set
obj.EmployeeID = 123456;
obj.EmployeeName = "John";
obj.Designation = "Tech Lead";

obj.Age = 25;             //Exception: DynamicClass does not contain a definition for 'Age'
obj.EmployeeName = 666;   //Exception: Value 666 is not of type String

//get
Console.WriteLine(obj.EmployeeID);     //123456
Console.WriteLine(obj.EmployeeName);   //John
Console.WriteLine(obj.Designation);    //Tech Lead

Edit: And here is how looks my class Field:

public class Field
{
    public Field(string name, Type type)
    {
        this.FieldName = name;
        this.FieldType = type;
    }

    public string FieldName;

    public Type FieldType;
}

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

In my case the above suggestions did not work for me. Mine was little different scenario.

When i tried installing bundler using gem install bundler .. But i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

then i tried using sudo gem install bundler then i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
  You don't have write permissions for the /usr/bin directory.

then i tried with sudo gem install bundler -n /usr/local/bin ( Just /usr/bin dint work in my case ).

And then successfully installed bundler

EDIT: I use MacOS, maybe /usr/bin din't work for me for that reason (https://stackoverflow.com/a/34989655/3786657 comment )

disable Bootstrap's Collapse open/close animation

For Bootstrap 3 and 4 it's

.collapsing {
    -webkit-transition: none;
    transition: none;
    display: none;
}

find difference between two text files with one item per line

If you want to use loops You can try like this: (diff and cmp are much more efficient. )

while read line
do
    flag = 0
    while read line2
    do
       if ( "$line" = "$line2" )
        then
            flag = 1
        fi
     done < file1 
     if ( flag -eq 0 )
     then
         echo $line > file3
     fi
done < file2

Note: The program is only to provide a basic insight into what can be done if u dont want to use system calls such as diff n comm..

Counting DISTINCT over multiple columns

How about this,

Select DocumentId, DocumentSessionId, count(*) as c 
from DocumentOutputItems 
group by DocumentId, DocumentSessionId;

This will get us the count of all possible combinations of DocumentId, and DocumentSessionId

Place a button right aligned

In my case the

<p align="right"/>

worked fine

Div 100% height works on Firefox but not in IE

I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."

Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.

How to compare two dates in php

Extending @nevermind's answer, one can use DateTime::createFromFormat: like,

// use - instead of _. replace _ by - if needed.
$format = "d-m-y";
$date1  = DateTime::createFromFormat($format, date('d-m-y'));
$date2  = DateTime::createFromFormat($format, str_replace("_", "-",$date2));    
var_dump($date1 > $date2);

Specify sudo password for Ansible

I don't think ansible will let you specify a password in the flags as you wish to do. There may be somewhere in the configs this can be set but this would make using ansible less secure overall and would not be recommended.

One thing you can do is to create a user on the target machine and grant them passwordless sudo privileges to either all commands or a restricted list of commands.

If you run sudo visudo and enter a line like the below, then the user 'privilegedUser' should not have to enter a password when they run something like sudo service xxxx start:

%privilegedUser ALL= NOPASSWD: /usr/bin/service

What do pty and tty mean?

If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system

Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).

Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .

For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.

internal/modules/cjs/loader.js:582 throw err

The below commands resolved the issue for me.

npm install node-gyp -g
npm install bcrypt -g

npm install bcrypt -save

How can I close a browser window without receiving the "Do you want to close this window" prompt?

In my situation the following code was embedded into a php file.

var PreventExitPop = true;
function ExitPop() {
  if (PreventExitPop != false) {
    return "Hold your horses! \n\nTake the time to reserve your place.Registrations might become paid or closed completely to newcomers!"
  }
}
window.onbeforeunload = ExitPop;

So I opened the console and write the following

PreventExitPop = false

This solved the problem. So, find out the JavaScript code and find the variable(s) and assign them to an appropriate "value" which in my case was "false"

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

How to semantically add heading to a list

Try defining a new class, ulheader, in css. p.ulheader ~ ul selects all that immediately follows My Header

p.ulheader ~ ul {
   margin-top:0;
{
p.ulheader {
   margin-bottom;0;
}

Constructors in JavaScript objects

In most cases you have to somehow declare the property you need before you can call a method that passes in this information. If you do not have to initially set a property you can just call a method within the object like so. Probably not the most pretty way of doing this but this still works.

var objectA = {
    color: ''; 
    callColor : function(){
        console.log(this.color);
    }
    this.callColor(); 
}
var newObject = new objectA(); 

How to send a GET request from PHP?

For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):

$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

How to search for a string in text files?

found = False

def check():
    datafile = file('example.txt')
    for line in datafile:
        if blabla in line:
            found = True
            break
    return found

if check():
    print "true"
else:
    print "false"

Check if string contains a value in array

Simple str_replace with count parameter would work here:

$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
  echo "One of Array value is present in the string.";
}

More Info - https://www.techpurohit.com/extended-behaviour-explode-and-strreplace-php

What is the difference between Serializable and Externalizable in Java?

When considering options for improving performance, don't forget custom serialization. You can let Java do what it does well, or at least good enough, for free, and provide custom support for what it does badly. This is usually a lot less code than full Externalizable support.

Best way to select random rows PostgreSQL

A variation of the materialized view "Possible alternative" outlined by Erwin Brandstetter is possible.

Say, for example, that you don't want duplicates in the randomized values that are returned. So you will need to set a boolean value on the primary table containing your (non-randomized) set of values.

Assuming this is the input table:

id_values  id  |   used
           ----+--------
           1   |   FALSE
           2   |   FALSE
           3   |   FALSE
           4   |   FALSE
           5   |   FALSE
           ...

Populate the ID_VALUES table as needed. Then, as described by Erwin, create a materialized view that randomizes the ID_VALUES table once:

CREATE MATERIALIZED VIEW id_values_randomized AS
  SELECT id
  FROM id_values
  ORDER BY random();

Note that the materialized view does not contain the used column, because this will quickly become out-of-date. Nor does the view need to contain other columns that may be in the id_values table.

In order to obtain (and "consume") random values, use an UPDATE-RETURNING on id_values, selecting id_values from id_values_randomized with a join, and applying the desired criteria to obtain only relevant possibilities. For example:

UPDATE id_values
SET used = TRUE
WHERE id_values.id IN 
  (SELECT i.id
    FROM id_values_randomized r INNER JOIN id_values i ON i.id = r.id
    WHERE (NOT i.used)
    LIMIT 5)
RETURNING id;

Change LIMIT as necessary -- if you only need one random value at a time, change LIMIT to 1.

With the proper indexes on id_values, I believe the UPDATE-RETURNING should execute very quickly with little load. It returns randomized values with one database round-trip. The criteria for "eligible" rows can be as complex as required. New rows can be added to the id_values table at any time, and they will become accessible to the application as soon as the materialized view is refreshed (which can likely be run at an off-peak time). Creation and refresh of the materialized view will be slow, but it only needs to be executed when new id's are added to the id_values table.

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
    return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window and document aren't built-in, they're defined by the browser and most likely enumerable by design.

From ECMA-262 Edition 3:

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum } attribute set on them.


Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum } to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in loop.

Getting index value on razor foreach

IndexOf seems to be useful here.

@foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
    {
       int currentIndex = Model.ItemList.IndexOf(ts);
       @Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)

...

C#: what is the easiest way to subtract time?

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

$ is not a function - jQuery error

That error kicks in when you have forgot to include the jQuery library in your page or there is conflict between libraries - for example you be using any other javascript library on your page.

Take a look at this for more info:

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

Typescript export vs. default export

Here's example with simple object exporting.

var MyScreen = {

    /* ... */

    width : function (percent){

        return window.innerWidth / 100 * percent

    }

    height : function (percent){

        return window.innerHeight / 100 * percent

    }


};

export default MyScreen

In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :

import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );

Any good, visual HTML5 Editor or IDE?

Update

Use Aptana Studio 3, it's upgraded now.

You can either choose

Try online Aloha WYSIWYG Editor

But as a web-developer, I still prefer Notepad++, it has necessary code assists.


Outdated info, please don't refer.


This might be late answer, yeah very late answer, but surely will help someone
Download "Eclipse IDE for Java EE Developers" Latest Stable Version

Download Google Plugin for Eclipse.zip
Select your download according to your Eclipse Version
After Downloading (don't Unzip)
Open Eclipse
Help > Install New Software > Add > Archive > Select the Downloaded Plug-in.zip
in the field "Name" enter "Google Plugin" Click ok.

Ignore the Warnings, After Competion of Installation, Restart Eclipse.


How to use Google Plugin for Eclipse
    File > New > Other > Web > Static Web Project > Enter Project name

Create New Web Project


    Create New HTML File

Create New HTML File


    Name to index.html

index.html

    Select Properties of HTML File

Set Properties to HTML5

    Hit Ctrl+Space

Cheat Sheet HTML5

similarly create new *.css file
Right Click on the css file > Properties > Web Content Settings > Select CSS3 Profile > ok
Hit CTRL+Space
CSS3 Cheat Sheet
Wooo, Yeah Start Coding.!

No Android SDK found - Android Studio

I wanted to share a part of the issue I had because it is the first google result.

I installed Android Studio, when I tried to install my first SDK from the SDK Management windows I got the error that I didn't have any SDK installed. I tried to look on the internet to manually download the .zip,manualy create the folder, no luck what so ever.

When I tried to run the Android Studio as an administrator it detected I didn't have any SDK and prompt me right away at startup to download a SDK.

jQuery - Detect value change on hidden input field

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change events get fired whenever the value of the input element changes:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

How to permanently set $PATH on Linux/Unix?

Permanently add PATH variable

Global:

echo "export PATH=$PATH:/new/path/variable" >> /etc/profile

Local(for user only):

echo "export PATH=$PATH:/new/path/variable" >> ~/.profile

For global restart. For local relogin.

Example

Before:

$ cat /etc/profile 

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin

After:

$ cat /etc/profile 

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Alternatively you can just edit profile:

$ cat /etc/profile 

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Another way(thanks gniourf_gniourf):

echo 'PATH=$PATH:/new/path/variable' >> /etc/profile

You shouldn't use double quotes here! echo 'export PATH=$PATH:/new/path/variable'... And by the way, the export keyword is very likely useless as the PATH variable is very likely already marked as exported. – gniourf_gniourf

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

In my case I needed to install the IIS URL rewrite module 2.0 because it is being used in the web.config and this was the first time running site on new machine.

Generate a heatmap in MatPlotLib using a scatter data set

and the initial question was... how to convert scatter values to grid values, right? histogram2d does count the frequency per cell, however, if you have other data per cell than just the frequency, you'd need some additional work to do.

x = data_x # between -10 and 4, log-gamma of an svc
y = data_y # between -4 and 11, log-C of an svc
z = data_z #between 0 and 0.78, f1-values from a difficult dataset

So, I have a dataset with Z-results for X and Y coordinates. However, I was calculating few points outside the area of interest (large gaps), and heaps of points in a small area of interest.

Yes here it becomes more difficult but also more fun. Some libraries (sorry):

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
from scipy.interpolate import griddata

pyplot is my graphic engine today, cm is a range of color maps with some initeresting choice. numpy for the calculations, and griddata for attaching values to a fixed grid.

The last one is important especially because the frequency of xy points is not equally distributed in my data. First, let's start with some boundaries fitting to my data and an arbitrary grid size. The original data has datapoints also outside those x and y boundaries.

#determine grid boundaries
gridsize = 500
x_min = -8
x_max = 2.5
y_min = -2
y_max = 7

So we have defined a grid with 500 pixels between the min and max values of x and y.

In my data, there are lots more than the 500 values available in the area of high interest; whereas in the low-interest-area, there are not even 200 values in the total grid; between the graphic boundaries of x_min and x_max there are even less.

So for getting a nice picture, the task is to get an average for the high interest values and to fill the gaps elsewhere.

I define my grid now. For each xx-yy pair, i want to have a color.

xx = np.linspace(x_min, x_max, gridsize) # array of x values
yy = np.linspace(y_min, y_max, gridsize) # array of y values
grid = np.array(np.meshgrid(xx, yy.T))
grid = grid.reshape(2, grid.shape[1]*grid.shape[2]).T

Why the strange shape? scipy.griddata wants a shape of (n, D).

Griddata calculates one value per point in the grid, by a predefined method. I choose "nearest" - empty grid points will be filled with values from the nearest neighbor. This looks as if the areas with less information have bigger cells (even if it is not the case). One could choose to interpolate "linear", then areas with less information look less sharp. Matter of taste, really.

points = np.array([x, y]).T # because griddata wants it that way
z_grid2 = griddata(points, z, grid, method='nearest')
# you get a 1D vector as result. Reshape to picture format!
z_grid2 = z_grid2.reshape(xx.shape[0], yy.shape[0])

And hop, we hand over to matplotlib to display the plot

fig = plt.figure(1, figsize=(10, 10))
ax1 = fig.add_subplot(111)
ax1.imshow(z_grid2, extent=[x_min, x_max,y_min, y_max,  ],
            origin='lower', cmap=cm.magma)
ax1.set_title("SVC: empty spots filled by nearest neighbours")
ax1.set_xlabel('log gamma')
ax1.set_ylabel('log C')
plt.show()

Around the pointy part of the V-Shape, you see I did a lot of calculations during my search for the sweet spot, whereas the less interesting parts almost everywhere else have a lower resolution.

Heatmap of a SVC in high resolution

How can I access global variable inside class in Python

You need to move the global declaration inside your function:

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The statement tells the Python compiler that any assignments (and other binding actions) to that name are to alter the value in the global namespace; the default is to put any name that is being assigned to anywhere in a function, in the local namespace. The statement only applies to the current scope.

Since you are never assigning to g_c in the class body, putting the statement there has no effect. The global statement only ever applies to the scope it is used in, never to any nested scopes. See the global statement documentation, which opens with:

The global statement is a declaration which holds for the entire current code block.

Nested functions and classes are not part of the current code block.

I'll insert the obligatory warning against using globals to share changing state here: don't do it, this makes it harder to reason about the state of your code, harder to test, harder to refactor, etc. If you must share a changing singleton state (one value in the whole program) then at least use a class attribute:

class TestClass():
    g_c = 0

    def run(self):
        for i in range(10):
            TestClass.g_c = 1
            print(TestClass.g_c)  # or print(self.g_c)

t = TestClass()
t.run()

print(TestClass.g_c)

Note how we can still access the same value from the outside, namespaced to the TestClass namespace.

Unable to run Java code with Intellij IDEA

My classes contained a main() method yet I was unable to see the Run option. That option was enabled once I marked a folder containing my class files as a source folder:

  1. Right click the folder containing your source
  2. Select Mark Directory as → Test Source Root

Some of the classes in my folder don't have a main() method, but I still see a Run option for those.

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

MySQL Install: ERROR: Failed to build gem native extension

yum -y install gcc mysql-devel ruby-devel rubygems
gem install mysql2

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

How to set shadows in React Native for android?

for an android screen you can use this property elevation.

for example :

 HeaderView:{
    backgroundColor:'#F8F8F8',
    justifyContent:'center',
    alignItems:'center',
    height:60,
    paddingTop:15,

    //Its for IOS
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,

    // its for android 
    elevation: 5,
    position:'relative',

},

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

Meaning of *& and **& in C++

This *& in theory as well as in practical its possible and called as reference to pointer variable. and it's act like same. This *& combination is used in as function parameter for 'pass by' type defining. unlike ** can also be used for declaring a double pointer variable.
The passing of parameter is divided into pass by value, pass by reference, pass by pointer. there are various answer about "pass by" types available. however the basic we require to understand for this topic is.

pass by reference --> generally operates on already created variable refereed while passing to function e.g fun(int &a);

pass by pointer --> Operates on already initialized 'pointer variable/variable address' passing to function e.g fun(int* a);

auto addControl = [](SomeLabel** label, SomeControl** control) {
    *label = new SomeLabel;
    *control = new SomeControl;
    // few more operation further.
};

addControl(&m_label1,&m_control1);
addControl(&m_label2,&m_control2);
addControl(&m_label3,&m_control3);

in the above example(this is the real life problem i came across) i am trying to init few pointer variable from the lambda function and for that we need to pass it by double pointer, so that comes with d-referencing of pointer for its all usage inside of that lambda + while passing pointer in function which takes double pointer, you need to pass reference to the pointer variable.

so with this same thing reference to the pointer variable, *& this combination helps. in below given way for the same example i have mentioned above.

auto addControl = [](SomeLabel*& label, SomeControl*& control) {
        label = new SomeLabel;
        control = new SomeControl;
        // few more operation further.
    };

addControl(m_label1,m_control1);
addControl(m_label2,m_control2);
addControl(m_label3,m_control3);

so here you can see that you neither require d-referencing nor we require to pass reference to pointer variable while passing in function, as current pass by type is already reference to pointer.

Hope this helps :-)

Oracle: is there a tool to trace queries, like Profiler for sql server?

Apparently there is no small simple cheap utility that would help performing this task. There is however 101 way to do it in a complicated and inconvenient manner.

Following article describes several. There are probably dozens more... http://www.petefinnigan.com/ramblings/how_to_set_trace.htm

How do I enumerate through a JObject?

The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

This is the answer that worked for me:

foreach (var x in jobj)
{
    var key = ((JProperty) (x)).Name;
    var jvalue = ((JProperty)(x)).Value ;
}

How to get HTTP response code for a URL in Java?

This has worked for me :

            import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpGet;  
            import org.apache.http.impl.client.DefaultHttpClient;
            import org.apache.http.HttpResponse;
            import java.io.BufferedReader;
            import java.io.InputStreamReader;



            public static void main(String[] args) throws Exception {   
                        HttpClient client = new DefaultHttpClient();
                        //args[0] ="http://hostname:port/xyz/zbc";
                        HttpGet request1 = new HttpGet(args[0]);
                        HttpResponse response1 = client.execute(request1);
                        int code = response1.getStatusLine().getStatusCode();

                         try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
                            // Read in all of the post results into a String.
                            String output = "";
                            Boolean keepGoing = true;
                            while (keepGoing) {
                                String currentLine = br.readLine();          
                                if (currentLine == null) {
                                    keepGoing = false;
                                } else {
                                    output += currentLine;
                                }
                            }
                            System.out.println("Response-->"+output);   
                         }

                         catch(Exception e){
                              System.out.println("Exception"+e);  

                          }


                   }

How to check object is nil or not in swift?

Swift short expression:

var abc = "string"
abc != nil ? doWork(abc) : ()

or:

abc == nil ? () : abc = "string"

or both:

abc != nil ? doWork(abc) : abc = "string"

How to plot all the columns of a data frame in R

You could specify the title (and also the title of the axes via xlab and ylab) with the main option. E.g.:

plot(data[,i], main=names(data)[i])

And if you want to plot (and save) each variable of a dataframe, you should use png, pdf or any other graphics driver you need, and after that issue a dev.off() command. E.g.:

data <- read.csv("sample.csv",header=T,sep=",")
for (i in 1:length(data)) {
    pdf(paste('fileprefix_', names(data)[i], '.pdf', sep='')
    plot(data[,i], ylab=names(data[i]), type="l")
    dev.off()
}

Or draw all plots to the same image with the mfrow paramater of par(). E.g.: use par(mfrow=c(2,2) to include the next 4 plots in the same "image".

How to debug Google Apps Script (aka where does Logger.log log to?)

just debug your spreadsheet code like this:

...
throw whatAmI;
...

shows like this:

enter image description here

How to export table as CSV with headings on Postgresql?

When I don't have permission to write a file out from Postgres I find that I can run the query from the command line.

psql -U user -d db_name -c "Copy (Select * From foo_table LIMIT 10) To STDOUT With CSV HEADER DELIMITER ',';" > foo_data.csv

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

I'm posting my finding in a few of the responses I've seen that didn't mention what I ran into, and apprently this would even defeat BigDump, so check it:

I was trying to load a 500 meg dump via Linux command line and kept getting the "Mysql server has gone away" errors. Settings in my.conf didn't help. What turned out to fix it is...I was doing one big extended insert like:

    insert into table (fields) values (a record, a record, a record, 500 meg of data);

I needed to format the file as separate inserts like this:

    insert into table (fields) values (a record);
    insert into table (fields) values (a record);
    insert into table (fields) values (a record);
    Etc.

And to generate the dump, I used something like this and it worked like a charm:

    SELECT 
        id,
        status,
        email
    FROM contacts
    INTO OUTFILE '/tmp/contacts.sql'
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES STARTING BY "INSERT INTO contacts (id,status,email) values ("
    TERMINATED BY ');\n'

Data truncated for column?

I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.

Solved by altering the table column definition and added value 'a' into the enum set.

Is there a free GUI management tool for Oracle Database Express?

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

jQuery Mobile how to check if button is disabled?

I had the same problem and I found this is working:

if ($("#deliveryNext").attr('disabled')) {
  // do sth if disabled
} else {
  // do sth if enabled 
}

If this gives you undefined then you can use if condition also.

When you evaluate undefined it will return false.

How to make HTML input tag only accept numerical values?

http://www.texotela.co.uk/code/jquery/numeric/ numeric input credits to Leo Vu for mentioning this and of course TexoTela. with a test page.

Laravel: Validation unique on update

public function rules()
{

    switch($this->method())
    {
        case 'GET':
        case 'DELETE':
        {
            return [];
        }
        case 'POST':
        {
            return [
                'name' => 'required|unique:permissions|max:255',
                'display_name' => 'required',
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [                    
                'name' => 'unique:permissions,name,'.$this->get('id').'|max:255',
                'display_name' => 'required',
            ];
        }
        default:break;
    }    
}

How can I create an editable combo box in HTML/Javascript?

Was looking for an Answer as well, but all I could find was outdated.

This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>

If I had not found that, I would have gone with this approach:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

Pass a JavaScript function as parameter

To pass the function as parameter, simply remove the brackets!

function ToBeCalled(){
  alert("I was called");
}

function iNeedParameter( paramFunc) {
   //it is a good idea to check if the parameter is actually not null
   //and that it is a function
   if (paramFunc && (typeof paramFunc == "function")) {
      paramFunc();   
   }
}

//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled); 

The idea behind this is that a function is quite similar to a variable. Instead of writing

function ToBeCalled() { /* something */ }

you might as well write

var ToBeCalledVariable = function () { /* something */ }

There are minor differences between the two, but anyway - both of them are valid ways to define a function. Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:

anotherFunction(ToBeCalledVariable);

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

"Bitmap too large to be uploaded into a texture"

As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

Update Git branches from master

to update your branch from the master:

  git checkout master
  git pull
  git checkout your_branch
  git merge master

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

Swift GET request with parameters

I use:

let dictionary = ["method":"login_user",
                  "cel":mobile.text!
                  "password":password.text!] as  Dictionary<String,String>

for (key, value) in dictionary {
    data=data+"&"+key+"="+value
    }

request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);

Failed to find Build Tools revision 23.0.1

While running react-native In case you have installed 23.0.3 and it is asking for 23.0.1 simply in your application project directory. Open anroid/app/build.gradle and change buildToolsVersion "23.0.3"

enter image description here

Are there any disadvantages to always using nvarchar(MAX)?

Interesting link: Why use a VARCHAR when you can use TEXT?

It's about PostgreSQL and MySQL, so the performance analysis is different, but the logic for "explicitness" still holds: Why force yourself to always worry about something that's relevant a small percentage of the time? If you saved an email address to a variable, you'd use a 'string' not a 'string limited to 80 chars'.

How to update core-js to core-js@3 dependency?

Install

npm i core-js

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

Read: https://www.npmjs.com/package/core-js

Android Studio cannot resolve R in imported project?

In my case:

I had to Copy Reference the R file; i.e. right click gen/<package>/R and Copy Reference. Then paste that over the R in your code where it fails to resolve.

That solved it for me (after trying everything else here). Still not sure why it worked to be honest.

Safe navigation operator (?.) or (!.) and null property paths

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();

This is equvalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}

otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
    // ...
}

can be replaced now with this

if (someObj?.someProperty) {
    // ...
}

Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

Show Error on the tip of the Edit Text Android

I know it's too late, but in case someone still need help. Here is the working solution. Setting an error is pretty straight forward. But it will be displayed to user, when he request Focus on it. So to do the both thing on your own, User this code.

 firstName.setError("Enter FirstName");
 firstName.requestFocus();

Is a LINQ statement faster than a 'foreach' loop?

I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }


    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion


    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}

Custom thread pool in Java 8 parallel stream

Alternatively to the trick of triggering the parallel computation inside your own forkJoinPool you can also pass that pool to the CompletableFuture.supplyAsync method like in:

ForkJoinPool forkJoinPool = new ForkJoinPool(2);
CompletableFuture<List<Integer>> primes = CompletableFuture.supplyAsync(() ->
    //parallel task here, for example
    range(1, 1_000_000).parallel().filter(PrimesPrint::isPrime).collect(toList()), 
    forkJoinPool
);

Open a selected file (image, pdf, ...) programmatically from my Android Application?

You can get any file mime type with getContentResolver().getType(uri):

protected static void openFile(Context context, Uri localUri){
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        i.setDataAndType(localUri, context.getContentResolver().getType(localUri));
        context.startActivity(i);
    }

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

What does "select 1 from" do?

SELECT COUNT(*) in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will always return true irrespective of CONDITIONS are met or not.

NOT EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will always return false irrespective of CONDITIONS are met or not.

SELECT COUNT 1 in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will return true if CONDITIONS are met. Else false.

NOT EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will return false if CONDITIONS are met. Else true.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

Setting up Gradle for api 26 (Android)

Have you added the google maven endpoint?

Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.

Add the endpoint to your build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com'
        }
    }
}

Which can be replaced by the shortcut google() since Android Gradle v3:

allprojects {
    repositories {
        jcenter()
        google()
    }
}

If you already have any maven url inside repositories, you can add the reference after them, i.e.:

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url 'https://maven.google.com'
        }
    }
}

Validation for 10 digit mobile number and focus input field on invalid

I used $form.submit() as it keeps html input validation.

Also I used input type tel as it supported by mobile browsers, only display numeric keypad.

<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>


$('#mob_frm').submit(function(e) {
            e.preventDefault();
            if(!$('#mobile').val().match('[0-9]{10}'))  {
                alert("Please put 10 digit mobile number");
                return;
            }  

        });

compareTo with primitives -> Integer / int

May I propose a third

((Integer) a).compareTo(b)  

Gradle does not find tools.jar

I had this problem when I was trying to run commands through CLI.

It was a problem with system looking at the JRE folder i.e. D:\Program Files\Java\jre8\bin. If we look in there, there is no Tools.jar, hence the error.

You need to find where the JDK is, in my case: D:\Program Files\Java\jdk1.8.0_11, and if you look in the lib directory, you will see Tools.jar.

What I did I created a new environment variable JAVA_HOME: enter image description here

And then you need to edit your PATH variable to include JAVA_HOME, i.e. %JAVA_HOME%/bin; enter image description here

Re-open command prompt and should run.

How to create a button programmatically?

For Swift 5 just the same as Swift 4

 let button = UIButton()
 button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
 button.backgroundColor = UIColor.red
 button.setTitle("Name your Button ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

 @objc func buttonAction(sender: UIButton!) {
    print("Button tapped")
 }

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
                         ^^^^^^^^^^^^^^^^^^^^^^^^

In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.

In CreateReportCardForm, these are your only three inputs:

@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];

Add one for currentReportCardCount and you should be good to go.

Quick way to retrieve user information Active Directory

The reason why your code is slow is that your LDAP query retrieves every single user object in your domain even though you're only interested in one user with a common name of "Adit":

dSearcher.Filter = "(&(objectClass=user))";

So to optimize, you need to narrow your LDAP query to just the user you are interested in. Try something like:

dSearcher.Filter = "(&(objectClass=user)(cn=Adit))";

In addition, don't forget to dispose these objects when done:

  • DirectoryEntry dEntry
  • DirectorySearcher dSearcher

C/C++ line number

Use __LINE__, but what is its type?

LINE The presumed line number (within the current source file) of the current source line (an integer constant).

As an integer constant, code can often assume the value is __LINE__ <= INT_MAX and so the type is int.

To print in C, printf() needs the matching specifier: "%d". This is a far lesser concern in C++ with cout.

Pedantic concern: If the line number exceeds INT_MAX1 (somewhat conceivable with 16-bit int), hopefully the compiler will produce a warning. Example:

format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]

Alternatively, code could force wider types to forestall such warnings.

printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));

Avoid printf()

To avoid all integer limitations: stringify. Code could directly print without a printf() call: a nice thing to avoid in error handling2 .

#define xstr(a) str(a)
#define str(a) #a

fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);

1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.

2 In debugging, sometimes code simply is not working as hoped. Calling complex functions like *printf() can itself incur issues vs. a simple fputs().

Using atan2 to find angle between two vectors

 atan2(vector1.y - vector2.y, vector1.x - vector2.x)

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);

and you may want to normalize it to the range [0, 2 p):

if (angle < 0) { angle += 2 * M_PI; }

or to the range (-p, p]:

if (angle > M_PI)        { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

iOS for VirtualBox

Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'