Programs & Examples On #Nested table

Table containing another table (hierarchical table)

How can I convert an image into Base64 string using JavaScript?

I ended up using a function that returns a Promise.

_x000D_
_x000D_
const getImg64 = async() => {
  const convertImgToBase64URL = (url) => {
  console.log(url)
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
          let canvas = document.createElement('CANVAS')
          const ctx = canvas.getContext('2d')
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL();
          canvas = null;
          resolve(dataURL)
      }
      img.src = url;
    })
  }
  //for the demonstration purposes I used proxy server to avoid cross origin error
  const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
  const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
  console.log(image)
}
getImg64()
_x000D_
_x000D_
_x000D_


You can use this approach in any async function. Then you can just await for the converted image and continue with instructions.

How to set selected value on select using selectpicker plugin from bootstrap

$('.selectpicker').selectpicker('val', '0');

With the '0' being the value of the item you want selected

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

Where does MAMP keep its php.ini?

To be clearer (as i read this thread but didn't SEE the solution, also if it was here!), I have the same problem and found the cause: I were modifying the wrong php.ini!

Yes, there are 2 php.ini files in MAMP:

  1. Applications/MAMP/conf/php5.5.10/php.ini
  2. Applications/MAMP/bin/php/php5.5.10/conf/php.ini

The right php.ini file is the second: Applications/MAMP/bin/php/php5.5.10/conf/php.ini

To prove this, create a .php file (call it as you like, for example "info.php") and put into it a simple phpinfo()

<?php
echo phpinfo();

Open it in your browser and search for "Loaded Configuration File": mine is "/Applications/MAMP/bin/php/php5.5.10/conf/php.ini"

The error was here; i edited Applications/MAMP/conf/php5.5.10/php.ini but this is the wrong file to modify! Infact, the right php.ini file is the one in the bin directory.

Take care of this so small difference that caused me literally 1 and a half hours of headaches!

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

jQuery count number of divs with a certain class?

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

or

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

Python: Find a substring in a string and returning the index of the substring

Here is a simple approach:

my_string = 'abcdefg'
print(text.find('def'))

Output:

3

I the substring is not there, you will get -1. For example:

my_string = 'abcdefg'
print(text.find('xyz'))

Output:

-1

Sometimes, you might want to throw exception if substring is not there:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

Output:

Traceback (most recent call last):

File "test.py", line 6, in print(text.index('xyz'))

ValueError: substring not found

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

How can I parse JSON with C#?

System.Text.Json

.NET core 3.0 comes with System.Text.Json built-in which means you can deserialize/serialize JSON without using a third-party library.

To serialize your class(es) to JSON string:

var json = JsonSerializer.Serialize(order);

To deserialize the JSON into a strongly typed class:

var order = JsonSerializer.Deserialize<Order>(json);

So if you have a class like below:

public class Order
{
    public int Id { get; set; }
    public string OrderNumber { get; set; }
    public decimal Balance { get; set; }
    public DateTime Opened { get; set; }
}

var json = JsonSerializer.Serialize(order);
// creates JSON ==>
{
    "id": 123456,
    "orderNumber": "ABC-123-456",
    "balance": 9876.54,
    "opened": "2019-10-21T23:47:16.85",
};

var order = JsonSerializer.Deserialize<Order>(json);
// ==> creates the above class

One thing to note is that System.Text.Json does not automatically handle camelCase JSON properties when using your own code (however, it does when using MVC/WebAPI requests and the model binder).

To resolve this you need to pass JsonSerializerOptions as a parameter.

JsonSerializerOptions options = new JsonSerializerOptions
{        
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,  // set camelCase       
    WriteIndented = true                                // write pretty json
};

// pass options to serializer
var json = JsonSerializer.Serialize(order, options);
// pass options to deserializer
var order = JsonSerializer.Deserialize<Order>(json, options);

System.Text.Json is also available for .Net Framework and .Net Standard as a Nu-get package System.Text.Json

How to run TestNG from command line

Ok after 2 days of trying to figure out why I couldn't run the example from

http://www.tutorialspoint.com/testng/testng_environment.htm the following code did not work for me

C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml

The fix for it is as follows: I came to the following conclusion: First off install eclipse, and download the TestNG plugin. After that follow the instructions from the tutorial to create and compile the test class from cmd using javac, and add the testng.xml. To run the testng.xml on windows 10 cmd run the following line:

java -cp C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*;C:\Test org.testng.TestNG testng.xml

to clarify: C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\* The path above represents the location of jcommander.jar and testng.jar that you downloaded by installing the TESTNG plugin for eclipse. The path may vary so to be sure just open the installation location of eclipse, go to plugins and search for jcommander.jar. Then copy that location and after that add * to select all the necessary .jars.

C:\Test  

The path above represents the location of the testing.xml in your project. After getting all the necessary paths, append them by using ";".

I hope I have been helpful to some of you guys :)

Replace console output in Python

It can be done without using the sys library if we look at the print() function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here is my code:

def update(n):
    for i in range(n):
        print("i:",i,sep='',end="\r",flush=True)
        #time.sleep(1)

Insert image after each list item

For IE8 support, the "content" property cannot be empty.

To get around this I've done the following :

.ul li:after {
    content:"icon";
    text-indent:-999em;
    display:block;
    width:32px;
    height:32px;
    background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
    margin:5% 0 0 45%;
}

Note : This works with image sprites too

ImportError: cannot import name main when running pip --version command in windows7 32 bit

i fixed the problem by reinstalling pip using get-pip.py.

  1. Download get-pip from official link: https://pip.pypa.io/en/stable/installing/#upgrading-pip
  2. run it using commande: python get-pip.py.

And pip is fixed and work perfectly.

how to find 2d array size in c++

#include <bits/stdc++.h>
using namespace std;


int main(int argc, char const *argv[])
{
    int arr[6][5] = {
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5}
    };
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(arr[0][0]);
    cout<<rows<<" "<<cols<<endl;
    return 0;
}

Output: 6 5

Unable to auto-detect email address

it's pretty simple but tricky at the first time.
For example:
If my email is [email protected] type:

git config --global user.email [email protected]

OR

If my username is mrsuicidesheep type:

git config user.name mrsuicidesheep

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Try this:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider NuGet -Force

Set-PSRepository PSGallery -InstallationPolicy Trusted

Remove duplicate rows in MySQL

In Order to duplicate records with unique columns, e.g. COL1,COL2, COL3 should not be replicated (suppose we have missed 3 column unique in table structure and multiple duplicate entries have been made into the table)

DROP TABLE TABLE_NAME_copy;
CREATE TABLE TABLE_NAME_copy LIKE TABLE_NAME;
INSERT INTO TABLE_NAME_copy
SELECT * FROM TABLE_NAME
GROUP BY COLUMN1, COLUMN2, COLUMN3; 
DROP TABLE TABLE_NAME;
ALTER TABLE TABLE_NAME_copy RENAME TO TABLE_NAME;

Hope will help dev.

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

How to Store Historical Data

In SQL Server 2016 and above, there is a new feature called Temporal Tables that aims to solve this challenge with minimal effort from developer. The concept of temporal table is similar to Change Data Capture (CDC), with the difference that temporal table has abstracted most of the things that you had to do manually if you were using CDC.

HTTP Basic Authentication - what's the expected web browser experience?

You might have old invalid username/password cached in your browser. Try clearing them and check again.

If you are using IE and somesite.com is in your Intranet security zone, IE may be sending your windows credentials automatically.

Could not connect to React Native development server on Android

This is most probably a firewall issue. If someone using ubuntu faces this issue , then you can use

sudo service iptables stop

to disable the firewall for the port to be accessible

PHP Regex to check date is in YYYY-MM-DD format

preg_match needs a / or another char as delimiter.

preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$date)

you also should check for validity of that date so you wouldn't end up with something like 9999-19-38

bool checkdate ( int $month , int $day , int $year )

psql: FATAL: Peer authentication failed for user "dev"

In my case I was using different port. Default is 5432. I was using 5433. This worked for me:

$ psql -f update_table.sql -d db_name -U db_user_name -h 127.0.0.1 -p 5433

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

wamp server does not start: Windows 7, 64Bit

You can open the Windows event viewer to try to get more information about the errors : in the "Application" section of the Windows logs, there is a good chance you will find error messages from Apache. (At least I found what was wrong in my case there !)

How to access pandas groupby dataframe by key

You can use the get_group method:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient than creating the naive dictionary with dict(iter(gb)). This is because it uses data-structures already available in the groupby object.


You can select different columns using the groupby slicing:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64

Summernote image upload

UPLOAD IMAGES WITH PROGRESS BAR

Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.

HTML

<progress></progress>

<div id="summernote"></div>

JS

// initialise editor

$('#summernote').summernote({
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
});

// send the file

function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                return myXhr;
            },
            url: root + '/assets/scripts/php/app/uploadEditorImages.php',
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                editor.insertImage(welEditable, url);
            }
        });
}

// update progress bar

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded, max:e.total});
        // reset progress on complete
        if (e.loaded == e.total) {
            $('progress').attr('value','0.0');
        }
    }
}

What does "Changes not staged for commit" mean

What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

What is ANSI format?

ANSI (aka Windows-1252/WinLatin1) is a character encoding of the Latin alphabet, fairly similar to ISO-8859-1. You may want to take a look of it at Wikipedia.

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

ASP.NET Web API session or something?

Now in 2017 with ASP.Net Core you can do it as explained here.

The Microsoft.AspNetCore.Session package provides middleware for managing session state.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

From the Docs: Introduction to session and application state in ASP.NET Core

Already tested on a working project

How to display databases in Oracle 11g using SQL*Plus

Maybe you could use this view, but i'm not sure.

select * from v$database;

But I think It will only show you info about the current db.

Other option, if the db is running in linux... whould be something like this:

SQL>!grep SID $TNS_ADMIN/tnsnames.ora | grep -v PLSExtProc

Return list using select new in LINQ

Your method's return value has to be a List<Project>.

Using select new you are creating an instance of an anonymous type, instead of a Project.

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

How to install PIP on Python 3.6?

pip is bundled with Python > 3.4

On Unix-like systems use:

python3.6 -m pip install [Package_to_install]

On a Windows system use:

py -m pip install [Package_to_install]

(On Windows you may need to run the command prompt as administrator to be able to write into python installation directory)

Hover and Active only when not disabled

You can use :enabled pseudo-class, but notice IE<9 does not support it:

button:hover:enabled{
    /*your styles*/
}
button:active:enabled{
    /*your styles*/
}

How to fix the "508 Resource Limit is reached" error in WordPress?

I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.

Create a rounded button / button with border-radius in Flutter

New Elevate Button-------->

    style --->
    
    customElevatedButton({radius, color}) => ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(radius == null ? 100 : radius),
          ),
          primary: color,
        );



icon--->

    Widget saveIcon() => iconsStyle1(
          Icons.save,
        );

//common icon style

    iconsStyle1(icon) => Icon(
          icon,
          color: white,
          size: 15,
        );

button use---> 
    ElevatedButton.icon(
                            icon: saveIcon(),
                            style:
                                customElevatedButton(color: Colors.green[700]),
                            label: Text('Save',
                                style: TextStyle(color: Colors.white)),
                            onPressed: () {
                            },
                          ),

Can we locate a user via user's phone number in Android?

Yess, possible with conditions:

If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!

In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).

1* App sends SMS to user's phone

Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )

2* App receives SMS at user's phone from the SMS sender

Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)

3* App gets location coordinates of the user's phone

Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.

4* App sends location coordinates to the SMS sender via SMS

Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.

(Those 4 yesses for you :) )

Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:

  • Listen for location changes (GPS, Network or Cell Id)
  • Send user location periodically(Ex: each 2 hours) or when user position changed!
  • Stock user locations in file and create a map based on daily locations
  • Receive SMS and update user location
  • Receive server app commend and update user location
  • Send events when user go inside or outside of a defined circle
  • Listen for what user say and record it or open live voip call :s
  • Maybe anything you think or u want to do :) !

And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->

The final user will accept for something like that (those permissions of an android app u asked about):

This app has access to these permissions:

Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration

Your location -approximate location (network-based) -precise location (GPS and network-based)

Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)

Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity

Phone calls -read phone status and identity -directly call phone numbers

Storage -modify or delete the contents of your USB storage

Your applications information -retrieve running apps -close other apps -run at startup

Bluetooth -pair with Bluetooth devices -access Bluetooth settings

Camera -take pictures and videos

Other Application UI -draw over other apps

Microphone -record audio

Lock screen -disable your screen lock

Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream

Development tools -read sensitive log data

System tools -modify system settings -send sticky broadcast -test access to protected storage

Affects battery -control vibration -prevent device from sleeping

Audio settings -change your audio settings

Sync Settings -read sync settings -toggle sync on and off -read sync statistics

Wallpaper -set wallpaper

How can I get the image url in a Wordpress theme?

You need to use

 <?php bloginfo('template_directory'); ?>

It returns the directory of the current WordPress theme.

Now for example, if your theme has some image named example.jpg inside some folder name subfolder folder in the images folder.

 themes
   |-> your theme
          |-> images
                |->subfolder
                      |-> examples.jpg

You access it like this

 <img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
    public int s_id;
    public String s_name, c_name, dob;
}
class Program
{
    static void Main(string[] args)
    {
        student[] arr = new student[4];

        for(int i = 0; i < 4; i++)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");


            arr[i].s_id = Int32.Parse(Console.ReadLine());
            arr[i].s_name = Console.ReadLine();
            arr[i].c_name = Console.ReadLine();
            arr[i].s_dob = Console.ReadLine();
       }
    }
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

Writing to a new file if it doesn't exist, and appending to a file if it does

Just open it in 'a' mode:

a   Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

with open(filename, 'a') as f:
    f.write(...)

To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.

with open('somefile.txt', 'a') as f:
    if f.tell() == 0:
        print('a new file or the file was empty')
        f.write('The header\n')
    else:
        print('file existed, appending')
    f.write('Some data\n')

If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.

Parsing JSON with Unix tools

Following MartinR and Boecko's lead:

$ curl -s 'http://twitter.com/users/username.json' | python -mjson.tool

That will give you an extremely grep friendly output. Very convenient:

$ curl -s 'http://twitter.com/users/username.json' | python -mjson.tool | grep my_key

How to format strings using printf() to get equal length in the output

You can specify a width on string fields, e.g.

printf("%-20s", "initialization...");

And then whatever's printed with that field will be blank-padded to the width you indicate.

The - left-justifies your text in that field.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

Difference between jQuery parent(), parents() and closest() functions

from http://api.jquery.com/closest/

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

.parent()

  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.

Here are related threads:

How to select the rows with maximum values in each group with dplyr?

Try this:

result <- df %>% 
             group_by(A, B) %>%
             filter(value == max(value)) %>%
             arrange(A,B,C)

Seems to work:

identical(
  as.data.frame(result),
  ddply(df, .(A, B), function(x) x[which.max(x$value),])
)
#[1] TRUE

As pointed out in the comments, slice may be preferred here as per @RoyalITS' answer below if you strictly only want 1 row per group. This answer will return multiple rows if there are multiple with an identical maximum value.

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

Regular expressions inside SQL Server

stored value in DB is: 5XXXXXX [where x can be any digit]

You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

Use:

WHERE CHARINDEX(column, '5') = 1
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

i have also different cases like XXXX7XX for example, so it has to be generic.

Use:

WHERE PATINDEX('%7%', column) = 5
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

Regex Support

SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:

  • 5\d{6} for your first example
  • \d{4}7\d{2} for your second example

For more info on regular expressions, I highly recommend this website.

How to set host_key_checking=false in ansible inventory file?

Due to the fact that I answered this in 2014, I have updated my answer to account for more recent versions of ansible.

Yes, you can do it at the host/inventory level (Which became possible on newer ansible versions) or global level:

inventory:

Add the following.

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

host:

Add the following.

ansible_ssh_extra_args='-o StrictHostKeyChecking=no'

hosts/inventory options will work with connection type ssh and not paramiko. Some people may strongly argue that inventory and hosts is more secure because the scope is more limited.

global:

Ansible User Guide - Host Key Checking

  • You can do it either in the /etc/ansible/ansible.cfg or ~/.ansible.cfg file:

    [defaults]
    host_key_checking = False
    
  • Or you can setup and env variable (this might not work on newer ansible versions):

    export ANSIBLE_HOST_KEY_CHECKING=False
    

How to Initialize char array from a string

const char S[] = "ABCD";

This should work. i use this notation only and it works perfectly fine for me. I don't know how you are using.

Responsive Google Map?

in the iframe tag, you can easily add width='100%' instead of the preset value giving to you by the map

like this:

 <iframe src="https://www.google.com/maps/embed?anyLocation" width="100%" height="400" frameborder="0" style="border:0;" allowfullscreen=""></iframe>

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

How can I force clients to refresh JavaScript files?

The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.

This is how I did it:

$(document).ready(function(){
    $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
         startProgram();
    });
});

Check the function at http://api.jquery.com/jQuery.getScript/

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

JPA or JDBC, how are they different?

Main difference between JPA and JDBC is level of abstraction.

JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC.

Scroll to element on click in Angular 4

You can achieve that by using the reference to an angular DOM element as follows:

Here is the example in stackblitz

the component template:

<div class="other-content">
      Other content
      <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
        Click to scroll
      </button>
    </div>
    <div id="content" #element>
      Some text to scroll
</div>

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Convert array of indices to 1-hot encoded numpy array

You can use the following code for converting into a one-hot vector:

let x is the normal class vector having a single column with classes 0 to some number:

import numpy as np
np.eye(x.max()+1)[x]

if 0 is not a class; then remove +1.

Pointers, smart pointers or shared pointers?

To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++

  • Reference counted (e.g. boost::shared_ptr / std::tr1:shared_ptr)
  • non reference counted (e.g. boost::scoped_ptr / std::auto_ptr)

The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.

(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)

Singleton with Arguments in Java

You can add a configurable initialization method in order to separate instantiation from getting.

public class Singleton {
    private static Singleton singleton = null;
    private final int x;

    private Singleton(int x) {
        this.x = x;
    }

    public static Singleton getInstance() {
        if(singleton == null) {
            throw new AssertionError("You have to call init first");
        }

        return singleton;
    }

    public synchronized static Singleton init(int x) {
        if (singleton != null)
        {
            // in my opinion this is optional, but for the purists it ensures
            // that you only ever get the same instance when you call getInstance
            throw new AssertionError("You already initialized me");
        }

        singleton = new Singleton(x);
        return singleton;
    }

}

Then you can call Singleton.init(123) once to configure it, for example in your app startup.

Is it possible to run selenium (Firefox) web driver without a GUI?

maybe you need to set your window-size dimension. just like:

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--window-size=1920x1080');

browser = webdriver.Chrome(options=options,executable_path = './chromedriver')

if also not working, try increase window-size dimension.

How to remove decimal part from a number in C#

If you just need the integer part of the double then use explicit cast to int.

int number = (int) a;

You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

React Router Pass Param to Component

Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to property of the <Link /> component. The search parameters can later be accessed via new URLSearchParams();

<Link 
  key={id} 
  to={{
    pathname: this.props.match.url + '/' + foo,
    search: '?foo=' + foo
  }} />

<Route path="/details/:foo" component={DetailsPage}/>

export default class DetailsPage extends Component {

    state = {
        foo: ''
    }

    componentDidMount () {
        this.parseQueryParams();
    }

    componentDidUpdate() {
        this.parseQueryParams();
    }

    parseQueryParams () {
        const query = new URLSearchParams(this.props.location.search);
        for (let param of query.entries()) {
            if (this.state.foo!== param[1]) {
                this.setState({foo: param[1]});
            }
        }
    }

      render() {
        return(
          <div>
            <h2>{this.state.foo}</h2>
          </div>
        )
      }
    }

How to prompt for user input and read command-line arguments

This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.

import argparse
import sys

try:
     parser = argparse.ArgumentParser()
     parser.add_argument("square", help="display a square of a given number",
                type=int)
    args = parser.parse_args()

    #print the square of user input from cmd line.
    print args.square**2

    #print all the sys argument passed from cmd line including the program name.
    print sys.argv

    #print the second argument passed from cmd line; Note it starts from ZERO
    print sys.argv[1]
except:
    e = sys.exc_info()[0]
    print e

1) To find the square root of 5

C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5

2) Passing invalid argument other than number

C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>

Running .sh scripts in Git Bash

I was having two .sh scripts to start and stop the digital ocean servers that I wanted to run from the Windows 10. What I did is:

  • downloaded "Git for Windows" (from https://git-scm.com/download/win).
  • installed Git
  • to execute the .sh script just double-clicked the script file it started the execution of the script.

Now to run the script each time I just double-click the script

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Adapting dplyr::ntile to take advantage of data.table optimizations provides a faster solution.

library(data.table)
setDT(temp)
temp[order(value) , quartile := floor( 1 + 4 * (.I-1) / .N)]

Probably doesn't qualify as cleaner, but it's faster and one-line.

Timing on bigger data set

Comparing this solution to ntile and cut for data.table as proposed by @docendo_discimus and @MichaelChirico.

library(microbenchmark)
library(dplyr)

set.seed(123)

n <- 1e6
temp <- data.frame(name=sample(letters, size=n, replace=TRUE), value=rnorm(n))
setDT(temp)

microbenchmark(
    "ntile" = temp[, quartile_ntile := ntile(value, 4)],
    "cut" = temp[, quartile_cut := cut(value,
                                       breaks = quantile(value, probs = seq(0, 1, by=1/4)),
                                       labels = 1:4, right=FALSE)],
    "dt_ntile" = temp[order(value), quartile_ntile_dt := floor( 1 + 4 * (.I-1)/.N)]
)

Gives:

Unit: milliseconds
     expr      min       lq     mean   median       uq      max neval
    ntile 608.1126 647.4994 670.3160 686.5103 691.4846 712.4267   100
      cut 369.5391 373.3457 375.0913 374.3107 376.5512 385.8142   100
 dt_ntile 117.5736 119.5802 124.5397 120.5043 124.5902 145.7894   100

Detecting when a div's height changes using jQuery

These days you can also use the Web API ResizeObserver.

Simple example:

const resizeObserver = new ResizeObserver(() => {
    console.log('size changed');
});

resizeObserver.observe(document.querySelector('#myElement'));

How can I switch word wrap on and off in Visual Studio Code?

Word wrap settings redesign

Here are the new word wrap options:

editor.wordWrap: "off" - Lines will never wrap.
editor.wordWrap: "on" - Lines will wrap at viewport width.
editor.wordWrap: "wordWrapColumn" - Lines will wrap at the value of editor.wordWrapColumn.
editor.wordWrap: "bounded" 

Lines will wrap at the minimum of viewport width and the value of editor.wordWrapColumn.

What does "static" mean in C?

A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:

void func(void) {
    static int count; // If you don't declare its value, it is initialized with zero
    printf("%d, ", count);
    ++count;
}

int main(void) {
    while(true) {
        func();
    }
    return 0;
}

The output:

0, 1, 2, 3, 4, 5, ...

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

How to assign name for a screen?

I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:

#!/bin/bash
screen -d -r tab$1

where first argument is the tab number.

How can I select an element with multiple classes in jQuery?

You can use getElementsByClassName() method for what you want.

_x000D_
_x000D_
var elems = document.getElementsByClassName("a b c");_x000D_
elems[0].style.color = "green";_x000D_
console.log(elems[0]);
_x000D_
<ul>_x000D_
  <li class="a">a</li>_x000D_
  <li class="a b">a, b</li>_x000D_
  <li class="a b c">a, b, c</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

This is the fastest solution also. you can see a benchmark about that here.

How can I search for a commit message on GitHub?

This works well from within Eclipse, until GitHub adds the feature:

Enter image description here

EGit/User Guide, Searching for commits

Could not establish secure channel for SSL/TLS with authority '*'

Here is what fixed for me:

1) Make sure you are running Visual Studio as Administrator

2) Install and run winhttpcertcfg.exe to grant access

https://msdn.microsoft.com/en-us/library/windows/desktop/aa384088(v=vs.85).aspx

The command is similar to below: (enter your certificate subject and service name)

winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "NetworkService"
winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "LOCAL SERVICE"
winhttpcertcfg -g -c LOCAL_MACHINE\MY -s "certificate subject" -a "My Apps Service Account"

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

What does "where T : class, new()" mean?

This is part of the Generics mechanism, where the where keyword add constraints to what types must implement in order to be used as type parameters.

Can I hide the HTML5 number input’s spin box?

I've encountered this problem with a input[type="datetime-local"], which is similar to this problem.

And I've found a way to overcome this kind of problems.

First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"

Then you can see all shadowed DOM elements, for example, for <input type="number">, the full element with shadowed DOM is:

_x000D_
_x000D_
<input type="number">_x000D_
  <div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
    <div id="editing-view-port">_x000D_
      <div id="inner-editor"></div>_x000D_
    </div>_x000D_
    <div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
  </div>_x000D_
</input>
_x000D_
_x000D_
_x000D_

shadow DOM of input[type="number"

And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Vlookup referring to table data in a different sheet

There might be something wrong with your formula if you are looking from another sheet maybe you have to change Sheet1 to Sheet2 ---> =VLOOKUP(M3,Sheet2!$A$2:$Q$47,13,FALSE) --- Where Sheet2 is your table array

Can you split/explode a field in a MySQL query?

I used the above logic but modified it slightly. My input is of format : "apple:100|pinapple:200|orange:300" stored in a variable @updtAdvanceKeyVal

Here is the function block :

set @res = "";

set @i = 1;
set @updtAdvanceKeyVal = updtAdvanceKeyVal;

REPEAT


 -- set r =  replace(SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
 --  LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1),"|","");

-- wrapping the function in "replace" function as above causes to cut off a character from
 -- the 2nd splitted value if the value is more than 3 characters. Writing it in 2 lines causes no such problem and the output is as expected
-- sample output by executing the above function :
-- orange:100
-- pi apple:200    !!!!!!!!strange output!!!!!!!!
-- tomato:500

      set @r =  SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
                  LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1);

      set @r = replace(@r,"|","");

      if @r <> "" then

              set @key = SUBSTRING_INDEX(@r, ":",1);
              set @val = SUBSTRING_INDEX(@r, ":",-1);

              select @key, @val;
      end if;

      set @i = @i + 1;

     until @r = ""
END REPEAT;

VSCode: How to Split Editor Vertically

I just found a simple solution. You can drag an opened file and move towards the four sides of the Editor, it will show a highlighted area that you can drop to. It will split the view automatically, either horizontally, vertically, or even into three rows.

VSCode v1.30.2

Update: you can also drag a file from the Explorer to split the Editor in the same way above.

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

How to make a script wait for a pressed key?

I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.

How to print GETDATE() in SQL Server with milliseconds in time?

SELECT CONVERT( VARCHAR(24), GETDATE(), 113)

UPDATE

PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

In python version >= 2.7 and in python 3:

d = {el:0 for el in a}

How to get response status code from jQuery.ajax?

I see the status field on the jqXhr object, here is a fiddle with it working:

http://jsfiddle.net/magicaj/55HQq/3/

$.ajax({
    //...        
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    } 
});

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

Sanitizing strings to make them URL and filename safe?

This is a nice way to secure an upload filename:

$file_name = trim(basename(stripslashes($name)), ".\x00..\x20");

What does SQL clause "GROUP BY 1" mean?

That means sql group by 1st column in your select clause, we always use this GROUP BY 1 together with ORDER BY 1, besides you can also use like this GROUP BY 1,2,3.., of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized

Laravel Fluent Query Builder Join with subquery

You can use following addon to handle all subquery related function from laravel 5.5+

https://github.com/maksimru/eloquent-subquery-magic

User::selectRaw('user_id,comments_by_user.total_count')->leftJoinSubquery(
  //subquery
  Comment::selectRaw('user_id,count(*) total_count')
      ->groupBy('user_id'),
  //alias
  'comments_by_user', 
  //closure for "on" statement
  function ($join) {
      $join->on('users.id', '=', 'comments_by_user.user_id');
  }
)->get();

This IP, site or mobile application is not authorized to use this API key

Disable both direction api and geocoding api and re-enable.

it works for only 5-10 seconds and than automatically disabled itself.

it means you have only 5-10 sec to test you assignment.

Web API optional parameters

Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

You can do the following:

foreach (Control X in this.Controls)
{
    TextBox tb = X as TextBox;
    if (tb != null)
    {
        string text = tb.Text;
        // Do something to text...
        tb.Text = string.Empty; // Clears it out...
    }
}

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

Pointer to class data member "::*"

I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.

Trim leading and trailing spaces from a string in awk

Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).

I would use sed:

sed 's/, /,/' input.txt

This will remove on leading space after the , . Output:

Name,Order
Trim,working
cat,cat1

More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,:

sed 's/,[ \t]\?/,/g' input.txt

It will also work with more than two columns because of the global modifier /g


@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:

sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt

*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *


IMO sed is the optimal tool for this job. However, here comes a solution with awk because you've asked for that:

awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt

Another simple solution that comes in mind to remove all whitespaces is tr -d:

cat input.txt | tr -d ' '

How to map atan2() to degrees 0-360

The R packages geosphere will calculate bearingRhumb, which is a constant bearing line given an origin point and easting/northing. The easting and northing must be in a matrix or vector. The origin point for a wind rose is 0,0. The following code seems to readily resolve the issue:

windE<-wind$uasE
windN<-wind$vasN
wind_matrix<-cbind(windE, windN)
wind$wind_dir<-bearingRhumb(c(0,0), wind_matrix)
wind$wind_dir<-round(wind$wind_dir, 0)

estimating of testing effort as a percentage of development time

When you speak of tests, you could mean waterfall or agile test development. In an agile environment, developers should spend 50% of their time developing and maintaining tests.

But that 50% extra will save you time when the re-factoring and manual verification time comes.

Best way to serialize/unserialize objects in JavaScript?

I tried to do this with Date with native JSON...

function stringify (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) {
      if (this[k] instanceof Date) {
        return ['$date', +this[k]]
      }
      return v
    }
  )
}

function clone<T> (obj: T): T {
  return JSON.parse(
    stringify(obj),
    (_, v) => (Array.isArray(v) && v[0] === '$date') ? new Date(v[1]) : v
  )
}

What does this say? It says

  • There needs to be a unique identifier, better than $date, if you want it more secure.
class Klass {
  static fromRepr (repr: string): Klass {
    return new Klass(...)
  }

  static guid = '__Klass__'

  __repr__ (): string {
    return '...'
  }
}

This is a serializable Klass, with

function serialize (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) { return this[k] instanceof Klass ? [Klass.guid, this[k].__repr__()] : v }
  )
}

function deserialize (repr: string) {
  return JSON.parse(
    repr,
    (_, v) => (Array.isArray(v) && v[0] === Klass.guid) ? Klass.fromRepr(v[1]) : v
  )
}

I tried to do it with Mongo-style Object ({ $date }) as well, but it failed in JSON.parse. Supplying k doesn't matter anymore...

BTW, if you don't care about libraries, you can use yaml.dump / yaml.load from js-yaml. Just make sure you do it the dangerous way.

Convert DateTime to TimeSpan

In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:

var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;

    TimeSpan DateTimeToTimeSpan(DateTime? ts)
    {
        if (!ts.HasValue) return TimeSpan.Zero;
        else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
    }

XAML :

<Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />

If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds.

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

Changing user agent on urllib2.urlopen

Setting the User-Agent from everyone's favorite Dive Into Python.

The short story: You can use Request.add_header to do this.

You can also pass the headers as a dictionary when creating the Request itself, as the docs note:

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib2‘s default user agent string is "Python-urllib/2.6" (on Python 2.6).

Access to ES6 array element index inside for-of loop

In this world of flashy new native functions, we sometimes forget the basics.

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}

Clean, efficient, and you can still break the loop. Bonus! You can also start from the end and go backwards with i--!

Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i]; at the top of the loop for an easy, readable reference.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Got stuck as I was trying to a go get ... I think it was related to git. Here is how was able to fix it ...

  1. I entered the following in terminal:

    sudo xcodebuild -license
    
  2. This will open the agreement. Go all the way to end and type "agree".

That takes care of go get issues.

It was quite interesting how unrelated things were.

How to implement swipe gestures for mobile devices?

I looked at several solutions but all failed with scroll and select text being the biggest confusion. Instead of scrolling right I was closing boxes and such.

I just finished my implementation that does it all for me.

https://github.com/webdevelopers-eu/jquery-dna-gestures

It is MIT so do what you want - and yes, it is really simple - 800 bytes minified. You can check it out on my (under-development) site https://cyrex.tech - swiperight on touch-devices should dismiss popup windows.

UITextField border color

borderColor on any view(or UIView Subclass) could also be set using storyboard with a little bit of coding and this approach could be really handy if you're setting border color on multiple UI Objects.

Below are the steps how to achieve it,

  1. Create a category on CALayer class. Declare a property of type UIColor with a suitable name, I'll name it as borderUIColor .
  2. Write the setter and getter for this property.
  3. In the 'Setter' method just set the "borderColor" property of layer to the new colors CGColor value.
  4. In the 'Getter' method return UIColor with layer's borderColor.

P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.

Please have a look at the below code sample;

Objective C:

Interface File:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer (BorderProperties)

// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;

@end

Implementation File:

#import "CALayer+BorderProperties.h"

@implementation CALayer (BorderProperties)

- (void)setBorderUIColor:(UIColor *)color {
    self.borderColor = color.CGColor;
}

- (UIColor *)borderUIColor {
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Swift 2.0:

extension CALayer {
var borderUIColor: UIColor {
    set {
        self.borderColor = newValue.CGColor
    }

    get {
        return UIColor(CGColor: self.borderColor!)
    }
}
}

And finally go to your storyboard/XIB, follow the remaining steps;

  1. Click on the View object for which you want to set border Color.
  2. Click on "Identity Inspector"(3rd from Left) in "Utility"(Right side of the screen) panel.
  3. Under "User Defined Runtime Attributes", click on the "+" button to add a key path.
  4. Set the type of the key path to "Color".
  5. Enter the value for key path as "layer.borderUIColor". [Remember this should be the variable name you declared in category, not borderColor here it's borderUIColor].
  6. Finally chose whatever color you want.

You've to set layer.borderWidth property value to at least 1 to see the border color.

Build and Run. Happy Coding. :)

Error parsing yaml file: mapping values are not allowed here

Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:

someKey: another key: Change to make today: work out more

should be

someKey: another key: "Change to make today: work out more"

Using sudo with Python script

To pass the password to sudo's stdin:

#!/usr/bin/env python
from subprocess import Popen, PIPE

sudo_password = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()

p = Popen(['sudo', '-S'] + command, stdin=PIPE, stderr=PIPE,
          universal_newlines=True)
sudo_prompt = p.communicate(sudo_password + '\n')[1]

Note: you could probably configure passwordless sudo or SUDO_ASKPASS command instead of hardcoding your password in the source code.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Can't connect to MySQL server on 'localhost' (10061) after Installation

The simple solution that worked for me is: change localhost to 127.0.0.1 in your database.yml or in your script if writing one.

How do I launch a program from command line without opening a new cmd window?

Add /B, as documented in the command-line help for start:

C:\>start /?
Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
  [command/program] [parameters]

"title"     Title to display in window title bar.
path        Starting directory.
B           Start application without creating a new window. The
            application has ^C handling ignored. Unless the application
            enables ^C processing, ^Break is the only way to interrupt
            the application.

WHERE clause on SQL Server "Text" data type

Please try this

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR, CastleType) = 'foo'

Bash loop ping successful

You probably shouldn't rely on textual output of a command to decide this, especially when the ping command gives you a perfectly good return value:

The ping utility returns an exit status of zero if at least one response was heard from the specified host; a status of two if the transmission was successful but no responses were received; or another value from <sysexits.h> if an error occurred.

In other words, use something like:

((count = 100))                            # Maximum number to try.
while [[ $count -ne 0 ]] ; do
    ping -c 1 8.8.8.8                      # Try once.
    rc=$?
    if [[ $rc -eq 0 ]] ; then
        ((count = 1))                      # If okay, flag to exit loop.
    fi
    ((count = count - 1))                  # So we don't go forever.
done

if [[ $rc -eq 0 ]] ; then                  # Make final determination.
    echo `say The internet is back up.`
else
    echo `say Timeout.`
fi

How to get current foreground activity context in android?

(Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733)

DO NOT USE PREVIOUS (waqas716) answer.

You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html

To avoid this, you should manage activities references. Add the name of the application in the manifest file:

<application
    android:name=".MyApp"
    ....
 </application>

Your application class :

  public class MyApp extends Application {
        public void onCreate() {
              super.onCreate();
        }

        private Activity mCurrentActivity = null;
        public Activity getCurrentActivity(){
              return mCurrentActivity;
        }
        public void setCurrentActivity(Activity mCurrentActivity){
              this.mCurrentActivity = mCurrentActivity;
        }
  }

Create a new Activity :

public class MyBaseActivity extends Activity {
    protected MyApp mMyApp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMyApp = (MyApp)this.getApplicationContext();
    }
    protected void onResume() {
        super.onResume();
        mMyApp.setCurrentActivity(this);
    }
    protected void onPause() {
        clearReferences();
        super.onPause();
    }
    protected void onDestroy() {        
        clearReferences();
        super.onDestroy();
    }

    private void clearReferences(){
        Activity currActivity = mMyApp.getCurrentActivity();
        if (this.equals(currActivity))
            mMyApp.setCurrentActivity(null);
    }
}

So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :

Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

sys.argv[1] meaning in script

Just adding to Frederic's answer, for example if you call your script as follows:

./myscript.py foo bar

sys.argv[0] would be "./myscript.py" sys.argv[1] would be "foo" and sys.argv[2] would be "bar" ... and so forth.

In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.

var Obj1 = [
    {id:1, name:'Sandra'},
    {id:2, name:'John'},   
];

var Obj2 = [
    {_id:2, name:'John'},
    {_id:4, name:'Bobby'}
];

var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
    return o1['id'] === o2['_id']
});

console.log(Obj3);
//  {id:1, name:'Sandra'}

Access mysql remote database from command line

simply put this on terminal at ubuntu:

mysql -u username -h host -p

Now hit enter

terminal will ask you password, enter the password and you are into database server

How to resolve symbolic links in a shell script

To work around the Mac incompatibility, I came up with

echo `php -r "echo realpath('foo');"`

Not great but cross OS

Uninstall mongoDB from ubuntu

I suggest the following to make sure everything is uninstalled:

sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev

sudo apt-get purge mongodb-10gen

sudo apt-get autoremove

This should also remove your config from

 /etc/mongodb.conf.

If you want to clean up completely and you might also want to remove the data directory

/var/lib/mongodb

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

Gson: Is there an easier way to serialize a map

Default

The default Gson implementation of Map serialization uses toString() on the key:

Gson gson = new GsonBuilder()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will give:

{
  "java.awt.Point[x\u003d1,y\u003d2]": "a",
  "java.awt.Point[x\u003d3,y\u003d4]": "b"
}


Using enableComplexMapKeySerialization

If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:

Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will return:

[
  [
    {
      "x": 1,
      "y": 2
    },
    "a"
  ],
  [
    {
      "x": 3,
      "y": 4
    },
    "b"
  ]
]

More details can be found here.

JavaScript load a page on button click

Just window.location = "http://wherever.you.wanna.go.com/", or, for local links, window.location = "my_relative_link.html".

You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/".

Also note that the protocol part of the URL (http://) is not optional for absolute links; omitting it will make javascript assume a relative link.

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

tl;dr

java.sql.Timestamp.from (
    LocalDate.of ( 2007 , 9 , 23 )
             .atStartOfDay( ZoneId.of ( "America/Montreal" ) )
             .toInstant()
)

java.time

Let’s update this page by showing code using the java.time framework built into Java 8 and later.

These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.

In java.time, an Instant is a moment on the timeline in UTC. A ZonedDateTime is an Instant adjusted into a time zone (ZoneId).

Time zone is crucial here. A date of September 23, 2007 cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.

Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0 because of Daylight Saving Time and possibly other anomalies.

Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.

Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM’s current default time zone to its date-time value when generating a string representation via its toString method. Here you see my America/Los_Angeles time zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601 formats.

LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;

Dump to console.

System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );

When run.

d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0

By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp.

  • PreparedStatement.setObject
  • ResultSet.getObject

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

How to append rows in a pandas dataframe in a for loop?

A more compact and efficient way would be perhaps:

cols = ['frame', 'count']
N = 4
dat = pd.DataFrame(columns = cols)
for i in range(N):

    dat = dat.append({'frame': str(i), 'count':i},ignore_index=True)

output would be:

>>> dat
   frame count
0     0     0
1     1     1
2     2     2
3     3     3

About the Full Screen And No Titlebar from manifest

In AndroidManifest.xml, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"in application tag.

Individual activities can override the default by setting their own theme attributes.

How to determine if a point is in a 2D triangle?

Here is an efficient Python implementation:

def PointInsideTriangle2(pt,tri):
    '''checks if point pt(2) is inside triangle tri(3x2). @Developer'''
    a = 1/(-tri[1,1]*tri[2,0]+tri[0,1]*(-tri[1,0]+tri[2,0])+ \
        tri[0,0]*(tri[1,1]-tri[2,1])+tri[1,0]*tri[2,1])
    s = a*(tri[2,0]*tri[0,1]-tri[0,0]*tri[2,1]+(tri[2,1]-tri[0,1])*pt[0]+ \
        (tri[0,0]-tri[2,0])*pt[1])
    if s<0: return False
    else: t = a*(tri[0,0]*tri[1,1]-tri[1,0]*tri[0,1]+(tri[0,1]-tri[1,1])*pt[0]+ \
              (tri[1,0]-tri[0,0])*pt[1])
    return ((t>0) and (1-s-t>0))

and an example output:

enter image description here

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

Asynchronous file upload (AJAX file upload) using jsp and javascript

I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).

SWFUpload is a good start : http://www.swfupload.org/documentation

jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.

Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html

How to clear a notification in Android

Starting with API level 18 (Jellybean MR2) you can cancel Notifications other than your own via NotificationListenerService.

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}

...

private void clearNotificationExample(StatusBarNotification sbn) {
    myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}

Is this how you define a function in jQuery?

First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.

Here's an example:

$(document).ready( function () {

    var MyBlah = function($blah) { alert($blah);  };

    MyBlah("Hello this works") // Inside the anonymous function we are cool.

 });

MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)

This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.

Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.

Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).

Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:

$('div#message').myBlah("hello")

See also: http://www.re-cycledair.com/creating-jquery-plugins

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

phonegap open link in browser

None of these answers are explicit enough to get external links to open in each platform. As per the inAppBrowser docs:

Install

cordova plugin add cordova-plugin-inappbrowser

Overwrite window.open (optional, but recommended for simplicity)

window.open = cordova.InAppBrowser.open;

If you don't overwrite window.open, you will be using the native window.open function, and can't expect to get the same results cross-platform.

Use it to open links in default browser

window.open(your_href_value, '_system');

Note that the target for the inAppBrowser (which is what the plugin name suggests it is to be used for) is '_blank', instead of '_system'.


Without the steps above, I was not able to get links to open in the default browser app cross-platform.

Extra credit

Here's an example (live) click handler for the links:

document.addEventListener('click', function (e) {
    if (e.target.tagName === 'A' &&
        e.target.href.match(/^https?:\/\//)) {
        e.preventDefault();
        window.open(e.target.href, '_system');
    }
});

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

How to view the Folder and Files in GAC?

I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:

  1. Launch regedit.
  2. Navigate to HKLM\Software\Microsoft\Fusion
  3. Add a DWORD called DisableCacheViewer and set the value to 1.

For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.

  1. Launch a Command Prompt at your account's privilege level.
  2. Type SUBST Z: C:\Windows\assembly
    • Z can be any free drive letter.
  3. Open My Computer and look in the new substitute directory.
  4. To remove the virtual drive from Command Prompt, type SUBST Z: /D

As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.

uncaught syntaxerror unexpected token U JSON

Most common case of this error happening is using template that is generating the control then changing the way id and/or nameare being generated by 'overriding' default template with something like

@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} )

and then forgetting to change ValidationMessageFor to

@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] })    

Hope this saves you some time.

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none
    

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

How do I center a window onscreen in C#?

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

jQuery iframe load() event?

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar(10) is a fixed-length Unicode string of length 10. nvarchar(10) is a variable-length Unicode string with a maximum length of 10. Typically, you would use the former if all data values are 10 characters and the latter if the lengths vary.

How do you remove a specific revision in the git history?

Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD and use this to remove <commit-id> from the branch you're on:

git rebase --onto <commit-id>^ <commit-id>

How to mkdir only if a directory does not already exist?

The old tried and true

mkdir /tmp/qq >/dev/null 2>&1

will do what you want with none of the race conditions many of the other solutions have.

Sometimes the simplest (and ugliest) solutions are the best.

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

React.js: Set innerHTML vs dangerouslySetInnerHTML

You can bind to dom directly

<div dangerouslySetInnerHTML={{__html: '<p>First &middot; Second</p>'}}></div>

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

How to read values from the querystring with ASP.NET Core?

Some of the comments mention this as well, but asp net core does all this work for you.

If you have a query string that matches the name it will be available in the controller.

https://myapi/some-endpoint/123?someQueryString=YayThisWorks

[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
    {
        Debug.WriteLine(someValue);
        Debug.WriteLine(someQueryString);
        return Ok();
    }

Ouputs:

123

YayThisWorks

How to ignore the first line of data when processing CSV data?

just add [1:]

example below:

data = pd.read_csv("/Users/xyz/Desktop/xyxData/xyz.csv", sep=',', header=None)**[1:]**

that works for me in iPython

Check with jquery if div has overflowing elements

Here's a pure jQuery solution, but it's rather messy:

var div_height = $(this).height();
var vertical_div_top_position = $(this).offset().top;
var lastchild_height = $(this).children('p:last-child').height();
var vertical_lastchild_top_position = $(this).children('p:last-child').offset().top;
var vertical_lastchild_bottom_position = lastchild_height + vertical_lastchild_top_position;
var real_height = vertical_lastchild_bottom_position - vertical_div_top_position;

if (real_height > div_height){
    //overflow div
}

How to round each item in a list of floats to 2 decimal places?

mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList =  [round(x,2) for x in mylist] 
# [0.3, 0.5, 0.2]

Convert multiple rows into one with comma as separator

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

source: http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

get next and previous day with PHP

Simply use this

echo date('Y-m-d',strtotime("yesterday"));
echo date('Y-m-d',strtotime("tomorrow"));

Eclipse - debugger doesn't stop at breakpoint

Usually when this happens to me (rare but it does) means that the code being executed is different than the code in the editor. It will happen from time to time for Eclipse that the built classes and the code in editor are out of sync. When that happens I get all sort of weird debugger behavior (debugging empty lines, skipping lines of codes etc).

Restarting Eclipse, clean all projects and rebuild everything usually clears things up. I had also the Maven plugins (older versions... had not had it for a while now) that had a tendency to do that too.

Otherwise it might be a bug, maybe the one Vineet stated,

Hope this helps

How to remove constraints from my MySQL table?

The simplest way to remove constraint is to use syntax ALTER TABLE tbl_name DROP CONSTRAINT symbol; introduced in MySQL 8.0.19:

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name

ALTER TABLE tbl_magazine_issue DROP CONSTRAINT FK_tbl_magazine_issue_mst_users;

db<>fiddle demo

Git pushing to remote branch

You can push your local branch to a new remote branch like so:

git push origin master:test

(Assuming origin is your remote, master is your local branch name and test is the name of the new remote branch, you wish to create.)

If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u (on newer versions of Git) or --set-upstream, so:

git push -u origin master:test

or

git push --set-upstream origin master:test

...will create a new remote branch, named test, in remote repository origin, based on your local master, and setup your local master to track it.

Inconsistent Accessibility: Parameter type is less accessible than method

If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).

Giving the type the public modifier would fix it.

Another approach is to make both the type and the method internal, if that is your intent.

The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.

How to list all `env` properties within jenkins pipeline job?

Here's a quick script you can add as a pipeline job to list all environment variables:

node {
    echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
}

This will list both system and Jenkins variables.

How to get first object out from List<Object> using Linq

You can do

Component depCountry = lstComp
                       .Select(x => x.ComponentValue("Dep"))
                       .FirstOrDefault();

Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

var newDictionary = dic.Select(x => new 
            {
               Key = x.Key,
               Value = x.Value.Select( y => 
                      {
                          depCountry = y.ComponentValue("Dep")
                      }).FirstOrDefault()
             }
             .Where(x => x.Value != null)
             .ToDictionary(x => x.Key, x => x.Value());

This will give you a new dictionary. You can access the values

var myTest = newDictionary[key1].depCountry     

Random numbers with Math.random() in Java

Google is right :-)

Google's formula creates numbers between: min and max Your formula creates numbers between: min and (min+max)

Get Android API level of phone currently running my application

try this :Float.valueOf(android.os.Build.VERSION.RELEASE) <= 2.1

Swing vs JavaFx for desktop applications

I'd look around to find some (3rd party?) components that do what you want. I've had to create custom Swing components for an agenda view where you can book multiple resources, as well as an Excel-like grid that works well with keyboard navigation and so on. I had a terrible time getting them to work nicely because I needed to delve into many of Swing's many intricacies whenever I came upon a problem. Mouse and focus behaviour and a lot of other things can be very difficult to get right, especially for a casual Swing user. I would hope that JavaFX is a bit more future-orientated and smooth out of the box.

How to find integer array size in java

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

Error: " 'dict' object has no attribute 'iteritems' "

As answered by RafaelC, Python 3 renamed dict.iteritems -> dict.items. Try a different package version. This will list available packages:

python -m pip install yourOwnPackageHere==

Then rerun with the version you will try after == to install/switch version

Tool to Unminify / Decompress JavaScript

In Firefox, SpiderMonkey and Rhino you can wrap any code into an anonymous function and call its toSource method, which will give you a nicely formatted source of the function.

toSource also strips comments.

E. g.:

(function () { /* Say hello. */ var x = 'Hello!'; print(x); }).toSource()

Will be converted to a string:

function () {
    var x = "Hello!";
    print(x);
}

P. S.: It's not an "online tool", but all questions about general beautifying techniques are closed as duplicates of this one.

avrdude: stk500v2_ReceiveMessage(): timeout

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

How to test code dependent on environment variables using JUnit?

In a similar situation like this where I had to write Test Case which is dependent on Environment Variable, I tried following:

  1. I went for System Rules as suggested by Stefan Birkner. Its use was simple. But sooner than later, I found the behavior erratic. In one run, it works, in the very next run it fails. I investigated and found that System Rules work well with JUnit 4 or higher version. But in my cases, I was using some Jars which were dependent on JUnit 3. So I skipped System Rules. More on it you can find here @Rule annotation doesn't work while using TestSuite in JUnit.
  2. Next I tried to create Environment Variable through Process Builder class provided by Java. Here through Java Code we can create an environment variable, but you need to know the process or program name which I did not. Also it creates environment variable for child process, not for the main process.

I wasted a day using the above two approaches, but of no avail. Then Maven came to my rescue. We can set Environment Variables or System Properties through Maven POM file which I think best way to do Unit Testing for Maven based project. Below is the entry I made in POM file.

    <build>
      <plugins>
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <systemPropertyVariables>
              <PropertyName1>PropertyValue1</PropertyName1>                                                          
              <PropertyName2>PropertyValue2</PropertyName2>
          </systemPropertyVariables>
          <environmentVariables>
            <EnvironmentVariable1>EnvironmentVariableValue1</EnvironmentVariable1>
            <EnvironmentVariable2>EnvironmentVariableValue2</EnvironmentVariable2>
          </environmentVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>

After this change, I ran Test Cases again and suddenly all worked as expected. For reader's information, I explored this approach in Maven 3.x, so I have no idea on Maven 2.x.

How to build and fill pandas dataframe from for loop?

I may be wrong, but I think the accepted answer by @amit has a bug.

from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]

# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]

# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)

# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))

Node.js setting up environment specific configs to be used with everyauth

The way we do this is by passing an argument in when starting the app with the environment. For instance:

node app.js -c dev

In app.js we then load dev.js as our configuration file. You can parse these options with optparse-js.

Now you have some core modules that are depending on this config file. When you write them as such:

var Workspace = module.exports = function(config) {
    if (config) {
         // do something;
    }
}

(function () {
    this.methodOnWorkspace = function () {

    };
}).call(Workspace.prototype);

And you can call it then in app.js like:

var Workspace = require("workspace");
this.workspace = new Workspace(config);

Javascript - validation, numbers only

here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313

<input type="text" 
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>

and this will not accept entering the dot (.), so it will only accept integers

<input type="text" 
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>

this way you will not permit the user to input anything but numbers

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

how to make UITextView height dynamic according to text length?

SWIFT 4

Change the size when typing

UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
        yourTextView.translatesAutoresizingMaskIntoConstraints = true
        yourTextView.sizeToFit()
        yourTextView.isScrollEnabled = false

        let calHeight = yourTextView.frame.size.height
        yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
    }

Change the size when load

func textViewNotasChange(arg : UITextView) {
        arg.translatesAutoresizingMaskIntoConstraints = true
        arg.sizeToFit()
        arg.isScrollEnabled = false

        let calHeight = arg.frame.size.height
        arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
    }

Call the function of the second option like this:

textViewNotasChange(arg: yourTextView)

Can't specify the 'async' modifier on the 'Main' method of a console app

To avoid freezing when you call a function somewhere down the call stack that tries to re-join the current thread (which is stuck in a Wait), you need to do the following:

class Program
{
    static void Main(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        List<TvChannel> list = Task.Run((Func<Task<List<TvChannel>>>)bs.GetList).Result;
    }
}

(the cast is only required to resolve ambiguity)

ERROR 1064 (42000): You have an error in your SQL syntax;

Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

Datatables - Search Box outside datatable

As per @lvkz comment :

if you are using datatable with uppercase d .DataTable() ( this will return a Datatable API object ) use this :

 oTable.search($(this).val()).draw() ;

which is @netbrain answer.

if you are using datatable with lowercase d .dataTable() ( this will return a jquery object ) use this :

 oTable.fnFilter($(this).val());

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

How do I see which version of Swift I'm using?

To see the default version of swift installed on your machine then from the command line, type the following :

swift --version

Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2)

Target: x86_64-apple-darwin17.6.0

This is most likely the version that is included in the app store version of Xcode that you have installed (unless you have changed it).

If you want to determine the actual version of Swift being used by a particular version of Xcode (a beta, for instance) then from the command line, invoke the swift binary within the Xcode bundle and pass it the parameter --version

/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift --version

Apple Swift version 4.2 (swiftlang-1000.0.16.7 clang-1000.10.25.3)

Target: x86_64-apple-darwin17.6.0

How can you get the Manifest Version number from the App's (Layout) XML variables?

I believe that was already answered here.

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

OR

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

How I can check if an object is null in ruby on rails 2?

Now with Ruby 2.3 you can use &. operator ('lonely operator') to check for nil at the same time as accessing a value.

@person&.spouse&.name

https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#Other_operators


Use #try instead so you don't have to keep checking for nil.

http://api.rubyonrails.org/classes/Object.html#method-i-try

@person.try(:spouse).try(:name)

instead of

@person.spouse.name if @person && @person.spouse

Why is datetime.strptime not working in this simple example?

You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

CodeIgniter : Unable to load the requested file:

try $this->load->view('home/home_view',$data);

instead of this:

$this->load->view(‘home\home_view’,$data);

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

Moving average or running mean

This question is now even older than when NeXuS wrote about it last month, BUT I like how his code deals with edge cases. However, because it is a "simple moving average," its results lag behind the data they apply to. I thought that dealing with edge cases in a more satisfying way than NumPy's modes valid, same, and full could be achieved by applying a similar approach to a convolution() based method.

My contribution uses a central running average to align its results with their data. When there are too few points available for the full-sized window to be used, running averages are computed from successively smaller windows at the edges of the array. [Actually, from successively larger windows, but that's an implementation detail.]

import numpy as np

def running_mean(l, N):
    # Also works for the(strictly invalid) cases when N is even.
    if (N//2)*2 == N:
        N = N - 1
    front = np.zeros(N//2)
    back = np.zeros(N//2)

    for i in range(1, (N//2)*2, 2):
        front[i//2] = np.convolve(l[:i], np.ones((i,))/i, mode = 'valid')
    for i in range(1, (N//2)*2, 2):
        back[i//2] = np.convolve(l[-i:], np.ones((i,))/i, mode = 'valid')
    return np.concatenate([front, np.convolve(l, np.ones((N,))/N, mode = 'valid'), back[::-1]])

It's relatively slow because it uses convolve(), and could likely be spruced up quite a lot by a true Pythonista, however, I believe that the idea stands.

How to sort an array of objects with jquery or javascript

the sort method contains an optional argument to pass a custom compare function.

Assuming you wanted an array of arrays:

var arr = [[3, "Mike", 20],[5, "Alex", 15]];

function compareName(a, b)
{

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
arr.sort(compareName);

Otherwise if you wanted an array of objects, you could do:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In Apache Derby DB, refrain from using table names as "user" or so because they are reserved keywords on Apache Derby but will work fine on MySql.

In the Query, you must specify the name of the Entity class that you want to fetch the data from in the FROM clause of the Query.

List<User> users=session.createQuery("from User").list();

Here, User is the name of my Java Entity class(Consider the casing of the name as in Java it matters.)

How to use cURL to send Cookies?

If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..