Programs & Examples On #Html5 audio

The audio element is used to embed sound content in an HTML or XHTML document. The audio element was added as part of HTML5.

How to make audio autoplay on chrome

Use iframe instead:

<iframe id="stream" src="YOUTSOURCEAUDIOORVIDEOHERE" frameborder="0"></iframe>

change <audio> src with javascript

Try this:

Replace:

audio.load();

with:

audio.play();

Custom CSS for <audio> tag?

There is not currently any way to style HTML5 <audio> players using CSS. Instead, you can leave off the control attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.

How to play a notification sound on websites?

We can just use Audio and an object together like:

var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();

and even adding addEventListener for play and ended

html 5 audio tag width

You can use html and be a boss with simple things :

<embed src="music.mp3" width="3000" height="200" controls>

HTML5 record audio to file

Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer

This streams PCM data but you could modify the code to stream mp3 or Speex

HTML5 Audio stop function

This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").

<div id="plHolder">
     <audio controls id="player">
     ...
     </audio>
<div>

Then this javascript should work:

function stopAudio() {
    var savePlayer = $('#plHolder').html(); // Save player code
    $('#player').remove(); // Remove player from DOM
    $('#FlHolder').html(savePlayer); // Restore it
}

Sound effects in JavaScript / HTML5

HTML5 Audio objects

You don't need to bother with <audio> elements. HTML 5 lets you access Audio objects directly:

var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();

There's no support for mixing in current version of the spec.

To play same sound multiple times, create multiple instances of the Audio object. You could also set snd.currentTime=0 on the object after it finishes playing.


Since the JS constructor doesn't support fallback <source> elements, you should use

(new Audio()).canPlayType("audio/ogg; codecs=vorbis")

to test whether the browser supports Ogg Vorbis.


If you're writing a game or a music app (more than just a player), you'll want to use more advanced Web Audio API, which is now supported by most browsers.

HTML5 Audio Looping

While loop is specified, it is not implemented in any browser I am aware of Firefox [thanks Anurag for pointing this out]. Here is an alternate way of looping that should work in HTML5 capable browsers:

var myAudio = new Audio('someSound.ogg'); 
myAudio.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
myAudio.play();

How do I download NLTK data?

I think you must have named the file as nltk.py (or the folder consists of a file with that name) so change it to any other name and try executing it....

What Are Some Good .NET Profilers?

I would add that dotTrace's ability to diff memory and performance trace sessions is absolutely invaluable (ANTS may also have a memory diff feature, but I didn't see a performance diff).

Being able to run a profiling session before and after a bug fix or enhancement, then compare the results is incredibly valuable, especially with a mammoth legacy .NET application (as in my case) where performance was never a priority and where finding bottlenecks could be VERY tedious. Doing a before-and-after diff allows you to see the change in call count for each method and the change in duration for each method.

This is helpful not only during code changes, but also if you have an application that uses a different database, say, for each client/customer. If one customer complains of slowness, you can run a profiling session using their database and compare the results with a "fast" database to determine which operations are contributing to the slowness. Of course there are many database-side performance tools, but sometimes I really helps to see the performance metrics from the application side (since that's closer to what the user's actually seeing).

Bottom line: dotTrace works great, and the diff is invaluable.

Allow only numeric value in textbox using Javascript

// Solution to enter only numeric value in text box

$('#num_of_emp').keyup(function () { 
    this.value = this.value.replace(/[^0-9.]/g,'');
});

for an input box such as :

<input type='text' name='number_of_employee' id='num_of_emp' />

How to get length of a list of lists in python

"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/file.ext");

AngularJS passing data to $http.get request

Starting from AngularJS v1.4.8, you can use get(url, config) as follows:

var data = {
 user_id:user.id
};

var config = {
 params: data,
 headers : {'Accept' : 'application/json'}
};

$http.get(user.details_path, config).then(function(response) {
   // process response here..
 }, function(response) {
});

"Unable to find remote helper for 'https'" during git clone

I got the same problem today: git http broken after years of happy service. It seems caused by some Perl lib updates. Tried some sane suggestions on web, none worked. Had enough, I just removed all git stuff, got a new tarball from http://git-scm.com/, compiled and installed, and all things are back to normal. Give it try, or you can go dig deep into your logs...

How to get current time and date in Android

final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText(""+mDay+"-"+mMonth+"-"+mYear);

How to select the first row of each group?

We can use the rank() window function (where you would choose the rank = 1) rank just adds a number for every row of a group (in this case it would be the hour)

here's an example. ( from https://github.com/jaceklaskowski/mastering-apache-spark-book/blob/master/spark-sql-functions.adoc#rank )

val dataset = spark.range(9).withColumn("bucket", 'id % 3)

import org.apache.spark.sql.expressions.Window
val byBucket = Window.partitionBy('bucket).orderBy('id)

scala> dataset.withColumn("rank", rank over byBucket).show
+---+------+----+
| id|bucket|rank|
+---+------+----+
|  0|     0|   1|
|  3|     0|   2|
|  6|     0|   3|
|  1|     1|   1|
|  4|     1|   2|
|  7|     1|   3|
|  2|     2|   1|
|  5|     2|   2|
|  8|     2|   3|
+---+------+----+

How do I unlock a SQLite database?

you can try this: .timeout 100 to set timeout . I don't know what happen in command line but in C# .Net when I do this: "UPDATE table-name SET column-name = value;" I get Database is locked but this "UPDATE table-name SET column-name = value" it goes fine.

It looks like when you add ;, sqlite'll look for further command.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

How to completely DISABLE any MOUSE CLICK

The easiest way to freeze the UI would be to make the AJAX call synchronous.

Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

jQuery: Performing synchronous AJAX requests

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success: function (result) {
            /* if result is a JSon object */
            if (result.valid)
                return true;
            else
                return false;
        }
    });
}

INSERT INTO vs SELECT INTO

Select into for large datasets may be good only for a single user using one single connection to the database doing a bulk operation task. I do not recommend to use

SELECT * INTO table

as this creates one big transaction and creates schema lock to create the object, preventing other users to create object or access system objects until the SELECT INTO operation completes.

As proof of concept open 2 sessions, in first session try to use

select into temp table from a huge table 

and in the second section try to

create a temp table 

and check the locks, blocking and the duration of second session to create a temp table object. My recommendation it is always a good practice to create and Insert statement and if needed for minimal logging use trace flag 610.

How do I convert from int to Long in Java?

use

new Long(your_integer);

or

Long.valueOf(your_integer);

How to insert a row in an HTML table body in JavaScript

Add Column, Add Row, Delete Column, Delete Row. Simplest way

_x000D_
_x000D_
    function addColumn(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = row[i].innerHTML + '<td></td>';
      }
    }
    function deleterow(tblId)
    {
        
      var table = document.getElementById(tblId);
      var row = table.getElementsByTagName('tr');
            if(row.length!='1'){
                row[row.length - 1].outerHTML='';
            }
    }
    function deleteColumn(tblId)
    {
        var allRows = document.getElementById(tblId).rows;
        for (var i=0; i<allRows.length; i++) {
            if (allRows[i].cells.length > 1) {
                allRows[i].deleteCell(-1);
            }
        }
    }
    function myFunction(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].outerHTML;
      table.innerHTML = table.innerHTML + row;
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].getElementsByTagName('td');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = '';
      }
    }
_x000D_
    table, td {
      border: 1px solid black;
      border-collapse:collapse;
    }
    td {
      cursor:text;
      padding:10px;
    }
    td:empty:after{
      content:"Type here...";
      color:#cccccc;
    }
_x000D_
   <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form>
    <p>
    <input type="button" value="+Column" onclick="addColumn('tblSample')">
    <input type="button" value="-Column" onclick="deleteColumn('tblSample')">
    <input type="button" value="+Row" onclick="myFunction('tblSample')">
    <input type="button" value="-Row" onclick="deleterow('tblSample')">
    </p>
    <table id="tblSample" contenteditable><tr><td></td></tr></table>
    </form>

    </body>
    </html>
_x000D_
_x000D_
_x000D_

Posting JSON Data to ASP.NET MVC

You can try these. 1. stringify your JSON Object before calling the server action via ajax 2. deserialize the string in the action then use the data as a dictionary.

Javascript sample below (sending the JSON Object

$.ajax(
   {
       type: 'POST',
       url: 'TheAction',
       data: { 'data': JSON.stringify(theJSONObject) 
   }
})

Action (C#) sample below

[HttpPost]
public JsonResult TheAction(string data) {

       string _jsonObject = data.Replace(@"\", string.Empty);
       var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();           
        Dictionary<string, string> jsonObject = serializer.Deserialize<Dictionary<string, string>>(_jsonObject);


        return Json(new object{status = true});

    }

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL. Here an example: (I used a procedure instead of a function, like @Thilo did)

create or replace procedure myprocedure(retval in out sys_refcursor) is
begin
  open retval for
    select TABLE_NAME from user_tables;
end myprocedure;

 declare 
   myrefcur sys_refcursor;
   tablename user_tables.TABLE_NAME%type;
 begin
   myprocedure(myrefcur);
   loop
     fetch myrefcur into tablename;
     exit when myrefcur%notfound;
     dbms_output.put_line(tablename);
   end loop;
   close myrefcur;
 end;

How to implement a secure REST API with node.js

I would like to contribute this code as an structural solution for the question posed, according (I hope so) to the accepted answer. (You can very easily customize it).

// ------------------------------------------------------
// server.js 

// .......................................................
// requires
var fs = require('fs');
var express = require('express'); 
var myBusinessLogic = require('../businessLogic/businessLogic.js');

// .......................................................
// security options

/*
1. Generate a self-signed certificate-key pair
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem

2. Import them to a keystore (some programs use a keystore)
keytool -importcert -file certificate.pem -keystore my.keystore
*/

var securityOptions = {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('certificate.pem'),
    requestCert: true
};

// .......................................................
// create the secure server (HTTPS)

var app = express();
var secureServer = require('https').createServer(securityOptions, app);

// ------------------------------------------------------
// helper functions for auth

// .............................................
// true if req == GET /login 

function isGETLogin (req) {
    if (req.path != "/login") { return false; }
    if ( req.method != "GET" ) { return false; }
    return true;
} // ()

// .............................................
// your auth policy  here:
// true if req does have permissions
// (you may check here permissions and roles 
//  allowed to access the REST action depending
//  on the URI being accessed)

function reqHasPermission (req) {
    // decode req.accessToken, extract 
    // supposed fields there: userId:roleId:expiryTime
    // and check them

    // for the moment we do a very rigorous check
    if (req.headers.accessToken != "you-are-welcome") {
        return false;
    }
    return true;
} // ()

// ------------------------------------------------------
// install a function to transparently perform the auth check
// of incoming request, BEFORE they are actually invoked

app.use (function(req, res, next) {
    if (! isGETLogin (req) ) {
        if (! reqHasPermission (req) ){
            res.writeHead(401);  // unauthorized
            res.end();
            return; // don't call next()
        }
    } else {
        console.log (" * is a login request ");
    }
    next(); // continue processing the request
});

// ------------------------------------------------------
// copy everything in the req body to req.body

app.use (function(req, res, next) {
    var data='';
    req.setEncoding('utf8');
    req.on('data', function(chunk) { 
       data += chunk;
    });
    req.on('end', function() {
        req.body = data;
        next(); 
    });
});

// ------------------------------------------------------
// REST requests
// ------------------------------------------------------

// .......................................................
// authenticating method
// GET /login?user=xxx&password=yyy

app.get('/login', function(req, res){
    var user = req.query.user;
    var password = req.query.password;

    // rigorous auth check of user-passwrod
    if (user != "foobar" || password != "1234") {
        res.writeHead(403);  // forbidden
    } else {
        // OK: create an access token with fields user, role and expiry time, hash it
        // and put it on a response header field
        res.setHeader ('accessToken', "you-are-welcome");
        res.writeHead(200); 
    }
    res.end();
});

// .......................................................
// "regular" methods (just an example)
// newBook()
// PUT /book

app.put('/book', function (req,res){
    var bookData = JSON.parse (req.body);

    myBusinessLogic.newBook(bookData, function (err) {
        if (err) {
            res.writeHead(409);
            res.end();
            return;
        }
        // no error:
        res.writeHead(200);
        res.end();
    });
});

// .......................................................
// "main()"

secureServer.listen (8081);

This server can be tested with curl:

echo "----   first: do login "
curl -v "https://localhost:8081/login?user=foobar&password=1234" --cacert certificate.pem

# now, in a real case, you should copy the accessToken received before, in the following request

echo "----  new book"
curl -X POST  -d '{"id": "12341324", "author": "Herman Melville", "title": "Moby-Dick"}' "https://localhost:8081/book" --cacert certificate.pem --header "accessToken: you-are-welcome" 

Set icon for Android application

In AndroidManifest change these :

android:icon="@drawable/icon_name"
android:roundIcon="@drawable/icon_name"

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

Sending email from Azure

I know this is an old post but I've just signed up for Azure and I get 25,000 emails a month for free via SendGrid. These instructions are excellent, I was up and running in minutes:

How to Send Email Using SendGrid with Azure

Azure customers can unlock 25,000 free emails each month.

Batch Renaming of Files in a Directory

I have this to simply rename all files in subfolders of folder

import os

def replace(fpath, old_str, new_str):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(old_str.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(old_str,new_str)))

I am replacing all occurences of old_str with any case by new_str.

Change a Rails application to production

By default server runs on development environment: $ rails s

If you're running on production environment: $ rails s -e production or $ RAILS_ENV=production rails s

How to secure the ASP.NET_SessionId cookie?

Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL

<authentication mode="Forms">
   <forms ...  requireSSL="true" />
</authentication>

Other wise authentication cookie will not be https

See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx

Extracting specific selected columns to new DataFrame as a copy

As far as I can tell, you don't necessarily need to specify the axis when using the filter function.

new = old.filter(['A','B','D'])

returns the same dataframe as

new = old.filter(['A','B','D'], axis=1)

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

Set date input field's max date to today

I am using Laravel 7.x with blade templating and I use:

<input ... max="{{ now()->toDateString('Y-m-d') }}">

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

Android Studio gradle takes too long to build

1) My build time severely increased after i added some new library dependencies to my gradle file, what turned out that i need to use multidex after that. And when i set up multidex correctly then my build times went up to 2-3 minutes. So if you want faster build times, avoid using multidex, and as far as possible, reduce the number of library dependencies.

2) Also you can try enabling "offline work" in android studio, like suggested here, that makes sense. This will not refetch libraries every time you make a build. Perhaps slow connection or proxy/vpn usage with "offline work" disabled may lead to slow build times.

3) google services - as mentioned here, dont use the whole bundle, use only the needed parts of it.

Proper way of checking if row exists in table in PL/SQL block

If you are using an explicit cursor, It should be as follows.

DECLARE
   CURSOR get_id IS 
    SELECT id 
      FROM person 
      WHERE id = 10;

  id_value_ person.id%ROWTYPE;
BEGIN 
   OPEN get_id;
   FETCH get_id INTO id_value_;

   IF (get_id%FOUND) THEN
     DBMS_OUTPUT.PUT_LINE('Record Found.');
   ELSE
     DBMS_OUTPUT.PUT_LINE('Record Not Found.');
   END IF;
   CLOSE get_id;

EXCEPTION
  WHEN no_data_found THEN
  --do things when record doesn't exist
END;

Download file from web in Python 3

I hope I understood the question right, which is: how to download a file from a server when the URL is stored in a string type?

I download files and save it locally using the below code:

import requests

url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
    file.write(chunk)
file.close()

Sending email with PHP from an SMTP server

In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.

Here are the steps:

Install msmtp

sudo apt-get install msmtp-mta ca-certificates

Create a new configuration file:

sudo nano /etc/msmtprc

...with the following configuration information:

# Set defaults.    
defaults

# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL

You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.

Tell PHP to use it

sudo nano /etc/php5/apache2/php.ini

Add this single line:

sendmail_path = /usr/bin/msmtp -t

Complete documention can be found here:

https://marlam.de/msmtp/

RegEx pattern any two letters followed by six numbers

Everything you need here can be found in this quickstart guide. A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d or [A-Za-z]{2}\d{6}.

If you want to accept only capital letters then replace [A-Za-z] with [A-Z].

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):

  1. In SQL Server Management Studio, open Object Explorer and expand the folder of the server instance in which to create the new login.
  2. Right-click the Security folder, point to New, and then click Login.
  3. On the General page, enter the name of a Windows user in the Login name box.
  4. Select Windows Authentication.
  5. Click OK.

For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.

Also you need to change the User mapping to allow access to the Database which you want to access.

nginx 502 bad gateway

If you're on Ubuntu, and all of the above has failed you, AppArmor is most likely to blame.

Here is a good guide how to fix it: https://www.digitalocean.com/community/tutorials/how-to-create-an-apparmor-profile-for-nginx-on-ubuntu-14-04

Long story short:

vi /etc/apparmor.d/nginx

Or

sudo aa-complain nginx
sudo service nginx restart

See everything working nicely... then

sudo aa-logprof

I still had problems with Nginx not being able to read error.log, even though it had all the permissions possible, including in Apparomor. I'm guessing it's got something to do with the order of the entries, or some interaction with Passenger or PHP-Fpm... I've run out of time to troubleshoot this and have gone back to Apache for now. (Apache performs much better too FYI.)

AppArmor just lets Nginx do whatever it wants if you just remove the profile:

 rm /etc/apparmor.d/nginx
 service apparmor reload

Shockingly, but hardly surprising, a lot of posts on fixing Nginx errors resorts to completely disabling SELinux or removing AppArmor. That's a bad idea because you lose protection from a whole lot of software. Just removing the Nginx profile is a better way to troubleshoot your config files. Once you know that the problem isn't in your Nginx config files, you can take the time to create a proper AppArmor profile.

Without an AppArmor profile, especially if you run something like Passenger too, I give your server about a month to get backdoored.

Present and dismiss modal view controller

The easiest way i tired in xcode 4.52 was to create an additional view and connect them by using segue modal(control drag the button from view one to the second view, chose Modal). Then drag in a button to second view or the modal view that you created. Control and drag this button to the header file and use action connection. This will create an IBaction in your controller.m file. Find your button action type in the code.

[self dismissViewControllerAnimated:YES completion:nil];

How to convert an int array to String with toString method in Java

What you want is the Arrays.toString(int[]) method:

import java.util.Arrays;

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

..      

System.out.println(Arrays.toString(array));

There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:

public static String toString(int[] a)

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.

Android RecyclerView addition & removal of items

  String str = arrayList.get(position);
  arrayList.remove(str);
  MyAdapter.this.notifyDataSetChanged();

how to add key value pair in the JSON object already declared

Could you do the following:

obj = {
    "1":"aa",
    "2":"bb"
};


var newNum = "3";
var newVal = "cc";


obj[newNum] = newVal;



alert(obj["3"]); // this would alert 'cc'

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Embedding a media player in a website using HTML

<html>

<head>
  <H1>
      Automatically play music files on your website when a page loads
    </H1>
</head>

<body>
  <embed src="YourMusic.mp3" autostart="true" loop="true" width="2" height="0">
  </embed>
</body>

</html>

Sorting JSON by values

Demo: https://jsfiddle.net/kvxazhso/

Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).

Given data such :

var people = [ 
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 3 },
{ 'myKey': 'D', 'status': 2 },
{ 'myKey': 'E', 'status': 7 },
...
];

Sorting by ascending or reverse order:

function sortJSON(arr, key, way) {
    return arr.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
        if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
    });
}

people2 = sortJSON(people,'status', '321'); // 123 or 321
alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));

Can I change the scroll speed using css or jQuery?

I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

What killed my process and why?

Let me first explain when and why OOMKiller get invoked?

Say you have 512 RAM + 1GB Swap memory. So in theory, your CPU has access to total of 1.5GB of virtual memory.

Now, for some time everything is running fine within 1.5GB of total memory. But all of sudden (or gradually) your system has started consuming more and more memory and it reached at a point around 95% of total memory used.

Now say any process has requested large chunck of memory from the kernel. Kernel check for the available memory and find that there is no way it can allocate your process more memory. So it will try to free some memory calling/invoking OOMKiller (http://linux-mm.org/OOM).

OOMKiller has its own algorithm to score the rank for every process. Typically which process uses more memory becomes the victim to be killed.

Where can I find logs of OOMKiller?

Typically in /var/log directory. Either /var/log/kern.log or /var/log/dmesg

Hope this will help you.

Some typical solutions:

  1. Increase memory (not swap)
  2. Find the memory leaks in your program and fix them
  3. Restrict memory any process can consume (for example JVM memory can be restricted using JAVA_OPTS)
  4. See the logs and google :)

JavaScript Number Split into individual digits

You can work on strings instead of numbers to achieve this. You can do it like this

(111 + '').split('')

This will return an array of strings ['1','1','1'] on which you can iterate upon and call parseInt method.

parseInt('1') === 1

If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this

(111 + '').split('').reduce(function(previousValue, currentValue){  
  return parseInt(previousValue,10) + parseInt(currentValue,10);  
})

Why do I get an error instantiating an interface?

IUser is the interface, you can't instantiate the interface.

You need to instantiate the concrete class that implements the interface.

IUser user = new User();

or

User user = new User();

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

What causes a Python segmentation fault?

Google search found me this article, and I did not see the following "personal solution" discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but "re-installing" pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

SonarQube Exclude a directory

If we want to skip the entire folder following can be used:

sonar.exclusions=folderName/**/*

And if we have only one particular file just give the complete path.

All the folder which needs to be exclude and be appended here.

HTTP response header content disposition for attachments

Try the Content-Disposition header

Content-Disposition: attachment; filename=<file name.ext> 

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

Returning a value from thread?

It depends on how do you want to create the thread and available .NET version:

.NET 2.0+:

A) You can create the Thread object directly. In this case you could use "closure" - declare variable and capture it using lambda-expression:

object result = null;
Thread thread = new System.Threading.Thread(() => { 
    //Some work...
    result = 42; });
thread.Start();
thread.Join();
Console.WriteLine(result);

B) You can use delegates and IAsyncResult and return value from EndInvoke() method:

delegate object MyFunc();
...
MyFunc x = new MyFunc(() => { 
    //Some work...
    return 42; });
IAsyncResult asyncResult = x.BeginInvoke(null, null);
object result = x.EndInvoke(asyncResult);

C) You can use BackgroundWorker class. In this case you could use captured variable (like with Thread object) or handle RunWorkerCompleted event:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) => {
    //Some work...
    e.Result = 42;
};
worker.RunWorkerCompleted += (s, e) => {
    //e.Result "returned" from thread
    Console.WriteLine(e.Result);
};
worker.RunWorkerAsync();

.NET 4.0+:

Starting with .NET 4.0 you could use Task Parallel Library and Task class to start your threads. Generic class Task<TResult> allows you to get return value from Result property:

//Main thread will be blocked until task thread finishes
//(because of obtaining the value of the Result property)
int result = Task.Factory.StartNew(() => {
    //Some work...
    return 42;}).Result;

.NET 4.5+:

Starting with .NET 4.5 you could also use async/await keywords to return value from task directly instead of obtaining Result property:

int result = await Task.Run(() => {
    //Some work...
    return 42; });

Note: method, which contains the code above shoud be marked with asynckeyword.

For many reasons using of Task Parallel Library is preferable way of working with threads.

Changing image size in Markdown

When using Flask (I am using it with flat pages)... I found that enabling explicitly (was not by default for some reason) 'attr_list' in extensions within the call to markdown does the trick - and then one can use the attributes (very useful also to access CSS - class="my class" for example...).

FLATPAGES_HTML_RENDERER = prerender_jinja

and the function:

def prerender_jinja(text):
    prerendered_body = render_template_string(Markup(text))
    pygmented_body   = markdown.markdown(prerendered_body, extensions=['codehilite', 'fenced_code', 'tables', 'attr_list'])
    return pygmented_body

And then in Markdown:

![image](https://octodex.github.com/images/yaktocat.png "This is a tooltip"){: width=200px}

Print series of prime numbers in python

we can make a list of prime numbers using sympy library

import sympy
lower=int(input("lower value:"))          #let it be 30
upper=int(input("upper value:"))          #let it be 60
l=list(sympy.primerange(lower,upper+1))   #[31,37,41,43,47,53,59]
print(l)

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

Operations with a Python list operate on the list. list1 and list2 will check if list1 is empty, and return list1 if it is, and list2 if it isn't. list1 + list2 will append list2 to list1, so you get a new list with len(list1) + len(list2) elements.

Operators that only make sense when applied element-wise, such as &, raise a TypeError, as element-wise operations aren't supported without looping through the elements.

Numpy arrays support element-wise operations. array1 & array2 will calculate the bitwise or for each corresponding element in array1 and array2. array1 + array2 will calculate the sum for each corresponding element in array1 and array2.

This does not work for and and or.

array1 and array2 is essentially a short-hand for the following code:

if bool(array1):
    return array2
else:
    return array1

For this you need a good definition of bool(array1). For global operations like used on Python lists, the definition is that bool(list) == True if list is not empty, and False if it is empty. For numpy's element-wise operations, there is some disambiguity whether to check if any element evaluates to True, or all elements evaluate to True. Because both are arguably correct, numpy doesn't guess and raises a ValueError when bool() is (indirectly) called on an array.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):

  1. Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".

  2. Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"

Not sure why both were needed. I used this to remove a dependency on glut32.dll.

Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

What is a non-capturing group in regular expressions?

Well I am a JavaScript developer and will try to explain its significance pertaining to JavaScript.

Consider a scenario where you want to match cat is animal when you would like match cat and animal and both should have a is in between them.

 // this will ignore "is" as that's is what we want
"cat is animal".match(/(cat)(?: is )(animal)/) ;
result ["cat is animal", "cat", "animal"]

 // using lookahead pattern it will match only "cat" we can
 // use lookahead but the problem is we can not give anything
 // at the back of lookahead pattern
"cat is animal".match(/cat(?= is animal)/) ;
result ["cat"]

 //so I gave another grouping parenthesis for animal
 // in lookahead pattern to match animal as well
"cat is animal".match(/(cat)(?= is (animal))/) ;
result ["cat", "cat", "animal"]

 // we got extra cat in above example so removing another grouping
"cat is animal".match(/cat(?= is (animal))/) ;
result ["cat", "animal"]

Editing specific line in text file in Python

Suppose I have a file named file_name as following:

this is python
it is file handling
this is editing of line

We have to replace line 2 with "modification is done":

f=open("file_name","r+")
a=f.readlines()
for line in f:
   if line.startswith("rai"):
      p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
   o.write(i)
o.close()
#now the modification is done in the file

How do I turn a C# object into a JSON string in .NET?

It is as easy as this (it works for dynamic objects as well (type object)):

string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

"Could not find a valid gem in any repository" (rubygame and others)

Make sure you type the command from the "App" Directory

Server Discovery And Monitoring engine is deprecated

This solved my problem.

 const url = 'mongodb://localhost:27017';

 const client = new MongoClient(url, {useUnifiedTopology: true});

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Random row selection in Pandas dataframe

Something like this?

import random

def some(x, n):
    return x.ix[random.sample(x.index, n)]

Note: As of Pandas v0.20.0, ix has been deprecated in favour of loc for label based indexing.

Better way to find last used row

I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.

Example of use:

lastRow=FindRange("Sheet1","A1:A1000")

would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")

Public Function FindRange(inSheet As String, inRange As String) As Long
    Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function

What is a PDB file?

A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.

You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug switch.

Spark - repartition() vs coalesce()

Repartition: Shuffle the data into a NEW number of partitions.

Eg. Initial data frame is partitioned in 200 partitions.

df.repartition(500): Data will be shuffled from 200 partitions to new 500 partitions.

Coalesce: Shuffle the data into existing number of partitions.

df.coalesce(5): Data will be shuffled from remaining 195 partitions to 5 existing partitions.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

Guys in my case none of the solutions above worked.

I had to delete the files within the Project workspace:

  • .project
  • .classpath

And the folder:

  • .settings

Then I copied the ones from a similar project that was working before. This managed to fix my broken project.

Of course do not use this method before trying the previous alternatives!.

Android simple alert dialog

You would simply need to do this in your onClick:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

I don't know from where you saw that you need DialogFragment for simply showing an alert.

Hope this helps.

Git push failed, "Non-fast forward updates were rejected"

Using the --rebase option worked for me.

  • git pull <remote> <branch> --rebase

Then push to the repo.

  • git push <remote> <branch>

E.g.

git pull origin master --rebase

git push origin master

How to change a DIV padding without affecting the width/height ?

Solution is to wrap your padded div, with fixed width outer div

HTML

<div class="outer">
    <div class="inner">

        <!-- your content -->

    </div><!-- end .inner -->
</div><!-- end .outer -->

CSS

.outer, .inner {
    display: block;
}

.outer {
    /* specify fixed width */
    width: 300px;
    padding: 0;
}

.inner {
    /* specify padding, can be changed while remaining fixed width of .outer */
    padding: 5px;
}

jQuery Validate Plugin - Trigger validation of single field

$("#FormId").validate().element('#FieldId');

How to display the current time and date in C#

In WPF you'll need to use the Content property instead:

label1.Content = DateTime.Now.ToString();

Set default host and port for ng serve in config file

If you are planning to run the angular project in custom host/IP and Port there is no need of making changes in config file

The following command worked for me

ng serve --host aaa.bbb.ccc.ddd --port xxxx

Where,

aaa.bbb.ccc.ddd --> IP you want to run the project
xxx --> Port you want to run the project

Example

ng serve --host 192.168.322.144 --port 6300

Result for me was

enter image description here

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

showing that a date is greater than current date

SELECT * 
FROM MyTable 
WHERE CreatedDate >= getdate() 
AND CreatedDate <= dateadd(day, 90, getdate())

http://msdn.microsoft.com/en-us/library/ms186819.aspx

Difference between staticmethod and classmethod

A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).

For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

Online index rebuilds are less intrusive when it comes to locking tables. Offline rebuilds cause heavy locking of tables which can cause significant blocking issues for things that are trying to access the database while the rebuild takes place.

"Table locks are applied for the duration of the index operation [during an offline rebuild]. An offline index operation that creates, rebuilds, or drops a clustered, spatial, or XML index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements."

http://msdn.microsoft.com/en-us/library/ms188388(v=sql.110).aspx

Additionally online index rebuilds are a enterprise (or developer) version only feature.

JavaScript - get the first day of the week from current date

Not sure how it compares for performance, but this works.

var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 )                // Only manipulate the date if it isn't Mon.
    today.setHours(-24 * (day - 1));   // Set the hours to day number minus 1
                                         //   multiplied by negative 24
alert(today); // will be Monday

Or as a function:

# modifies _date_
function setToMonday( date ) {
    var day = date.getDay() || 7;  
    if( day !== 1 ) 
        date.setHours(-24 * (day - 1)); 
    return date;
}

setToMonday(new Date());

How to save an image to localStorage and display it on the next page?

document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];
  const reader = new FileReader();
  reader.onloadend = () => {
    // convert file to base64 String
    const base64String = reader.result.replace('data:', '').replace(/^.+,/, '');
    // store file
    localStorage.setItem('wallpaper', base64String);
    // display image
    document.body.style.background = `url(data:image/png;base64,${base64String})`;
  };
  reader.readAsDataURL(file);
});

Example CodePen

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

MySQL - UPDATE query with LIMIT

When dealing with null, = does not match the null values. You can use IS NULL or IS NOT NULL

UPDATE `smartmeter_usage`.`users_reporting` 
SET panel_id = 3 WHERE panel_id IS NULL

LIMIT can be used with UPDATE but with the row count only

Spring Security with roles and permissions

I'm the author of the article in question.

No doubt there are multiple ways to do it, but the way I typically do it is to implement a custom UserDetails that knows about roles and permissions. Role and Permission are just custom classes that you write. (Nothing fancy--Role has a name and a set of Permission instances, and Permission has a name.) Then the getAuthorities() returns GrantedAuthority objects that look like this:

PERM_CREATE_POST, PERM_UPDATE_POST, PERM_READ_POST

instead of returning things like

ROLE_USER, ROLE_MODERATOR

The roles are still available if your UserDetails implementation has a getRoles() method. (I recommend having one.)

Ideally you assign roles to the user and the associated permissions are filled in automatically. This would involve having a custom UserDetailsService that knows how to perform that mapping, and all it has to do is source the mapping from the database. (See the article for the schema.)

Then you can define your authorization rules in terms of permissions instead of roles.

Hope that helps.

Set Focus After Last Character in Text Box

Code for any Browser:

function focusCampo(id){
    var inputField = document.getElementById(id);
    if (inputField != null && inputField.value.length != 0){
        if (inputField.createTextRange){
            var FieldRange = inputField.createTextRange();
            FieldRange.moveStart('character',inputField.value.length);
            FieldRange.collapse();
            FieldRange.select();
        }else if (inputField.selectionStart || inputField.selectionStart == '0') {
            var elemLen = inputField.value.length;
            inputField.selectionStart = elemLen;
            inputField.selectionEnd = elemLen;
            inputField.focus();
        }
    }else{
        inputField.focus();
    }
}

Remove an onclick listener

    /**
 * Remove an onclick listener
 *
 * @param view
 * @author [email protected]
 * @website https://github.com/androidmalin
 * @data 2016-05-16
 */
public static void unBingListener(View view) {
    if (view != null) {
        try {
            if (view.hasOnClickListeners()) {
                view.setOnClickListener(null);

            }

            if (view.getOnFocusChangeListener() != null) {
                view.setOnFocusChangeListener(null);

            }

            if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                ViewGroup viewGroup = (ViewGroup) view;
                int viewGroupChildCount = viewGroup.getChildCount();
                for (int i = 0; i < viewGroupChildCount; i++) {
                    unBingListener(viewGroup.getChildAt(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

How to Identify Microsoft Edge browser via CSS?

For Internet Explorer 

@media all and (-ms-high-contrast: none) {
        .banner-wrapper{
            background: rgba(0, 0, 0, 0.16)
         }
}

For Edge
@supports (-ms-ime-align:auto) {
    .banner-wrapper{
            background: rgba(0, 0, 0, 0.16);
         }
}

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

Best way to find the months between two dates

This post nails it! Use dateutil.relativedelta.

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
r.months

How to reset the state of a Redux store?

With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).

const appReducer = combineReducers({
  tabs,
  user
})

const initialState = appReducer({}, {})

const rootReducer = (state, action) => {
  if (action.type === 'LOG_OUT') {
    state = initialState
  }

  return appReducer(state, action)
}

How do I crop an image in Java?

There are two potentially major problem with the leading answer to this question. First, as per the docs:

public BufferedImage getSubimage(int x, int y, int w, int h)

Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.

Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.

Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.

Try this:

BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(img, 0, 0, null);
return copyOfImage; //or use it however you want

This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)

How to change the server port from 3000?

Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **

Got the tip from Here

enter image description here enter image description here

TypeError: expected a character buffer object - while trying to save integer to textfile

from __future__ import with_statement
with open('file.txt','r+') as f:
    counter = str(int(f.read().strip())+1)
    f.seek(0)
    f.write(counter)

Clear data in MySQL table with PHP?

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

The remote server returned an error: (407) Proxy Authentication Required

Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.

If you're using httpClient then consider this.

HttpClientHandler handler = new HttpClientHandler();

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;

var client = new HttpClient(handler);
// your next steps...

And if you're using HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;

Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b

Making PHP var_dump() values display one line per value

For devs needing something that works in the view source and the CLI, especially useful when debugging unit tests.

echo vd([['foo'=>1, 'bar'=>2]]);

function vd($in) {
  ob_start(); 
  var_dump($in);
  return "\n" . preg_replace("/=>[\r\n\s]+/", "=> ", ob_get_clean());
}

Yields:

array(1) {
  [0] => array(2) {
    'foo' => int(1)
    'bar' => int(2)
  }
}

How can I stop float left?

There's a class in bootstrap for it

class="clearfix";

Parsing JSON with Unix tools

I needed something in BASH that's short and would run without dependencies beyond vanilla Linux LSB and Mac OS for both python 2.7 & 3 and handle errors, e.g. would report json parse errors and missing property errors without spewing python exceptions:

json-extract () {
  if [[ "$1" == "" || "$1" == "-h" || "$1" == "-?" || "$1" == "--help" ]] ; then
    echo 'Extract top level property value from json document'
    echo '  Usage: json-extract <property> [ <file-path> ]'
    echo '  Example 1: json-extract status /tmp/response.json'
    echo '  Example 2: echo $JSON_STRING | json-extract-file status'
    echo '  Status codes: 0 - success, 1 - json parse error, 2 - property missing'
  else
    python -c $'import sys, json;\ntry: obj = json.load(open(sys.argv[2])); \nexcept: sys.exit(1)\ntry: print(obj[sys.argv[1]])\nexcept: sys.exit(2)' "$1" "${2:-/dev/stdin}"
  fi
}

Rails: How can I set default values in ActiveRecord?

# db/schema.rb
create_table :store_listings, force: true do |t|
  t.string :my_string, default: "original default"
end

StoreListing.new.my_string # => "original default"

# app/models/store_listing.rb
class StoreListing < ActiveRecord::Base
  attribute :my_string, :string, default: "new default"
end

StoreListing.new.my_string # => "new default"

class Product < ActiveRecord::Base
  attribute :my_default_proc, :datetime, default: -> { Time.now }
end

Product.new.my_default_proc # => 2015-05-30 11:04:48 -0600
sleep 1
Product.new.my_default_proc # => 2015-05-30 11:04:49 -0600

Converting A String To Hexadecimal In Java

Here an other solution

public static String toHexString(byte[] ba) {
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < ba.length; i++)
        str.append(String.format("%x", ba[i]));
    return str.toString();
}

public static String fromHexString(String hex) {
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
    }
    return str.toString();
}

Compiling a C++ program with gcc

By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:

gcc -x c++

More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language).

This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.

SQL multiple column ordering

You can use multiple ordering on multiple condition,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

Compiling/Executing a C# Source File in Command Prompt

CSC.exe is the CSharp compiler included in the .NET Framework and can be used to compile from the command prompt. The output can be an executable ".exe", if you use "/target:exe", or a DLL; If you use /target:library, CSC.exe is found in the .NET Framework directory,

e.g. for .NET 3.5, c:\windows\Microsoft.NET\Framework\v3.5\.

To run, first, open a command prompt, click "Start", then type cmd.exe.
You may then have to cd into the directory that holds your source files.

Run the C# compiler like this:

  c:\windows\Microsoft.NET\Framework\v3.5\bin\csc.exe 
            /t:exe /out:MyApplication.exe MyApplication.cs  ...

(all on one line)

If you have more than one source module to be compiled, you can put it on that same command line. If you have other assemblies to reference, use /r:AssemblyName.dll .

Ensure you have a static Main() method defined in one of your classes, to act as the "entry point".

To run the resulting EXE, type MyApplication, followed by <ENTER> using the command prompt.

This article on MSDN goes into more detail on the options for the command-line compiler. You can embed resources, set icons, sign assemblies - everything you could do within Visual Studio.

If you have Visual Studio installed, in the "Start menu"; under Visual Studio Tools, you can open a "Visual Studio command prompt", that will set up all required environment and path variables for command line compilation.

While it's very handy to know of this, you should combine it with knowledge of some sort of build tool such as NAnt, MSBuild, FinalBuilder etc. These tools provide a complete build environment, not just the basic compiler.

On a Mac

On a Mac, syntax is similar, only C sharp Compiler is just named csc:

$ csc /target:exe /out:MyApplication.exe MyApplication.cs ...

Then to run it :

$ mono MyApplication.exe

What is a segmentation fault?

Simple meaning of Segmentation fault is that you are trying to access some memory which doesn't belong to you. Segmentation fault occurs when we attempt to read and/or write tasks in a read only memory location or try to freed memory. In other words, we can explain this as some sort of memory corruption.

Below I mention common mistakes done by programmers that lead to Segmentation fault.

  • Use scanf() in wrong way(forgot to put &).
int num;
scanf("%d", num);// must use &num instead of num
  • Use pointers in wrong way.
int *num; 
printf("%d",*num); //*num should be correct as num only
//Unless You can use *num but you have to point this pointer to valid memory address before accessing it.
  • Modifying a string literal(pointer try to write or modify a read only memory.)
char *str;  

//Stored in read only part of data segment
str = "GfG";      

//Problem:  trying to modify read only memory
*(str+1) = 'n';
  • Try to reach through an address which is already freed.
// allocating memory to num 
int* num = malloc(8); 
*num = 100; 

// de-allocated the space allocated to num 
free(num); 

// num is already freed there for it cause segmentation fault
*num = 110; 
  • Stack Overflow -: Running out of memory on the stack
  • Accessing an array out of bounds'
  • Use wrong format specifiers when using printf() and scanf()'

How to "EXPIRE" the "HSET" child key in redis?

We had the same problem discussed here.

We have a Redis hash, a key to hash entries (name/value pairs), and we needed to hold individual expiration times on each hash entry.

We implemented this by adding n bytes of prefix data containing encoded expiration information when we write the hash entry values, we also set the key to expire at the time contained in the value being written.

Then, on read, we decode the prefix and check for expiration. This is additional overhead, however, the reads are still O(n) and the entire key will expire when the last hash entry has expired.

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

How to get current domain name in ASP.NET

I use it like this in asp.net core 3.1

 var url =Request.Scheme+"://"+ Request.Host.Value;

Is 'bool' a basic datatype in C++?

Allthough it's now a native type, it's still defined behind the scenes as an integer (int I think) where the literal false is 0 and true is 1. But I think all logic still consider anything but 0 as true, so strictly speaking the true literal is probably a keyword for the compiler to test if something is not false.

if(someval == true){

probably translates to:

if(someval !== false){ // e.g. someval !== 0

by the compiler

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This worked for me.

application.properties, used jdbc-url instead of url:

datasource.apidb.jdbc-url=jdbc:mysql://localhost:3306/apidb?useSSL=false
datasource.apidb.username=root
datasource.apidb.password=123
datasource.apidb.driver-class-name=com.mysql.jdbc.Driver

Configuration class:

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "fooEntityManagerFactory",
        basePackages = {"com.buddhi.multidatasource.foo.repository"}
)
public class FooDataSourceConfig {

    @Bean(name = "fooDataSource")
    @ConfigurationProperties(prefix = "datasource.foo")
    public HikariDataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(name = "fooEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean fooEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("fooDataSource") DataSource dataSource
    ) {
        return builder
                .dataSource(dataSource)
                .packages("com.buddhi.multidatasource.foo.model")
                .persistenceUnit("fooDb")
                .build();
    }
}

firestore: PERMISSION_DENIED: Missing or insufficient permissions

For development only:

Go in Database -> Rules ->

Change allow read, write: if false; to true;

Note: This completely turns off security for the database!

Making it world writable without authentication!!! This is NOT a solution to recommend for a production environment. Only use this for testing purposes.

Recursive Fibonacci

Why not use iterative algorithm?

int fib(int n)
{
    int a = 1, b = 1;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }           
    return b;
}

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

A repo may seem corrupted if you mix different git versions.

Local repositories touched by new git versions aren't backwards-compatible with old git versions. New git repos look corrupted to old git versions (in my case git 2.28 broke repo for git 2.11).

Updating old git version may solve the problem.

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

For window-10 resolved error- make' is not recognized as an internal or external command.

  1. Download MinGW - Minimalist GNU for Windows from here https://sourceforge.net/projects/mingw/

  2. install it

  3. While installation mark all basic setup packages like shown in image enter image description here

  4. Apply changes enter image description here

  5. After completion of installation copy C:\MinGW\bin paste in system variable

Open MyComputer properties and follow as shown in image enter image description here

You may also need to install this

  1. https://sourceforge.net/projects/gnuwin32/

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

Best solution to protect PHP code without encryption

in my opinion is, but just in case if your php code program is written for standalone model... best solutions is c) You could wrap the php in a container like Phalanger (.NET). as everyone knows it's bind tightly to the system especially if your program is intended for windows users. you just can make your own protection algorithm in windows programming language like .NET/VB/C# or whatever you know in .NET prog.lang.family sets.

How to force link from iframe to be opened in the parent window

I found the best solution was to use the base tag. Add the following to the head of the page in the iframe:

<base target="_parent">

This will load all links on the page in the parent window. If you want your links to load in a new window, use:

<base target="_blank">

Browser Support

What is the use of "assert"?

If you ever want to know exactly what a reserved function does in python, type in help(enter_keyword)

Make sure if you are entering a reserved keyword that you enter it as a string.

setTimeout in React Native

Same as above, might help some people.

setTimeout(() => {
  if (pushToken!=null && deviceId!=null) {
    console.log("pushToken & OS ");
    this.setState({ pushToken: pushToken});
    this.setState({ deviceId: deviceId });
    console.log("pushToken & OS "+pushToken+"\n"+deviceId);
  }
}, 1000);

How to print to console when using Qt

If it is good enough to print to stderr, you can use the following streams originally intended for debugging:

#include<QDebug>

//qInfo is qt5.5+ only.
qInfo() << "C++ Style Info Message";
qInfo( "C Style Info Message" );

qDebug() << "C++ Style Debug Message";
qDebug( "C Style Debug Message" );

qWarning() << "C++ Style Warning Message";
qWarning( "C Style Warning Message" );

qCritical() << "C++ Style Critical Error Message";
qCritical( "C Style Critical Error Message" );

// qFatal does not have a C++ style method.
qFatal( "C Style Fatal Error Message" );

Though as pointed out in the comments, bear in mind qDebug messages are removed if QT_NO_DEBUG_OUTPUT is defined

If you need stdout you could try something like this (as Kyle Strand has pointed out):

QTextStream& qStdOut()
{
    static QTextStream ts( stdout );
    return ts;
}

You could then call as follows:

qStdOut() << "std out!";

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How to embed new Youtube's live video permanent URL?

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Python - Convert a bytes array into JSON format

To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.

dumps(s.decode()).replace("'", '"')[1:-1]

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

Where is svcutil.exe in Windows 7?

With latest version of windows (e.g. Windows 10, other servers), type/search for "Developers Command prompt.." It will pop up the relevant command prompt for the Visual Studio version.

e.g. Developer Command Prompt for VS 2015

More here https://msdn.microsoft.com/en-us/library/ms229859(v=vs.110).aspx

Return string without trailing slash

Some of these examples are more complicated than you might need. To remove a single slash, from anywhere (leading or trailing), you could get away with something as simple as this:

let no_trailing_slash_url = site.replace('/', '');

Complete example:

let site1 = "www.somesite.com";  
let site2 = "www.somesite.com/";  

function someFunction(site)
{
    let no_trailing_slash_url = site.replace('/', '');
    return no_trailing_slash_url;
}

console.log(someFunction(site2)); // www.somesite.com

Note that .replace(...) returns a string, it does not modify the string it is called on.

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Find current directory and file's directory

1.To get the current directory full path

    >>import os
    >>print os.getcwd()

o/p:"C :\Users\admin\myfolder"

1.To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]

o/p:"myfolder"

ArrayList: how does the size increase?

  1. Arraylist default capacity is 10.

  2. [1,2,3,4,5.....10]

  3. if you want to increase the size of Arraylist in java, you can apply this

  4. formula-

  5. int newcapacity, current capacity;

  6. newcapacity =((current capacity*3/2)+1)

  7. arralist will be [1,2,3,4,5.....10,11] and arraylist capacity is 16.

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

Custom "confirm" dialog in JavaScript?

I managed to find the solution that will allow you to do this using default confirm() with minimum of changes if you have a lot of confirm() actions through out you code. This example uses jQuery and Bootstrap but the same thing can be accomplished using other libraries as well. You can just copy paste this and it should work right away

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Project Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <!--[if lt IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div class="container">
    <h1>Custom Confirm</h1>
    <button id="action"> Action </button> 
    <button class='another-one'> Another </button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>

<script type="text/javascript">

    document.body.innerHTML += `<div class="modal fade"  style="top:20vh" id="customDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
    <div class="modal-content">
    <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>
    <div class="modal-body">

    </div>
    <div class="modal-footer">
    <button type="button" id='dialog-cancel' class="btn btn-secondary">Cancel</button>
    <button type="button" id='dialog-ok' class="btn btn-primary">Ok</button>
    </div>
    </div>
    </div>
    </div>`;

    function showModal(text) {

        $('#customDialog .modal-body').html(text);
        $('#customDialog').modal('show');

    }

    function startInterval(element) {

         interval = setInterval(function(){

           if ( window.isConfirmed != null ) {

              window.confirm = function() {

                  return window.isConfirmed;
              }

              elConfrimInit.trigger('click');

              clearInterval(interval);
              window.isConfirmed = null;
              window.confirm = function(text) {
                showModal(text);
                startInterval();
            }

           }

        }, 500);

    }

    window.isConfirmed = null;
    window.confirm = function(text,elem = null) {
        elConfrimInit = elem;
        showModal(text);
        startInterval();
    }

    $(document).on('click','#dialog-ok', function(){

        isConfirmed = true;
        $('#customDialog').modal('hide');

    });

    $(document).on('click','#dialog-cancel', function(){

        isConfirmed = false;
        $('#customDialog').modal('hide');

   });

   $('#action').on('click', function(e) {

 

        if ( confirm('Are you sure?',$(this)) ) {

            alert('confrmed');
        }
        else {
            alert('not confimed');
        }
    });

    $('.another-one').on('click', function(e) {


        if ( confirm('Are really, really, really sure ? you sure?',$(this)) ) {

            alert('confirmed');
        }
        else {
            alert('not confimed');
        }
    });


</script>
</body>
</html>

This is the whole example. After you implement it you will be able to use it like this:

if ( confirm('Are you sure?',$(this)) )

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

Angular no provider for NameService

Blockquote

Registering providers in a component

Here's a revised HeroesComponent that registers the HeroService in its providers array.

import { Component } from '@angular/core';

import { HeroService } from './hero.service';

@Component({
  selector: 'my-heroes',
  providers: [HeroService],
  template: `
  `
})
export class HeroesComponent { }

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

Jquery insert new row into table at a certain index

try this:

$("table#myTable tr").last().after(data);

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

Import error No module named skimage

For OSX: pip install scikit-image

and then run python to try following

from skimage.feature import corner_harris, corner_peaks

disable all form elements inside div

For jquery 1.6+, use .prop() instead of .attr(),

$("#parent-selector :input").prop("disabled", true);

or

$("#parent-selector :input").attr("disabled", "disabled");

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

How to Detect Browser Window /Tab Close Event?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;

function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
 var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
 function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;

}
}
window.onbeforeunload=goodbye;

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
 }
 });

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
  // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
});

 // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

 }

  // Wire up the events as soon as the DOM tree is ready
   $(document).ready(function() {
   wireUpEvents();
   });
   </script>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

curl: (60) SSL certificate problem: unable to get local issuer certificate

This is ssh certificate store issue. You need to download the valid certificate pem file from target CA website, and then build the soft link file to instruct ssl the trusted certifacate.

openssl x509 -hash -noout -in DigiCert_Global_Root_G3.pem

you will get dd8e9d41

build solf link with hash number and suffix the file with a .0 (dot-zero)

dd8e9d41.0

Then try again.

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Convert string to a variable name

If you want to convert string to variable inside body of function, but you want to have variable global:

test <- function() {
do.call("<<-",list("vartest","xxx"))
}
test()
vartest

[1] "xxx"

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

How to install easy_install in Python 2.7.1 on Windows 7

Look for the official 2.7 setuptools installer (which contains easy_install). You only need to install from sources for windows 64 bits.

How to scroll to bottom in a ScrollView on activity startup

This is the best way of doing this.

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
});

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

How to serve up images in Angular2?

In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

C++ Pass A String

The obvious way would be to call the function like this

print(string("Yo!"));

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

How to kill all active and inactive oracle sessions for user

Execute this script:

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' 
FROM v$session 
where username='YOUR_USER';

It will printout sqls, which should be executed.

Detect if Android device has Internet connection

You are right. The code you've provided only checks if there is a network connection. The best way to check if there is an active Internet connection is to try and connect to a known server via http.

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

Of course you can substitute the http://www.google.com URL for any other server you want to connect to, or a server you know has a good uptime.

As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead.

If you want to use google.com you should look at Jeshurun's modification. In his answer he modified my code and made it a bit more efficient. If you connect to

HttpURLConnection urlc = (HttpURLConnection) 
            (new URL("http://clients3.google.com/generate_204")
            .openConnection());

and then check the responsecode for 204

return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);

then you don't have to fetch the entire google home page first.

@font-face not working

Double period (..) means you go up one folder and then look for the folder behind the slash. For example:

If your index.html is in the folder html/files and the fonts are in html/fonts, the .. is fine (because you have to go back one folder to go to /fonts). Is your index.html in html and your fonts in html/fonts, then you should use only one period.

Another problem could be that your browser might not support .eot font-files.

Without seeing more of your code (and maybe a link to a live version of your website), I can't really help you further.

Edit: Forget the .eot part, I missed the .ttf file in your css.

Try the following:

@font-face { 
font-family: Gotham;
src: url(../fonts/gothammedium.eot);
src: url(../fonts/Gotham-Medium.ttf); 
}

How to access Spring MVC model object in javascript file?

I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

<script>
  var model=[];
  model.paramOne="${model.paramOne}";
  model.paramTwo="${model.paramTwo}";
  model.paramThree="${model.paramThree}";
</script>

Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

$(document).ready(function() {
   alert(model.paramOne);
});

Can an Android Toast be longer than Toast.LENGTH_LONG?

If you need a long Toast, there's a practical alternative, but it requires your user to click on an OK button to make it go away. You can use an AlertDialog like this:

String message = "This is your message";
new AlertDialog.Builder(YourActivityName.this)
    .setTitle("Optional Title (you can omit this)")
    .setMessage(message)
    .setPositiveButton("ok", null)
    .show();

If you have a long message, chances are, you don't know how long it will take for your user to read the message, so sometimes it is a good idea to require your user to click on an OK button to continue. In my case, I use this technique when a user clicks on a help icon.

Spring boot Security Disable security

If you are using @WebMvcTest annotation in your test class

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
@TestPropertySource(properties = {"spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration"})

doesn't help you.

You can disable security here

@WebMvcTest(secure = false)

How can I convert integer into float in Java?

// The integer I want to convert

int myInt = 100;

// Casting of integer to float

float newFloat = (float) myInt

Use VBA to Clear Immediate Window?

If you happen to be using Autohotkey here's the script I use.

The key command is Ctrl+Delete. It only works if the VBE is active.
When pressed it will clear the immediate window and then activate the code editor, via F7.

I tend to want to clear the immediate when while I'm coding so now I can just hit Ctrl-Delete and keep coding.

#IfWinActive, ahk_class wndclass_desked_gsk

^Delete:: clearImmediateWindow()

#If

clearImmediateWindow() {
    Send, ^g
    Send, ^a
    Send, {Delete}
    Send, {F7}
}

React-Native: Application has not been registered error

I think the node server is running from another folder. So kill it and run in the current folder.

Find running node server:-

lsof -i :8081

Kill running node server :-

kill -9 <PID>

Eg:-

kill -9 1653

Start node server from current react native folder:-

react-native run-android

Stop a youtube video with jquery?

from the API docs:

player.stopVideo()

so in jQuery:

$('#playerID').get(0).stopVideo();

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

How to activate an Anaconda environment

Window: conda activate environment_name

Mac: conda activate environment_name

php - push array into array - key issue

All these answers are nice however when thinking about it....
Sometimes the most simple approach without sophistication will do the trick quicker and with no special functions.

We first set the arrays:

$arr1 = Array(
"cod" => ddd,
"denum" => ffffffffffffffff,
"descr" => ggggggg,
"cant" => 3
);
$arr2 = Array
(
"cod" => fff,
"denum" => dfgdfgdfgdfgdfg,
"descr" => dfgdfgdfgdfgdfg,
"cant" => 33
);

Then we add them to the new array :

$newArr[] = $arr1;
$newArr[] = $arr2;

Now lets see our new array with all the keys:

print_r($newArr);

There's no need for sql or special functions to build a new multi-dimensional array.... don't use a tank to get to where you can walk.

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

Twitter bootstrap collapse: change display of toggle button

I guess you could look inside your downloaded code where exactly there is a + sign (but this might not be very easy).

What I'd do? I'd find the class/id of the DOM elements that contain the + sign (suppose it's ".collapsible", and with Javascript (actually jQuery):

<script>
     $(document).ready(function() {
         var content=$(".collapsible").html().replace("+", "-");
         $(".collapsible").html(content));
     });
</script>

edit Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle, or slideDown and slideUp... Imagine it's a slideToggle for the elements of class .collapsible, which reveal contents of some .info elements. Then:

         $(".collapsible").click(function() { 
             var content=$(".collapsible").html();
             if $(this).next().css("display") === "none") { 
                 $(".collapsible").html(content.replace("+", "-"));
             }
             else $(".collapsible").html(content.replace("-", "+"));
         });

This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.

UnicodeDecodeError, invalid continuation byte

It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset.

If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then you'd just reject ones that didn't decode.

If you can't do that, you'll need heuristics.

Fast check for NaN in NumPy

I think np.isnan(np.min(X)) should do what you want.

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change

function getInstanceByName($name=''){

to

public static function getInstanceByName($name=''){

if you want to call them statically.

Note that static methods (and Singletons) are death to testability.

Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false statements do nothing but end the construction.

COALESCE Function in TSQL

There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

happy coding gl hf nerds

.includes() not working in Internet Explorer

If you want to keep using the Array.prototype.include() in javascript you can use this script: github-script-ie-include That converts automatically the include() to the match() function if it detects IE.

Other option is using always thestring.match(Regex(expression))

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

How do I tell Gradle to use specific JDK version?

You could easily point your desired Java version with specifying in the project level gradle.properties. This would effect the current project rather than altering the language level for every project throughout the system.

org.gradle.java.home=<YOUR_JDK_PATH>

React Native: Getting the position of an element

I had a similar problem and solved it by combining the answers above

class FeedPost extends React.Component {
  constructor(props) {
    ...
    this.handleLayoutChange = this.handleLayoutChange.bind(this);
  }


handleLayoutChange() {
    this.feedPost.measure( (fx, fy, width, height, px, py) => {
      console.log('Component width is: ' + width)
      console.log('Component height is: ' + height)
      console.log('X offset to page: ' + px)
      console.log('Y offset to page: ' + py)
    })
  }

  render {
    return(
      <View onLayout={(event) => {this.handleLayoutChange(event) }} 
      ref={view => { this.feedPost = view; }} >
...

Now I can see the position of my feedPost element in the logs:

08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838  3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Y offset to page: 870

How to connect HTML Divs with Lines?

It's kind of a pain to position, but you could use 1px wide divs as lines and position and rotate them appropriately.

http://jsfiddle.net/sbaBG/1

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>

<div class="line" id="line1"></div>
<div class="line" id="line2"></div>
.box {
    border: 1px solid black;
    background-color: #ccc;
    width: 100px;
    height: 100px;
    position: absolute;
}
.line {
    width: 1px;
    height: 100px;
    background-color: black;
    position: absolute;
}
#box1 {
    top: 0;
    left: 0;
}
#box2 {
    top: 200px;
    left: 0;
}
#box3 {
    top: 250px;
    left: 200px;
}
#line1 {
    top: 100px;
    left: 50px;
}
#line2 {
    top: 220px;
    left: 150px;
    height: 115px;

    transform: rotate(120deg);
    -webkit-transform: rotate(120deg);
    -ms-transform: rotate(120deg);
}

HTTP POST with Json on Body - Flutter/Dart

In my case I forgot to enable

app.use(express.json());

in my NodeJs server.

How to rename a single column in a data.frame?

Let df be the dataframe you have with col names myDays and temp. If you want to rename "myDays" to "Date",

library(plyr)
rename(df,c("myDays" = "Date"))

or with pipe, you can

dfNew      <- df %>% 
  plyr::rename(c("myDays" = "Date"))

How can I tell gcc not to inline a function?

I know the question is about GCC, but I thought it might be useful to have some information about compilers other compilers as well.

GCC's noinline function attribute is pretty popular with other compilers as well. It is supported by at least:

  • Clang (check with __has_attribute(noinline))
  • Intel C/C++ Compiler (their documentation is terrible, but I'm certain it works on 16.0+)
  • Oracle Solaris Studio back to at least 12.2
  • ARM C/C++ Compiler back to at least 4.1
  • IBM XL C/C++ back to at least 10.1
  • TI 8.0+ (or 7.3+ with --gcc, which will define __TI_GNU_ATTRIBUTE_SUPPORT__)

Additionally, MSVC supports __declspec(noinline) back to Visual Studio 7.1. Intel probably supports it too (they try to be compatible with both GCC and MSVC), but I haven't bothered to verify that. The syntax is basically the same:

__declspec(noinline)
static void foo(void) { }

PGI 10.2+ (and probably older) supports a noinline pragma which applies to the next function:

#pragma noinline
static void foo(void) { }

TI 6.0+ supports a FUNC_CANNOT_INLINE pragma which (annoyingly) works differently in C and C++. In C++, it's similar to PGI's:

#pragma FUNC_CANNOT_INLINE;
static void foo(void) { }

In C, however, the function name is required:

#pragma FUNC_CANNOT_INLINE(foo);
static void foo(void) { }

Cray 6.4+ (and possibly earlier) takes a similar approach, requiring the function name:

#pragma _CRI inline_never foo
static void foo(void) { }

Oracle Developer Studio also supports a pragma which takes the function name, going back to at least Forte Developer 6, but note that it needs to come after the declaration, even in recent versions:

static void foo(void);
#pragma no_inline(foo)

Depending on how dedicated you are, you could create a macro that would work everywhere, but you would need to have the function name as well as the declaration as arguments.

If, OTOH, you're okay with something that just works for most people, you can get away with something which is a little more aesthetically pleasing and doesn't require repeating yourself. That's the approach I've taken for Hedley, where the current version of HEDLEY_NEVER_INLINE looks like:

#if \
  HEDLEY_GNUC_HAS_ATTRIBUTE(noinline,4,0,0) || \
  HEDLEY_INTEL_VERSION_CHECK(16,0,0) || \
  HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  (HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
#  define HEDLEY_NEVER_INLINE __attribute__((__noinline__))
#elif HEDLEY_MSVC_VERSION_CHECK(13,10,0)
#  define HEDLEY_NEVER_INLINE __declspec(noinline)
#elif HEDLEY_PGI_VERSION_CHECK(10,2,0)
#  define HEDLEY_NEVER_INLINE _Pragma("noinline")
#elif HEDLEY_TI_VERSION_CHECK(6,0,0)
#  define HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
#else
#  define HEDLEY_NEVER_INLINE HEDLEY_INLINE
#endif

If you don't want to use Hedley (it's a single public domain / CC0 header) you can convert the version checking macros without too much effort, but more than I'm willing to put in ?.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Tensorflow 2.1 works with Cuda 10.1.

If you want a quick hack:

  • Just download cudart64_101.dll from here. Extract the zip file and copy the cudart64_101.dll to your CUDA bin directory

Else:

  • Install Cuda 10.1

How can I show and hide elements based on selected option with jQuery?

You are missing a :selected on the selector for show() - see the jQuery documentation for an example of how to use this.

In your case it will probably look something like this:

$('#'+$('#colorselector option:selected').val()).show();

How to check if two arrays are equal with JavaScript?

Using map() and reduce():

function arraysEqual (a1, a2) {
    return a1 === a2 || (
        a1 !== null && a2 !== null &&
        a1.length === a2.length &&
        a1
            .map(function (val, idx) { return val === a2[idx]; })
            .reduce(function (prev, cur) { return prev && cur; }, true)
    );
}

How to set the authorization header using curl

For HTTP Basic Auth:

curl -H "Authorization: Basic <_your_token_>" http://www.example.com

replace _your_token_ and the URL.

Eclipse error "Could not find or load main class"

Follow The Steps it Works for me : 1.Remove Configure build path from eclipse(Build Path) 2.Refresh 3.add configure Build Path->Source->add Folder->check src ok.