Programs & Examples On #6510

6510 is a microprocessor designed by MOS Technology, Inc. It is a modified version of the 6502 microprocessor with 8-bit IO port addition. 6510 was made famous by being used on the Commodore 64.

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

How to send a POST request with BODY in swift

I don't like any of the other answers so far (except perhaps the one by SwiftDeveloper), because they either require you to deserialize your JSON, only for it to be serialized again, or care about the structure of the JSON itself.

The correct answer has been posted by afrodev in another question. You should go and upvote it.

Below is just my adaption, with some minor changes (primarily explicit UTF-8 charset).

let urlString = "https://example.org/some/api"
let json = "{\"What\":\"Ever\"}"

let url = URL(string: urlString)!
let jsonData = json.data(using: .utf8, allowLossyConversion: false)!

var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData

Alamofire.request(request).responseJSON {
    (response) in

    print(response)
}

How to make HTTP Post request with JSON body in Swift

var request = URLRequest(url: URL(string: "http://yogpande.apphb.com/api/my/posttblhouse")!)
        request.httpMethod = "POST"
        let postString = "[email protected]&password=1234567"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {     
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")

            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

Give column name when read csv file pandas

If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.

user1 = pd.read_csv('dataset/1.csv')

If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.

col_names=['TIME', 'X', 'Y', 'Z'] 
user1 = pd.read_csv('dataset/1.csv', names=col_names)

To solve above problem we have to add extra filled which is supported by pandas, It is header=None

user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)

Reading specific XML elements from XML file

This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties

    class Word
    {
        public string Base { get; set; }
        public string Category { get; set; }
        public string Id { get; set; }
    }

load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .

    XDocument doc = XDocument.Parse(INPUT_DATA);
    XElement lex = doc.Element("lexicon");

make sure there is a value and use linq to extract the word elements from it . . .

    Word[] catWords = null;
    if (lex != null)
    {
        IEnumerable<XElement> words = lex.Elements("word");
        catWords = (from itm in words
                    where itm.Element("category") != null
                        && itm.Element("category").Value == "verb"
                        && itm.Element("id") != null
                        && itm.Element("base") != null
                    select new Word() 
                    {
                        Base = itm.Element("base").Value,
                        Category = itm.Element("category").Value,
                        Id = itm.Element("id").Value,
                    }).ToArray<Word>();
    }

The where statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .

The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.

Then print it to get . . .

[Found]
 Id: E0006429
 Base: abandon
 Category: verb

[Found]
 Id: E0006524
 Base: abolish
 Category: verb

Full Source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test
{
    class Program
    {

        class Word
        {
            public string Base { get; set; }
            public string Category { get; set; }
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(INPUT_DATA);
            XElement lex = doc.Element("lexicon");
            Word[] catWords = null;
            if (lex != null)
            {
                IEnumerable<XElement> words = lex.Elements("word");
                catWords = (from itm in words
                            where itm.Element("category") != null
                                && itm.Element("category").Value == "verb"
                                && itm.Element("id") != null
                                && itm.Element("base") != null
                            select new Word() 
                            {
                                Base = itm.Element("base").Value,
                                Category = itm.Element("category").Value,
                                Id = itm.Element("id").Value,
                            }).ToArray<Word>();
            }

            //print it
            if (catWords != null)
            {
                Console.WriteLine("Words with <category> and value verb:\n");
                foreach (Word itm in catWords)
                    Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n", 
                        itm.Id, itm.Base, itm.Category);
            }
        }

        const string INPUT_DATA =
        @"<?xml version=""1.0""?>
        <lexicon>
        <word>
          <base>a</base>
          <category>determiner</category>
          <id>E0006419</id>
        </word>
        <word>
          <base>abandon</base>
          <category>verb</category>
          <id>E0006429</id>
          <ditransitive/>
          <transitive/>
        </word>
        <word>
          <base>abbey</base>
          <category>noun</category>
          <id>E0203496</id>
        </word>
        <word>
          <base>ability</base>
          <category>noun</category>
          <id>E0006490</id>
        </word>
        <word>
          <base>able</base>
          <category>adjective</category>
          <id>E0006510</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abnormal</base>
          <category>adjective</category>
          <id>E0006517</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abolish</base>
          <category>verb</category>
          <id>E0006524</id>
          <transitive/>
        </word>
        </lexicon>";

    }
}

Time in milliseconds in C

From man clock:

The clock() function returns an approximation of processor time used by the program.

So there is no indication you should treat it as milliseconds. Some standards require precise value of CLOCKS_PER_SEC, so you could rely on it, but I don't think it is advisable. Second thing is that, as @unwind stated, it is not float/double. Man times suggests that will be an int. Also note that:

this function will return the same value approximately every 72 minutes

And if you are unlucky you might hit the moment it is just about to start counting from zero, thus getting negative or huge value (depending on whether you store the result as signed or unsigned value).

This:

printf("\n\n%6.3f", stop);

Will most probably print garbage as treating any int as float is really not defined behaviour (and I think this is where most of your problem comes). If you want to make sure you can always do:

printf("\n\n%6.3f", (double) stop);

Though I would rather go for printing it as long long int at first:

printf("\n\n%lldf", (long long int) stop);

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

Java integer to byte array

The chunks below work at least for sending an int over UDP.

int to byte array:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

byte array to int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}

How do I use dataReceived event of the SerialPort Port Object in C#?

Might very well be the Console.ReadLine blocking your callback's Console.Writeline, in fact. The sample on MSDN looks ALMOST identical, except they use ReadKey (which doesn't lock the console).

What should main() return in C and C++?

I believe that main() should return either EXIT_SUCCESS or EXIT_FAILURE. They are defined in stdlib.h

How to export JSON from MongoDB using Robomongo

A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray() and right click Copy JSON. Paste the data in the editor of your choice.

enter image description here

OS X: equivalent of Linux's wget

Instead of going with equivalent, you can try "brew install wget" and use wget.

You need to have brew installed in your mac.

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

htaccess remove index.php from url

Assuming the existent url is

http://example.com/index.php/foo/bar

and we want to convert it into

 http://example.com/foo/bar

You can use the following rule :

RewriteEngine on
#1) redirect the client from "/index.php/foo/bar" to "/foo/bar"
RewriteCond %{THE_REQUEST} /index\.php/(.+)\sHTTP [NC]
RewriteRule ^ /%1 [NE,L,R]
#2)internally map "/foo/bar" to "/index.php/foo/bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]

In the spep #1 we first match against the request string and capture everything after the /index.php/ and the captured value is saved in %1 var. We then send the browser to a new url. The #2 processes the request internally. When the browser arrives at /foo/bar , #2rule rewrites the new url to the orignal location.

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.

Note: It's just a simple representation. Weighted Edges could be added like

g.add_edges_from([(1,2),(2,5)], weight=2)

and hence plotted again.

Java: how to import a jar file from command line

If you're running a jar file with java -jar, the -classpath argument is ignored. You need to set the classpath in the manifest file of your jar, like so:

Class-Path: jar1-name jar2-name directory-name/jar3-name

See the Java tutorials: Adding Classes to the JAR File's Classpath.

Edit: I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the ':' after "Class-Path" like you showed, it would not work.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

SOAP­based Web Services In short, the SOAP­based Services model views the world as an ecosystem of co­equal peers that cannot control each other, but have to work together by honoring published contracts. It's a valid model of the messy real world, and the metadata ­based contracts form the SOAP Service Interface.

we can still associate SOAP with XML­based Remote Procedure Calls, but SOAP­based Web Services technology has emerged into a flexible and powerful messaging model.

SOAP assumes all systems are independent and no system has any knowledge of the internals of another and internal functionality. The most such systems can do is send messages to one another and hope they will be acted upon. Systems publish contracts that they undertake to honor, and other systems rely upon these contracts to exchange messages with them.

Contracts between systems are collectively called metadata, and comprise service descriptions, the message exchange patterns supported and the policies governing qualities of service (a service may need to be encrypted, reliably delivered, etc.) A service description, in turn, is a detailed specification of the data (message documents) that will be sent and received by the system. The documents are described using an XML description language like XML Schema Definition. As long as all systems honor their published contracts, they can inter operate, and changes to the internals of systems never affect any other. Every system is responsible for translating its own internal implementations to and from its contracts

REST - REpresentational State Transfer. The physical protocol is HTTP. Basically, REST is that all distinct resources on the web that are uniquely identifiable by a URL. All operations that can be performed on these resources can be described by a limited set of verbs (the “CRUD” verbs) which in turn map to HTTP verbs.

REST's is much less “heavyweight” than SOAP.

Working of web service

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

If you have an html form containing one or more fields with "required" attributes, Chrome (on last versions) will validate these fields before submitting the form and, if they are not filled, some tooltips will be shown to the users to help them getting the form submitted (I.e. "please fill out this field").

To avoid this browser built-in validation in forms you can use "novalidate" attribute on your form tag. This form won't be validated by browser:

<form id="form-id" novalidate>

    <input id="input-id" type="text" required>

    <input id="submit-button" type="submit">

</form>

Adding headers when using httpClient.GetAsync

The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:

client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);

How can I simulate a print statement in MySQL?

to take output in MySQL you can use if statement SYNTAX:

if(condition,if_true,if_false)

the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL

Can I delete data from the iOS DeviceSupport directory?

Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect

Implementing Singleton with an Enum (in Java)

Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.

I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

git: Your branch is ahead by X commits

Use these 3 simple commands

Step 1 : git checkout <branch_name>

Step 2 : git pull -s recursive -X theirs

Step 3 : git reset --hard origin/<branch_name>

More details : https://stackoverflow.com/a/39698570/2439715

Enjoy.

How to display the string html contents into webbrowser control?

Instead of navigating to blank, you can do

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.

Sending commands and strings to Terminal.app with Applescript

Your question is specifically about how to get Applescript to do what you want. But, for the particular example described, you might want to look into 'expect' as a solution.

How to get first two characters of a string in oracle query?

take a look here

SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR FROM DUAL;

TypeError: Converting circular structure to JSON in nodejs

I also ran into this issue. It was because I forgot to await for a promise.

What is the difference between varchar and nvarchar?

Mainly nvarchar stores Unicode characters and varchar stores non-Unicode characters.

"Unicodes" means 16-bit character encoding scheme allowing characters from lots of other languages like Arabic, Hebrew, Chinese, Japanese, to be encoded in a single character set.

That means unicodes is using 2 bytes per character to store and nonunicodes uses only one byte per character to store. Which means unicodes need double capacity to store compared to non-unicodes.

Convert column classes in data.table

I provide a more general and safer way to do this stuff,

".." <- function (x) 
{
  stopifnot(inherits(x, "character"))
  stopifnot(length(x) == 1)
  get(x, parent.frame(4))
}


set_colclass <- function(x, class){
  stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
  for(i in intersect(names(class), names(x))){
    f <- get(paste0("as.", class[i]))
    x[, (..("i")):=..("f")(get(..("i")))]
  }
  invisible(x)
}

The function .. makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols. You can use it like this:

dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)

When to use StringBuilder in Java

As a general rule, always use the more readable code and only refactor if performance is an issue. In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case.

You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize.

Round a double to 2 decimal places

In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?

You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;  
(int) 20034.56 = 20034;  
20034/100.0 = 200.34;

You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.

jQuery: Check if button is clicked

$('#btn1, #btn2').click(function() {
    let clickedButton = $(this).attr('id');
    console.log(clickedButton);
});

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

Material effect on button with background color

With AppCompat (22.1.1+) you can add a style like this:

<style name="MyGreenButton">
    <item name="colorButtonNormal">#009900</item>
</style>

And use it by just applying the style:

<android.support.v7.widget.AppCompatButton
    style="@style/MyGreenButton"
    android:layout_width="match_width"
    android:layout_height="wrap_content"
    android:text="A Green Button"
    />

Programmatically changing the color, I found that the only way to update the color (on API 15 or 16) was to use the 'background tint list' instead. And it doesn't remove the nice radial animation on API 21 devices:

ColorStateList colorStateList = new ColorStateList(new int[][] {{0}}, new int[] {0xFF009900}); // 0xAARRGGBB
button.setSupportBackgroundTintList(colorStateList);

Because button.setBackground(...) and button.getBackground().mutate().setColorFilter(...) do not change the button color on API 15 and 16 like they do on API 21.

How to stop INFO messages displaying on spark console?

Simple to do on the command line...

spark2-submit --driver-java-options="-Droot.logger=ERROR,console" ..other options..

Javascript - How to extract filename from a file input control

To split the string ({filepath}/{filename}) and get the file name you could use something like this:

str.split(/(\\|\/)/g).pop()

"The pop method removes the last element from an array and returns that value to the caller."
Mozilla Developer Network

Example:

from: "/home/user/file.txt".split(/(\\|\/)/g).pop()

you get: "file.txt"

Simulate a button click in Jest

Solutions in accepted answer are being deprecated

#4 Calling prop directly

Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.

You could call click, for example:

wrapper.find('Button').prop('onClick')() 

Or

wrapper.find('Button').props().onClick() 

Information about deprecation: Deprecation of .simulate() #2173

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Node.js version on the command line? (not the REPL)

By default node package is nodejs, so use

$ nodejs -v

or

$ nodejs --version 

You can make a link using

$ sudo ln -s /usr/bin/nodejs /usr/bin/node

then u can use

$ node --version

or

$ node -v

In C#, what's the difference between \n and \r\n?

\n is the line break used by Unix(-like) systems, \r\n is used by windows. This has nothing to do with C#.

Linux shell script for database backup

As a DBA, You must schedule the backup of MySQL Database in case of any issues so that you can recover your databases from the current backup.

Here, we are using mysqldump to take the backup of mysql databases and the same you can put into the script.

[orahow@oradbdb DB_Backup]$ cat .backup_script.sh

#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions

Continue Reading .... MySQL Backup

How to perform runtime type checking in Dart?

Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)

class Object {
  //...
  external Type get runtimeType;
}

Usage:

Object o = 'foo';
assert(o.runtimeType == String);

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

How to return JSON with ASP.NET & jQuery

Try to use this , it works perfectly for me

  // 

   varb = new List<object>();

 // Example 

   varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});

 // JSON  + Serializ

public string Json()
        {  
            return (new JavaScriptSerializer()).Serialize(varb);
        }


//  Jquery SIDE 

  var datasets = {
            "Products": {
                label: "Products",
                data: <%= getJson() %> 
            }

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

Docker - Ubuntu - bash: ping: command not found

Sometimes, the minimal installation of Linux in Docker doesn't define the path and therefore it is necessary to call ping using ....

cd /usr/sbin
ping <ip>

How do I remove newlines from a text file?

use

head -n 1 filename | od -c 

to figure WHAT is the offending character. then use

tr -d '\n' <filename

for LF

tr -d '\r\n' <filename

for CRLF

C++ JSON Serialization

The jsoncons C++ header-only library also supports conversion between JSON text and C++ objects. Decode and encode are defined for all C++ classes that have json_type_traits defined. The standard library containers are already supported, and json_type_traits can be specialized for user types in the jsoncons namespace.

Below is an example:

#include <iostream>
#include <jsoncons/json.hpp>

namespace ns {
    enum class hiking_experience {beginner,intermediate,advanced};

    class hiking_reputon
    {
        std::string rater_;
        hiking_experience assertion_;
        std::string rated_;
        double rating_;
    public:
        hiking_reputon(const std::string& rater,
                       hiking_experience assertion,
                       const std::string& rated,
                       double rating)
            : rater_(rater), assertion_(assertion), rated_(rated), rating_(rating)
        {
        }

        const std::string& rater() const {return rater_;}
        hiking_experience assertion() const {return assertion_;}
        const std::string& rated() const {return rated_;}
        double rating() const {return rating_;}
    };

    class hiking_reputation
    {
        std::string application_;
        std::vector<hiking_reputon> reputons_;
    public:
        hiking_reputation(const std::string& application, 
                          const std::vector<hiking_reputon>& reputons)
            : application_(application), 
              reputons_(reputons)
        {}

        const std::string& application() const { return application_;}
        const std::vector<hiking_reputon>& reputons() const { return reputons_;}
    };

} // namespace ns

// Declare the traits using convenience macros. Specify which data members need to be serialized.

JSONCONS_ENUM_TRAITS_DECL(ns::hiking_experience, beginner, intermediate, advanced)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputon, rater, assertion, rated, rating)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputation, application, reputons)

using namespace jsoncons; // for convenience

int main()
{

std::string data = R"(
    {
       "application": "hiking",
       "reputons": [
       {
           "rater": "HikingAsylum",
           "assertion": "advanced",
           "rated": "Marilyn C",
           "rating": 0.90
         }
       ]
    }
)";

    // Decode the string of data into a c++ structure
    ns::hiking_reputation v = decode_json<ns::hiking_reputation>(data);

    // Iterate over reputons array value
    std::cout << "(1)\n";
    for (const auto& item : v.reputons())
    {
        std::cout << item.rated() << ", " << item.rating() << "\n";
    }

    // Encode the c++ structure into a string
    std::string s;
    encode_json<ns::hiking_reputation>(v, s, indenting::indent);
    std::cout << "(2)\n";
    std::cout << s << "\n";
}    

Output:

(1)
Marilyn C, 0.9
(2)
{
    "application": "hiking",
    "reputons": [
        {
            "assertion": "advanced",
            "rated": "Marilyn C",
            "rater": "HikingAsylum",
            "rating": 0.9
        }
    ]
}

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How can I mock an ES6 module import using Jest?

To mock an ES6 dependency module default export using Jest:

import myModule from '../myModule';
import dependency from '../dependency';

jest.mock('../dependency');

// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);

describe('myModule', () => {
  it('calls the dependency once with double the input', () => {
    myModule(2);

    expect(dependency).toHaveBeenCalledTimes(1);
    expect(dependency).toHaveBeenCalledWith(4);
  });
});

The other options didn't work for my case.

Fastest way to set all values of an array?

Arrays.fill might suit your needs

Enable 'xp_cmdshell' SQL Server

While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE in RECONFIGURE gives the solution

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

The expected output is

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.

How are Anonymous inner classes used in Java?

They're commonly used as a verbose form of callback.

I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)

Here's a swing example

myButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here...
    }
});

Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)

How to add local .jar file dependency to build.gradle file?

According to the documentation, use a relative path for a local jar dependency as follows:

dependencies {
    implementation files('libs/something_local.jar')
}

What are .NET Assemblies?

Wikipedia has to say:

In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security. There are two types: process assemblies (EXE) and library assemblies (DLL). A process assembly represents a process which will use classes defined in library assemblies. .NET assemblies contain code in CIL, which is usually generated from a CLI language, and then compiled into machine language at runtime by the CLR just-in-time compiler. An assembly can consist of one or more files. Code files are called modules. An assembly can contain more than one code module and since it is possible to use different languages to create code modules it is technically possible to use several different languages to create an assembly. Visual Studio however does not support using different languages in one assembly.

If you really did browse it would help if you'd clarify what you don't understand

How to convert a hex string to hex number

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

Read user input inside a loop

You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0

BTW, if you really are using cat this way, replace it with a redirect and things become even easier:

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished

Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished

Run batch file as a Windows service

Why not simply set it up as a Scheduled Task that is scheduled to run at start up?

Paste multiple columns together

In my opinion the sprintf-function deserves a place among these answers as well. You can use sprintf as follows:

do.call(sprintf, c(d[cols], '%s-%s-%s'))

which gives:

 [1] "a-d-g" "b-e-h" "c-f-i"

And to create the required dataframe:

data.frame(a = d$a, x = do.call(sprintf, c(d[cols], '%s-%s-%s')))

giving:

  a     x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i

Although sprintf doesn't have a clear advantage over the do.call/paste combination of @BrianDiggs, it is especially usefull when you also want to pad certain parts of desired string or when you want to specify the number of digit. See ?sprintf for the several options.

Another variant would be to use pmap from :

pmap(d[2:4], paste, sep = '-')

Note: this pmap solution only works when the columns aren't factors.


A benchmark on a larger dataset:

# create a larger dataset
d2 <- d[sample(1:3,1e6,TRUE),]
# benchmark
library(microbenchmark)
microbenchmark(
  docp = do.call(paste, c(d2[cols], sep="-")),
  appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
  tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
  docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
  times=10)

results in:

Unit: milliseconds
 expr       min        lq      mean    median        uq       max neval cld
 docp  214.1786  226.2835  297.1487  241.6150  409.2495  493.5036    10 a  
 appl 3832.3252 4048.9320 4131.6906 4072.4235 4255.1347 4486.9787    10   c
 tidr  206.9326  216.8619  275.4556  252.1381  318.4249  407.9816    10 a  
 docs  413.9073  443.1550  490.6520  453.1635  530.1318  659.8400    10  b 

Used data:

d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i')) 

How might I schedule a C# Windows Service to perform a task daily?

You can also try the TaskSchedulerLibrary here http://visualstudiogallery.msdn.microsoft.com/a4a4f042-ffd3-42f2-a689-290ec13011f8

Implement the abstract class AbstractScheduledTask and call the ScheduleUtilityFactory.AddScheduleTaskToBatch static method

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

The problem was the cuDNN Library for me - for whatever reason cudnn-8.0-windows10-x64-v6.0 was NOT working - I used cudnn-8.0-windows10-x64-v5.1 - ALL GOOD!

My setup working with Win10 64 and the Nvidia GTX780M:

  • Be sure you have the lib MSVCP140.DLL by checking your system/path - if not get it here
  • Run the windows installer for python 3.5.3-amd64 from here - DO NOT try newer versions as they probably won't work
  • Get the cuDNN v5.1 for CUDA 8.0 from here - put it under your users folder or in another known location (you will need this in your path)
  • Get CUDA 8.0 x86_64 from here
  • Set PATH vars as expected to point at the cuDNN libs and python (the python path should be added during the python install)
  • Make sure that ".DLL" is included in your PATHEXT variable
  • If you are using tensorflow 1.3 then you want to use cudnn64_6.dll github.com/tensorflow/tensorflow/issues/7705

If you run Windows 32 be sure to get the 32 bit versions of the files mentioned above.

How to give a Blob uploaded as FormData a file name?

Are you using Google App Engine? You could use cookies (made with JavaScript) to maintain a relationship between filenames and the name received from the server.

How to represent matrices in python

((1,2,3,4),
 (5,6,7,8),
 (9,0,1,2))

Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.

If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

What is the difference between a cer, pvk, and pfx file?

Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:

  • Both PKCS12 and PEM can store entire cert chains: public keys, private keys, and root (CA) certs.
  • .pfx == .p12 == "PKCS12"
    • fully encrypted
  • .pem == .cer == .cert == "PEM" (or maybe not... could be binary... see comments...)
    • base-64 (string) encoded X509 cert (binary) with a header and footer
      • base-64 is basically just a string of "A-Za-z0-9+/" used to represent 0-63, 6 bits of binary at a time, in sequence, sometimes with 1 or 2 "=" characters at the very end when there are leftovers ("=" being "filler/junk/ignore/throw away" characters)
      • the header and footer is something like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" or "-----BEGIN ENCRYPTED PRIVATE KEY-----" and "-----END ENCRYPTED PRIVATE KEY-----"
    • Windows recognizes .cer and .cert as cert files
  • .jks == "Java Key Store"
    • just a Java-specific file format which the API uses
      • .p12 and .pfx files can also be used with the JKS API
  • "Trust Stores" contain public, trusted, root (CA) certs, whereas "Identity/Key Stores" contain private, identity certs; file-wise, however, they are the same.

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

Error: "an object reference is required for the non-static field, method or property..."

Create a class and put all your code in there and call an instance of this class from the Main :

static void Main(string[] args)
{

    MyClass cls  = new MyClass();
    Console.Write("Write a number: ");
    long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
    long av = cls.volteado(a);
    bool isTrue = cls.siprimo(a);
    ......etc

}

One-liner if statements, how to convert this if-else-statement

Since expression is boolean:

return expression;

How to reload page every 5 seconds?

There's an automatic refresh-on-change tool for IE. It's called ReloadIt, and is available at http://reloadit.codeplex.com . Free.

You choose a URL that you'd like to auto-reload, and specify one or more directory paths to monitor for changes. Press F12 to start monitoring.

enter image description here

After you set it, minimize it. Then edit your content files. When you save any change, the page gets reloaded. like this:

enter image description here

Simple. easy.

Is there a real solution to debug cordova apps

You can use Intel XDK IDE to develop and debug on emulator or on real device

I also found Visual Studio 2015 RC tools for cordova very good, with it's ripple emulator

Big-oh vs big-theta

I'm a mathematician and I have seen and needed big-O O(n), big-Theta T(n), and big-Omega O(n) notation time and again, and not just for complexity of algorithms. As people said, big-Theta is a two-sided bound. Strictly speaking, you should use it when you want to explain that that is how well an algorithm can do, and that either that algorithm can't do better or that no algorithm can do better. For instance, if you say "Sorting requires T(n(log n)) comparisons for worst-case input", then you're explaining that there is a sorting algorithm that uses O(n(log n)) comparisons for any input; and that for every sorting algorithm, there is an input that forces it to make O(n(log n)) comparisons.

Now, one narrow reason that people use O instead of O is to drop disclaimers about worst or average cases. If you say "sorting requires O(n(log n)) comparisons", then the statement still holds true for favorable input. Another narrow reason is that even if one algorithm to do X takes time T(f(n)), another algorithm might do better, so you can only say that the complexity of X itself is O(f(n)).

However, there is a broader reason that people informally use O. At a human level, it's a pain to always make two-sided statements when the converse side is "obvious" from context. Since I'm a mathematician, I would ideally always be careful to say "I will take an umbrella if and only if it rains" or "I can juggle 4 balls but not 5", instead of "I will take an umbrella if it rains" or "I can juggle 4 balls". But the other halves of such statements are often obviously intended or obviously not intended. It's just human nature to be sloppy about the obvious. It's confusing to split hairs.

Unfortunately, in a rigorous area such as math or theory of algorithms, it's also confusing not to split hairs. People will inevitably say O when they should have said O or T. Skipping details because they're "obvious" always leads to misunderstandings. There is no solution for that.

Running shell command and capturing the output

This is way easier, but only works on Unix (including Cygwin) and Python2.7.

import commands
print commands.getstatusoutput('wc -l file')

It returns a tuple with the (return_value, output).

For a solution that works in both Python2 and Python3, use the subprocess module instead:

from subprocess import Popen, PIPE
output = Popen(["date"],stdout=PIPE)
response = output.communicate()
print response

Using colors with printf

I use this c code for printing coloured shell output. The code is based on this post.

//General Formatting
#define GEN_FORMAT_RESET                "0"
#define GEN_FORMAT_BRIGHT               "1"
#define GEN_FORMAT_DIM                  "2"
#define GEN_FORMAT_UNDERSCORE           "3"
#define GEN_FORMAT_BLINK                "4"
#define GEN_FORMAT_REVERSE              "5"
#define GEN_FORMAT_HIDDEN               "6"

//Foreground Colors
#define FOREGROUND_COL_BLACK            "30"
#define FOREGROUND_COL_RED              "31"
#define FOREGROUND_COL_GREEN            "32"
#define FOREGROUND_COL_YELLOW           "33"
#define FOREGROUND_COL_BLUE             "34"
#define FOREGROUND_COL_MAGENTA          "35"
#define FOREGROUND_COL_CYAN             "36"
#define FOREGROUND_COL_WHITE            "37"

//Background Colors
#define BACKGROUND_COL_BLACK            "40"
#define BACKGROUND_COL_RED              "41"
#define BACKGROUND_COL_GREEN            "42"
#define BACKGROUND_COL_YELLOW           "43"
#define BACKGROUND_COL_BLUE             "44"
#define BACKGROUND_COL_MAGENTA          "45"
#define BACKGROUND_COL_CYAN             "46"
#define BACKGROUND_COL_WHITE            "47"

#define SHELL_COLOR_ESCAPE_SEQ(X) "\x1b["X"m"
#define SHELL_FORMAT_RESET  ANSI_COLOR_ESCAPE_SEQ(GEN_FORMAT_RESET)

int main(int argc, char* argv[])
{
    //The long way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW), stdout);
    fputs("Text in gold\n", stdout);
    fputs(SHELL_FORMAT_RESET, stdout);
    fputs("Text in default color\n", stdout);

    //The short way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW)"Text in gold\n"SHELL_FORMAT_RESET"Text in default color\n", stdout);

    return 0;
}

How to copy a huge table data into another table in SQL Server

I had the same problem, except I have a table with 2 billion rows, so the log file would grow to no end if I did this, even with the recovery model set to Bulk-Logging:

insert into newtable select * from oldtable

So I operate on blocks of data. This way, if the transfer is interupted, you just restart it. Also, you don't need a log file as big as the table. You also seem to get less tempdb I/O, not sure why.

set identity_insert newtable on
DECLARE @StartID bigint, @LastID bigint, @EndID bigint
select @StartID = isNull(max(id),0) + 1
from newtable

select @LastID = max(ID)
from oldtable

while @StartID < @LastID
begin
    set @EndID = @StartID + 1000000

    insert into newtable (FIELDS,GO,HERE)
    select FIELDS,GO,HERE from oldtable (NOLOCK)
    where id BETWEEN @StartID AND @EndId

    set @StartID = @EndID + 1
end
set identity_insert newtable off
go

You might need to change how you deal with IDs, this works best if your table is clustered by ID.

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

Removing Data From ElasticSearch

There are lots of good answers here, but there is also something i'd like to add:

  • If you are running on AWS ElasticSearch service, you can´t drop/delete indexes. Instead of delete indexes, you must reindex them.

Convert a list to a string in C#

If you want something slightly more complex than a simple join you can use LINQ e.g.

var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");

Will take ["A", "B", "C"] and produce "(a)(b)(c)"

Efficiently updating database using SQLAlchemy ORM

If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.

If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Error : error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Executing sudo apt-get install python-dev solved the error.

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Further to the answer by Jon Skeet, which uses this example code:

// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?

At the deepest level, the problem here is that dogs and animals share a reference. That means that one way to make this work would be to copy the entire list, which would break reference equality:

// This code is fine
List<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog());
List<Animal> animals = new ArrayList<>(dogs); // Copy list
animals.add(new Cat());
Dog dog = dogs.get(0);   // This is fine now, because it does not return the Cat

After calling List<Animal> animals = new ArrayList<>(dogs);, you cannot subsequently directly assign animals to either dogs or cats:

// These are both illegal
dogs = animals;
cats = animals;

therefore you can't put the wrong subtype of Animal into the list, because there is no wrong subtype -- any object of subtype ? extends Animal can be added to animals.

Obviously, this changes the semantics, since the lists animals and dogs are no longer shared, so adding to one list does not add to the other (which is exactly what you want, to avoid the problem that a Cat could be added to a list that is only supposed to contain Dog objects). Also, copying the entire list can be inefficient. However, this does solve the type equivalence problem, by breaking reference equality.

GET parameters in the URL with CodeIgniter

You can enable query strings if you really insist. In your config.php you can enable query strings:

$config['enable_query_strings'] = TRUE;

For more info you can look at the bottom of this Wiki page: http://codeigniter.com/user_guide/general/urls.html

Still, learning to work with clean urls is a better suggestion.

Disallow Twitter Bootstrap modal window from closing

I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.

Example:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

OR if you are using JavaScript:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

Determine function name from within that function (without using traceback)

functionNameAsString = sys._getframe().f_code.co_name

I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.

How to run regasm.exe from command line other than Visual Studio command prompt?

For the 64-bit RegAsm.exe you will need to find it someplace like this:

c:\Windows\Microsoft.NET\Framework64\version_number_stuff\regasm.exe

Markdown `native` text alignment

In order to center text in md files you can use the center tag like html tag:

<center>Centered text</center>

Mongodb service won't start

When I ran mongod.exe from Windows Terminal I got a message Unrecognized option: mp. There was an empty mp: in the end of mongod.cfg. Removing that solved the problem for me.

How do I share a global variable between c files?

Do same as you did in file1.c In file2.c:

#include <stdio.h> 

extern int i;  /*This declare that i is an int variable which is defined in some other file*/

int main(void)
{
/* your code*/

If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c

Hive External Table Skip First Row

I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"

disable a hyperlink using jQuery

Below will replace the link with it's text

$('a').each(function () {
    $(this).replaceWith($(this).text());
});

Edit :

Above given code will work with hyperlinks with text only, it will not work with images. When we'll try it with image link it won't show any image.

To make this code compatible with image links following will work fine

// below given function will replace links with images i.e. for image links
$('a img').each(function () {
    var image = this.src;
    var img = $('<img>', { src: image });
    $(this).parent().replaceWith(img);
});

// This piece of code will replace links with its text i.e. for text links
$('a').each(function () {
    $(this).replaceWith($(this).text());
});

explanation : In above given code snippets, in first snippet we are replacing all the image links with it's images only. After that we are replacing text links with it's text.

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Add a Progress Bar in WebView

in oncreate method where you have set your Webview.

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);

web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(SiteOpenInWebView.this);
    pd.setMessage("Please wait Loading...");
    pd.show();
    web_view.setWebViewClient(new MyWebViewClient());
    web_view.loadUrl("ur site name");
 }

WebViewClient

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);

    if (!pd.isShowing()) {
        pd.show();
    }

    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    System.out.println("on finish");
    if (pd.isShowing()) {
        pd.dismiss();
    }

  }
}

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Is there a way to programmatically scroll a scroll view to a specific edit text?

In my opinion the best way to scroll to a given rectangle is via View.requestRectangleOnScreen(Rect, Boolean). You should call it on a View you want to scroll to and pass a local rectangle you want to be visible on the screen. The second parameter should be false for smooth scrolling and true for immediate scrolling.

final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, false);

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

When you install the WAMPP in your machine by default the password of PhpMyAdmin is blank. so put root in user Section and left blank of password field. hope it works.

Happy Coding!!

What does '?' do in C++?

Just a note, if you ever see this:

a = x ? : y;

It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals).

It is the same as

a = x ? x : y;

How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App : https://www.postman.com/

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

The simplest way to comma-delimit a list?

StringBuffer result = new StringBuffer();
for(Iterator it=list.iterator; it.hasNext(); ) {
  if (result.length()>0)
    result.append(", ");
  result.append(it.next());
}

Update: As Dave Webb mentioned in the comments this may not produce correct results if the first items in the list are empty strings.

Nested iframes, AKA Iframe Inception

You should use live method for elements which are rendered later, like colorbox, hidden fields or iframe

$(".inverter-value").live("change",function() {
     elem = this
    $.ajax({
      url: '/main/invertor_attribute/',
      type: 'POST',
      aysnc: false,
      data: {id: $(this).val() },
      success: function(data){
       // code
      },
      dataType: 'html'
    });
  });

How to use LocalBroadcastManager?

An example of an Activity and a Service implementing a LocalBroadcastManager can be found in the developer docs. I personally found it very useful.

EDIT: The link has since then been removed from the site, but the data is the following: https://github.com/carrot-garden/android_maven-android-plugin-samples/blob/master/support4demos/src/com/example/android/supportv4/content/LocalServiceBroadcaster.java

Limiting the number of characters in a string, and chopping off the rest

If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.

int maxLength = 5;
StringUtils.left(string, maxLength);

Output:

      null -> null
        "" -> ""
       "a" -> "a"
"abcd1234" -> "abcd1"

Left Documentation

Regex to remove all special characters from string?

It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:

tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");

You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:

"TRA-12:123"
"TRA-121:23"

Why can't variables be declared in a switch statement?

Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization.

The correct way to handle this is to define a scope specific to that case statement and define your variable within it:

switch (val)
{   
case VAL:  
{
  // This will work
  int newVal = 42;  
  break;
}
case ANOTHER_VAL:  
...
break;
}

.m2 , settings.xml in Ubuntu

.m2 directory on linux box usually would be $HOME/.m2

you could get the $HOME :

echo $HOME

or simply:

cd <enter>

to go to your home directory.

other information from maven site: http://maven.apache.org/download.html#Installation

Spring Boot Program cannot find main class

I ran into same error, although i was using gradle build. Delegating IDE build/run actions to Gradle is solved my problem.

Intellij: Settings -> Build, Execution, Deployment -> Build Tools -> Gradle -> Runner

Screenshot

Submit button not working in Bootstrap form

Replace this

 <button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">

with

<button  value=" Send" class="btn btn-success" type="submit" id="submit">

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.

Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.

LaTeX table positioning

If you want to have two tables next to each other you can use: (with float package loaded)

\begin{table}[H]
 \begin{minipage}{.5\textwidth}
  %first table
 \end{minipage}
 \begin{minipage}{.5\textwidth}
  %second table
 \end{minipage}
\end{table}

Each one will have own caption and number. Another option is subfigure package.

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

INSERT with SELECT

Correct Syntax: select spelling was wrong

INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci 

python dataframe pandas drop column using int

You can delete column on i index like this:

df.drop(df.columns[i], axis=1)

It could work strange, if you have duplicate names in columns, so to do this you can rename column you want to delete column by new name. Or you can reassign DataFrame like this:

df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]]

How to send parameters from a notification-click to an activity?

After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.

like this:

   Intent notificationIntent = new Intent(Main.this, Main.class);
   notificationIntent.putExtra("sport_id", "sport"+id);
   notificationIntent.putExtra("game_url", "gameURL"+id);

   notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime()))); 

I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...

How do I call an Angular.js filter with multiple arguments?

In this code, jsondata is our array and in function return we are checking the 'version' present in the jsondata.

var as = $filter('filter')(jsondata, function (n,jsondata){
   return n.filter.version==='V.0.3'
});

console.log("name is " + as[0].name+as[0]); 

Using external images for CSS custom cursors

I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:

.test {
    cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}

Not able to start Genymotion device

I had to change Adapter's address to: 192.168.56.100.

Then it worked.

Programmatically get height of navigation bar

iOS 14

For me, view.window is null on iOS 14.

extension UIViewController {
    var topBarHeight: CGFloat {
        var top = self.navigationController?.navigationBar.frame.height ?? 0.0
        if #available(iOS 13.0, *) {
            top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
        } else {
            top += UIApplication.shared.statusBarFrame.height
        }
        return top
    }
}

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

How to use comparison and ' if not' in python?

In this particular case the clearest solution is the S.Lott answer

But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.

Using De Morgan's law ¬(A^B) = ¬Av¬B

not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step

then

if u0 > u or u >= u0+step:
    pass

... in this case the «clear» solution is not more clear :P

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

What is the difference between aggregation, composition and dependency?

An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.

On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.

A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.

Dropping Unique constraint from MySQL table

The constraint could be removed with syntax:

ALTER TABLE

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

Example:

CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));

-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';

-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;

db<>fiddle demo

How to show loading spinner in jQuery?

I ended up with two changes to the original reply.

  1. As of jQuery 1.8, ajaxStart and ajaxStop should only be attached to document. This makes it harder to filter only a some of the ajax requests. Soo...
  2. Switching to ajaxSend and ajaxComplete makes it possible to interspect the current ajax request before showing the spinner.

This is the code after these changes:

$(document)
    .hide()  // hide it initially
    .ajaxSend(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").show();
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").hide();
    })

Normalize data in pandas

If you don't mind importing the sklearn library, I would recommend the method talked on this blog.

import pandas as pd
from sklearn import preprocessing

data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
cols = data.columns
df = pd.DataFrame(data)
df

min_max_scaler = preprocessing.MinMaxScaler()
np_scaled = min_max_scaler.fit_transform(df)
df_normalized = pd.DataFrame(np_scaled, columns = cols)
df_normalized

How do I create an .exe for a Java program?

Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).

As for wrappers, the best ones i've used (as previously suggested) are:

JSmooth

and

Launch4j

best of luck!

How to encode the filename parameter of Content-Disposition header in HTTP?

I normally URL-encode (with %xx) the filenames, and it seems to work in all browsers. You might want to do some tests anyway.

Getting Java version at runtime

If you can have dependency to apache utils you can use org.apache.commons.lang3.SystemUtils.

    System.out.println("Is Java version at least 1.8: " + SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8));

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

javascript multiple OR conditions in IF statement

When it checks id!=2 it returns true and stops further checking

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

How to validate an OAuth 2.0 access token for a resource server?

OAuth 2.0 spec doesn't define the part. But there could be couple of options:

  1. When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.

  2. Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR can be comma delimited list of IPs
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED

I found the code on the following site useful:
http://www.grantburton.com/?p=97

How to SFTP with PHP?

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already:

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

Accessing Google Spreadsheets with C# using Google Data API

http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!

When and Why to use abstract classes/methods?

read the following article http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

add class with JavaScript

document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

var buttons = document.getElementsByClassName("navButton");

for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.setAttribute("class", "active");
        this.setAttribute("src", "images/arrows/top_o.png");
    }
}

Stretch horizontal ul to fit width of div

inelegant (but effective) way: use percentages

#horizontal-style {
    width: 100%;
}

li {
    width: 20%;
}

This only works with the 5 <li> example. For more or less, modify your percentage accordingly. If you have other <li>s on your page, you can always assign these particular ones a class of "menu-li" so that only they are affected.

The SQL OVER() clause - when and why is it useful?

prkey   whatsthat               cash   
890    "abb                "   32  32
43     "abbz               "   2   34
4      "bttu               "   1   35
45     "gasstuff           "   2   37
545    "gasz               "   5   42
80009  "hoo                "   9   51
2321   "ibm                "   1   52
998    "krk                "   2   54
42     "kx-5010            "   2   56
32     "lto                "   4   60
543    "mp                 "   5   65
465    "multipower         "   2   67
455    "O.N.               "   1   68
7887   "prem               "   7   75
434    "puma               "   3   78
23     "retractble         "   3   81
242    "Trujillo's stuff   "   4   85

That's a result of query. Table used as source is the same exept that it has no last column. This column is a moving sum of third one.

Query:

SELECT prkey,whatsthat,cash,SUM(cash) over (order by whatsthat)
    FROM public.iuk order by whatsthat,prkey
    ;

(table goes as public.iuk)

sql version:  2012

It's a little over dbase(1986) level, I don't know why 25+ years has been needed to finish it up.

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

Unable to establish SSL connection, how do I fix my SSL cert?

For me a DNS name of my server was added to /etc/hosts and it was mapped to 127.0.0.1 which resulted in

SL23_GET_SERVER_HELLO:unknown protocol

Removing mapping of my real DNS name to 127.0.0.1 resolved the problem.

Blurring an image via CSS?

With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.

See the following code for more details.

To make an image gray:

img {
 -webkit-filter: grayscale(100%);
}

To give a sepia look:

img {
 -webkit-filter: sepia(100%);
}

To adjust brightness:

img {
 -webkit-filter: brightness(50%);
}

To adjust contrast:

img {
 -webkit-filter: contrast(200%);
}

To Blur an image:

img {
 -webkit-filter: blur(10px);
}

You should also do it for different browser. That is include all css statements

  filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
 -moz-filter: grayscale(100%);

To use multiple

 filter: blur(5px) grayscale(1);

Codepen Demo

how to install gcc on windows 7 machine?

Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.

Get table column names in MySQL?

How about this:

SELECT @cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

SET @cCommand = CONCAT( 'SELECT ', @cCommand, ' from my_database.my_table;');
PREPARE xCommand from @cCommand;
EXECUTE xCommand;

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

How to put a jar in classpath in Eclipse?

First copy your jar file and paste into you Android project's libs folder.

Now right click on newly added (Pasted) jar file and select option

Build Path -> Add to build path

Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option

Build Path -> Configure Build path

A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.

Now run your project.

More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)

how to get the base url in javascript

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


Further reading is available on this Stack Overflow thread

How to lock orientation of one view controller to portrait mode only in Swift

For a new version of Swift try this

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

Labels for radio buttons in rails form

Using true/false as the value will have the field pre-filled if the model passed to the form has this attribute already filled:

= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)

how to zip a folder itself using java

Enhanced Java 8+ example (Forked from Nikita Koksharov's answer)

public static void pack(String sourceDirPath, String zipFilePath) throws IOException {
    Path p = Files.createFile(Paths.get(zipFilePath));
    Path pp = Paths.get(sourceDirPath);
    try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p));
        Stream<Path> paths = Files.walk(pp)) {
        paths
          .filter(path -> !Files.isDirectory(path))
          .forEach(path -> {
              ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
              try {
                  zs.putNextEntry(zipEntry);
                  Files.copy(path, zs);
                  zs.closeEntry();
            } catch (IOException e) {
                System.err.println(e);
            }
          });
    }
}

Files.walk has been wrapped in try with resources block so that stream can be closed. This resolves blocker issue identified by SonarQube. Thanks @Matt Harrison for pointing this.

NSString with \n or line break

If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0

myView.numberOfLines=0;

Multiple left-hand assignment with JavaScript

Actually,

var var1 = 1, var2 = 1, var3 = 1;

is not equivalent to:

var var1 = var2 = var3 = 1;

The difference is in scoping:

_x000D_
_x000D_
function good() {_x000D_
  var var1 = 1, var2 = 1, var3 = 1;_x000D_
}_x000D_
_x000D_
function bad() {_x000D_
  var var1 = var2 = var3 = 1;_x000D_
}_x000D_
_x000D_
good();_x000D_
console.log(window.var2); // undefined_x000D_
_x000D_
bad();_x000D_
console.log(window.var2); // 1. Aggh!
_x000D_
_x000D_
_x000D_

Actually this shows that assignment are right associative. The bad example is equivalent to:

var var1 = (window.var2 = (window.var3 = 1));

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Swift 3 Bonus: Why didn't anyone mention the short form?

CGRect(origin: .zero, size: size)

.zero instead of CGPoint.zero

When the type is defined, you can safely omit it.

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

converting drawable resource image into bitmap

You probably mean Notification.Builder.setLargeIcon(Bitmap), right? :)

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);

This is a great method of converting resource images into Android Bitmaps.

Add User to Role ASP.NET Identity

Below is an alternative implementation of a 'create user' controller method using Claims based roles.

The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]

    // POST api/User/Create
    [Route("Create")]
    public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Generate long password for the user
        var password = System.Web.Security.Membership.GeneratePassword(25, 5);

        // Create the user
        var user = new ApiUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, password);
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        // Add roles (permissions) for the user
        foreach (var perm in model.Permissions)
        {
            await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
        }

        return Ok<object>(new { UserName = user.UserName, Password = password });
    }

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

Disabling and enabling a html input button

 <!--Button Disable Script-->
    <script type="text/javascript">
        function DisableButton() {
            document.getElementById("<%=btnSave.ClientID %>").disabled = true;
        }
        window.onbeforeunload = DisableButton;
    </script>
    <!--Button Disable Script-->

How do I execute external program within C code in linux with arguments?

In C

#include <stdlib.h>

system("./foo 1 2 3");

In C++

#include <cstdlib>

std::system("./foo 1 2 3");

Then open and read the file as usual.

Difference Between Schema / Database in MySQL

Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.

How to get on scroll events?

Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

window:scroll

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {

}

or

<div (window:scroll)="onWindowScroll($event)">

scroll

@HostListener('scroll', ['$event'])
onElementScroll($event) {

}

or

<div (scroll)="onElementScroll($event)">

@HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

Examples

Angular: Can't find Promise, Map, Set and Iterator

Another Possible solution is to reinstall typings:
This works for me for "angular2": "2.0.0-beta.15"

  1. npm clean cache
  2. npm install
  3. npm install -g typings
  4. Delete typings directory from project (Directory wwhere typings modules are installed)
  5. typings install
  6. npm run

How to refer environment variable in POM.xml?

I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.

Using ${env.foo} or ${env.FOO} didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:

  1. Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh to call it from the parent script.

  2. In shared-pom, create a command-line param that grabs the environment variable:

<plugin>
  ...
  <executions>
    <executions>
    ...
      <execution>
      ...
        <configuration>
          <param>${foo}</param> <!-- Note this is *not* ${env.foo} -->
        </configuration>
  1. In com.google.code.maven-replacer-plugin, make the replacement value ${foo}.

  2. In my shell script that calls maven, add this to the command: -Dfoo=$foo

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

How to get a random number in Ruby

Use rand(range)

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

Git - remote: Repository not found

You can try deleting the .git file in the directory and doing everything again will fix your problem!

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

Argument Exception "Item with Same Key has already been added"

As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):

// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];

Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string> for each string key.

For example:

var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();

foreach (string line in rct3Lines)
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        // No items for this key have been added, so create a new list
        // for the value with item[1] as the only item in the list
        rct3Features.Add(items[0], new List<string> { items[1] });
    }
    else
    {
        // This key already exists, so add item[1] to the existing list value
        rct3Features[items[0]].Add(items[1]);
    }
}

// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
    Console.WriteLine("The Key: {0} has values:", item.Key);
    foreach (string value in item.Value)
    {
        Console.WriteLine(" - {0}", value);
    }
}

how to enable sqlite3 for php?

one thing I want to add , before you try to install

apt-get install php5-sqlite

or

apt-get install php5-sqlite3 

search the given package is available or not :-

 # apt-cache search 'php5'

After that you get :-

php5-rrd - rrd module for PHP 5

php5-sasl - Cyrus SASL extension for PHP 5

php5-snmp - SNMP module for php5

**php5-sqlite - SQLite module for php5**

php5-svn - PHP Bindings for the Subversion Revision control system

php5-sybase - Sybase / MS SQL Server module for php5

Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install

**apt-get install php5-sqlite**

Is it possible to opt-out of dark mode on iOS 13?

Just simply add following key in your info.plist file :

<key>UIUserInterfaceStyle</key>
    <string>Light</string>

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

Set new id with jQuery

I just wrote a quick plugin to run a test using your same snippet and it works fine

$.fn.test = function() {
      return this.each(function(){
        var new_id = 5;
        $(this).attr('id',   this.id + '_' + new_id);
        $(this).attr('name', this.name + '_' + new_id);
        $(this).attr('value', 'test');
      });
    };

$(document).ready(function() {
    $('#field_id').test()
});

<body>
  <div id="container">

  <input type="text" name="field_name" id="field_id" value="meh" />
  </div>
</body>

So I can only presume something else is going on in your code. Can you provide some more details?

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

How to get the device's IMEI/ESN programmatically in android?

I use the following code to get the IMEI or use Secure.ANDROID_ID as an alternative, when the device doesn't have phone capabilities:

/**
 * Returns the unique identifier for the device
 *
 * @return unique identifier for the device
 */
public String getDeviceIMEI() {
    String deviceUniqueIdentifier = null;
    TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    if (null != tm) {
        deviceUniqueIdentifier = tm.getDeviceId();
    }
    if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
        deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    return deviceUniqueIdentifier;
}

How to send a model in jQuery $.ajax() post request to MVC controller method

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

Count number of days between two dates

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

checking if number entered is a digit in jquery

Following script can be used to check whether value is valid integer or not.

  function myFunction() {
    var a = parseInt("10000000");
    if (!isNaN(a) && a <= 2147483647 && a >= -2147483647){
    alert("is integer"); 
    } else {
     alert("not integer"); 
    }
}

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

is there something like isset of php in javascript/jQuery?

http://phpjs.org/functions/isset:454

phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.

How do you pull first 100 characters of a string in PHP

$x = '1234567';

echo substr ($x, 0, 3);  // outputs 123

echo substr ($x, 1, 1);  // outputs 2

echo substr ($x, -2);    // outputs 67

echo substr ($x, 1);     // outputs 234567

echo substr ($x, -2, 1); // outputs 6

How to scroll to bottom in a ScrollView on activity startup

Try this

    final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
    scrollview.post(new Runnable() {
       @Override
       public void run() {
         scrollview.fullScroll(ScrollView.FOCUS_DOWN);
       }
    });

HowTo Generate List of SQL Server Jobs and their owners

There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:

Run the script in your PowerShell ISE:

Loads SQL Powerhell SMO and commands:

Import-Module SQLPS -disablenamechecking

BUild list of Servers manually (this builds an array list):

$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
    ## - Add Code block:
    $MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
    DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto 
    ## - End of Code block
}

How to set Default Controller in asp.net MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

How to set the height of table header in UITableView?

If you programatically set the tableHeaderView, then just set it inside viewDidLayoutSubviews.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        setupTableViewHeader()
    }

    private func setupTableViewHeader() {
        // Something you do to set it up programatically...
        tableView.tableHeaderView = MyHeaderView.instanceFromNib() 
    }

If you didn't set it programatically, you need to do similar to what @Kris answered based on this link

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        sizeHeaderToFit()
    }

    private func sizeHeaderToFit() {
        if let headerView = tableView.tableHeaderView {
            headerView.setNeedsLayout()
            headerView.layoutIfNeeded()

            let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            var frame = headerView.frame
            frame.size.height = height
            headerView.frame = frame

            tableView.tableHeaderView = headerView
        }
    }

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

Equivalent of LIMIT for DB2

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
  FROM EMP
  ORDER BY SALARY DESC
  FETCH FIRST 20 ROWS ONLY;

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address
FROM ( 
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

Convert System.Drawing.Color to RGB and Hex Value

I found an extension method that works quite well

public static string ToHex(this Color color)
{
    return String.Format("#{0}{1}{2}{3}"
        , color.A.ToString("X").Length == 1 ? String.Format("0{0}", color.A.ToString("X")) : color.A.ToString("X")
        , color.R.ToString("X").Length == 1 ? String.Format("0{0}", color.R.ToString("X")) : color.R.ToString("X")
        , color.G.ToString("X").Length == 1 ? String.Format("0{0}", color.G.ToString("X")) : color.G.ToString("X")
        , color.B.ToString("X").Length == 1 ? String.Format("0{0}", color.B.ToString("X")) : color.B.ToString("X"));
}

Ref: https://social.msdn.microsoft.com/Forums/en-US/4c77ba6c-6659-4a46-920a-7261dd4a15d0/how-to-convert-rgba-value-into-its-equivalent-hex-code?forum=winappswithcsharp

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

eclipse stuck when building workspace

In case there is a problem on start when building your project disable the build automatically from menu. Project -> Build Automatically. This solved my problem while more sophisticated solutions could not.

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

how to get files from <input type='file' .../> (Indirect) with javascript

If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

See this MDN article for more info on the FileList type.

Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files property in non-File API browsers.

What does -1 mean in numpy reshape?

numpy.reshape(a,newshape,order{})

check the below link for more info. https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

for the below example you mentioned the output explains the resultant vector to be a single row.(-1) indicates the number of rows to be 1. if the

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

output:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

this can be explained more precisely with another example:

b = np.arange(10).reshape((-1,1))

output:(is a 1 dimensional columnar array)

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

or

b = np.arange(10).reshape((1,-1))

output:(is a 1 dimensional row array)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

Where can I find a list of escape characters required for my JSON ajax return type?

The JSON reference states:

 any-Unicode-character-
     except-"-or-\\-or-
     control-character

Then lists the standard escape codes:

  \" Standard JSON quote
  \\ Backslash (Escape char)
  \/ Forward slash
  \b Backspace (ascii code 08)
  \f Form feed (ascii code 0C)
  \n Newline
  \r Carriage return
  \t Horizontal Tab
  \u four-hex-digits

From this I assumed that I needed to escape all the listed ones and all the other ones are optional. You can choose to encode all characters into \uXXXX if you so wished, or you could only do any non-printable 7-bit ASCII characters or characters with Unicode value not in \u0020 <= x <= \u007E range (32 - 126). Preferably do the standard characters first for shorter escape codes and thus better readability and performance.

Additionally you can read point 2.5 (Strings) from RFC 4627.

You may (or may not) want to (further) escape other characters depending on where you embed that JSON string, but that is outside the scope of this question.

How to iterate through a String

Java Strings aren't character Iterable. You'll need:

for (int i = 0; i < examplestring.length(); i++) {
  char c = examplestring.charAt(i);
  ...
}

Awkward I know.

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

How to add a tooltip to an svg graphic?

You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/