Programs & Examples On #Quickfix

QuickFIX is an open source implementation of FIX protocol, currently compatible with the FIX 4.0-5.0 specifications.

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

How to set selected value from Combobox?

I suspect something is not right when you are saving to the db. Do i understand your steps as:

  1. populate and bind
  2. user selects and item, hit and save.. then you save in the db
  3. now if you select another item it won't select?

got more code, especially when saving? where in your code are initializing and populating the bindinglist

How to make the Facebook Like Box responsive?

NOTE: this answer is obsolete. See the community wiki answer below for an up-to-date solution.


I found this Gist today and it works perfectly: https://gist.github.com/2571173

(Many thanks to https://gist.github.com/smeranda)

/* 
Make the Facebook Like box responsive (fluid width)
https://developers.facebook.com/docs/reference/plugins/like-box/ 
*/

/* 
This element holds injected scripts inside iframes that in 
some cases may stretch layouts. So, we're just hiding it. 
*/

#fb-root {
    display: none;
}

/* To fill the container and nothing else */

.fb_iframe_widget, .fb_iframe_widget span, .fb_iframe_widget span iframe[style] {
    width: 100% !important;
}

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

How to get the range of occupied cells in excel sheet

Bit old question now, but if somebody is looking for solution this works for me.

using Excel = Microsoft.Office.Interop.Excel;

Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Application app = excel.Application;
Excel.Range all = app.get_Range("A1:H10", Type.Missing);

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Add the Jenkinsfile where the pom.xml file has present. Provide the directory path on dir('project-dir'),

Ex:

node {

    withMaven(maven:'maven') {

        stage('Checkout') {
            git url: 'http://xxxxxxx/gitlab/root/XXX.git', credentialsId: 'xxxxx', branch: 'xxx'
        }

        stage('Build') {

            **dir('project-dir') {**
                sh 'mvn clean install'

                def pom = readMavenPom file:'pom.xml'

                print pom.version
                env.version = pom.version
            }
        }
    }
}

How do you declare an interface in C++?

The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance.

C++ supports multiple inheritance, and so a special type isn't needed. An abstract base class with no non-abstract (pure virtual) methods is functionally equivalent to a C#/Java interface.

Cannot connect to MySQL 4.1+ using old authentication

edit: This only applies if you are in control of the MySQL server... if you're not take a look at Mysql password hashing method old vs new

First check with the SQL query

SHOW VARIABLES LIKE 'old_passwords'

(in the MySQL command line client, HeidiSQL or whatever front end you like) whether the server is set to use the old password schema by default. If this returns old_passwords,Off you just happen to have old password entries in the user table. The MySQL server will use the old authentication routine for these accounts. You can simply set a new password for the account and the new routine will be used.

You can check which routine will be used by taking a look at the mysql.user table (with an account that has access to that table)

SELECT `User`, `Host`, Length(`Password`) FROM mysql.user

This will return 16 for accounts with old passwords and 41 for accounts with new passwords (and 0 for accounts with no password at all, you might want to take care of those as well).
Either use the user management tools of the MySQL front end (if there are any) or

SET PASSWORD FOR 'User'@'Host'=PASSWORD('yourpassword');
FLUSH Privileges;

(replace User and Host with the values you got from the previous query.) Then check the length of the password again. It should be 41 now and your client (e.g. mysqlnd) should be able to connect to the server.

see also the MySQL documentation: * http://dev.mysql.com/doc/refman/5.0/en/old-client.html
* http://dev.mysql.com/doc/refman/5.0/en/password-hashing.html
* http://dev.mysql.com/doc/refman/5.0/en/set-password.html

How do I migrate an SVN repository with history to a new Git repository?

Here is a simple shell script with no dependencies that will convert one or more SVN repositories to git and push them to GitHub.

https://gist.github.com/NathanSweet/7327535

In about 30 lines of script it: clones using git SVN, creates a .gitignore file from SVN::ignore properties, pushes into a bare git repository, renames SVN trunk to master, converts SVN tags to git tags, and pushes it to GitHub while preserving the tags.

I went thru a lot of pain to move a dozen SVN repositories from Google Code to GitHub. It didn't help that I used Windows. Ruby was all kinds of broken on my old Debian box and getting it working on Windows was a joke. Other solutions failed to work with Cygwin paths. Even once I got something working, I couldn't figure out how to get the tags to show up on GitHub (the secret is --follow-tags).

In the end I cobbled together two short and simple scripts, linked above, and it works great. The solution does not need to be any more complicated than that!

Python "extend" for a dictionary

Have you tried using dictionary comprehension with dictionary mapping:

a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}

c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}

Another way of doing is by Using dict(iterable, **kwarg)

c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.9 you can add two dict using union | operator

# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Is this going to put people off coming to Scala?

I don't think it is the main factor that will affect how popular Scala will become, because Scala has a lot of power and its syntax is not as foreign to a Java/C++/PHP programmer as Haskell, OCaml, SML, Lisps, etc..

But I do think Scala's popularity will plateau at less than where Java is today, because I also think the next mainstream language must be much simplified, and the only way I see to get there is pure immutability, i.e. declarative like HTML, but Turing complete. However, I am biased because I am developing such a language, but I only did so after ruling out over a several month study that Scala could not suffice for what I needed.

Is this going to give Scala a bad name in the commercial world as an academic plaything that only dedicated PhD students can understand? Are CTOs and heads of software going to get scared off?

I don't think Scala's reputation will suffer from the Haskell complex. But I think that some will put off learning it, because for most programmers, I don't yet see a use case that forces them to use Scala, and they will procrastinate learning about it. Perhaps the highly-scalable server side is the most compelling use case.

And, for the mainstream market, first learning Scala is not a "breath of fresh air", where one is writing programs immediately, such as first using HTML or Python. Scala tends to grow on you, after one learns all the details that one stumbles on from the start. However, maybe if I had read Programming in Scala from the start, my experience and opinion of the learning curve would have been different.

Was the library re-design a sensible idea?

Definitely.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I am using Scala as the initial platform of my new language. I probably wouldn't be building code on Scala's collection library if I was using Scala commercially otherwise. I would create my own category theory based library, since the one time I looked, I found Scalaz's type signatures even more verbose and unwieldy than Scala's collection library. Part of that problem perhaps is Scala's way of implementing type classes, and that is a minor reason I am creating my own language.


I decided to write this answer, because I wanted to force myself to research and compare Scala's collection class design to the one I am doing for my language. Might as well share my thought process.

The 2.8 Scala collections use of a builder abstraction is a sound design principle. I want to explore two design tradeoffs below.

  1. WRITE-ONLY CODE: After writing this section, I read Carl Smotricz's comment which agrees with what I expect to be the tradeoff. James Strachan and davetron5000's comments concur that the meaning of That (it is not even That[B]) and the mechanism of the implicit is not easy to grasp intuitively. See my use of monoid in issue #2 below, which I think is much more explicit. Derek Mahar's comment is about writing Scala, but what about reading the Scala of others that is not "in the common cases".

    One criticism I have read about Scala, is that it is easier to write it, than read the code that others have written. And I find this to be occasionally true for various reasons (e.g. many ways to write a function, automatic closures, Unit for DSLs, etc), but I am undecided if this is major factor. Here the use of implicit function parameters has pluses and minuses. On the plus side, it reduces verbosity and automates selection of the builder object. In Odersky's example the conversion from a BitSet, i.e. Set[Int], to a Set[String] is implicit. The unfamiliar reader of the code might not readily know what the type of collection is, unless they can reason well about the all the potential invisible implicit builder candidates which might exist in the current package scope. Of course, the experienced programmer and the writer of the code will know that BitSet is limited to Int, thus a map to String has to convert to a different collection type. But which collection type? It isn't specified explicitly.

  2. AD-HOC COLLECTION DESIGN: After writing this section, I read Tony Morris's comment and realized I am making nearly the same point. Perhaps my more verbose exposition will make the point more clear.

    In "Fighting Bit Rot with Types" Odersky & Moors, two use cases are presented. They are the restriction of BitSet to Int elements, and Map to pair tuple elements, and are provided as the reason that the general element mapping function, A => B, must be able to build alternative destination collection types. However, afaik this is flawed from a category theory perspective. To be consistent in category theory and thus avoid corner cases, these collection types are functors, in which each morphism, A => B, must map between objects in the same functor category, List[A] => List[B], BitSet[A] => BitSet[B]. For example, an Option is a functor that can be viewed as a collection of sets of one Some( object ) and the None. There is no general map from Option's None, or List's Nil, to other functors which don't have an "empty" state.

    There is a tradeoff design choice made here. In the design for collections library of my new language, I chose to make everything a functor, which means if I implement a BitSet, it needs to support all element types, by using a non-bit field internal representation when presented with a non-integer type parameter, and that functionality is already in the Set which it inherits from in Scala. And Map in my design needs to map only its values, and it can provide a separate non-functor method for mapping its (key,value) pair tuples. One advantage is that each functor is then usually also an applicative and perhaps a monad too. Thus all functions between element types, e.g. A => B => C => D => ..., are automatically lifted to the functions between lifted applicative types, e.g. List[A] => List[B] => List[C] => List[D] => .... For mapping from a functor to another collection class, I offer a map overload which takes a monoid, e.g. Nil, None, 0, "", Array(), etc.. So the builder abstraction function is the append method of a monoid and is supplied explicitly as a necessary input parameter, thus with no invisible implicit conversions. (Tangent: this input parameter also enables appending to non-empty monoids, which Scala's map design can't do.) Such conversions are a map and a fold in the same iteration pass. Also I provide a traversable, in the category sense, "Applicative programming with effects" McBride & Patterson, which also enables map + fold in a single iteration pass from any traversable to any applicative, where most every collection class is both. Also the state monad is an applicative and thus is a fully generalized builder abstraction from any traversable.

    So afaics the Scala collections is "ad-hoc" in the sense that it is not grounded in category theory, and category theory is the essense of higher-level denotational semantics. Although Scala's implicit builders are at first appearance "more generalized" than a functor model + monoid builder + traversable -> applicative, they are afaik not proven to be consistent with any category, and thus we don't know what rules they follow in the most general sense and what the corner cases will be given they may not obey any category model. It is simply not true that adding more variables makes something more general, and this was one of huge benefits of category theory is it provides rules by which to maintain generality while lifting to higher-level semantics. A collection is a category.

    I read somewhere, I think it was Odersky, as another justification for the library design, is that programming in a pure functional style has the cost of limited recursion and speed where tail recursion isn't used. I haven't found it difficult to employ tail recursion in every case that I have encountered so far.


Additionally I am carrying in my mind an incomplete idea that some of Scala's tradeoffs are due to trying to be both an mutable and immutable language, unlike for example Haskell or the language I am developing. This concurs with Tony Morris's comment about for comprehensions. In my language, there are no loops and no mutable constructs. My language will sit on top of Scala (for now) and owes much to it, and this wouldn't be possible if Scala didn't have the general type system and mutability. That might not be true though, because I think Odersky & Moors ("Fighting Bit Rot with Types") are incorrect to state that Scala is the only OOP language with higher-kinds, because I verified (myself and via Bob Harper) that Standard ML has them. Also appears SML's type system may be equivalently flexible (since 1980s), which may not be readily appreciated because the syntax is not so much similar to Java (and C++/PHP) as Scala. In any case, this isn't a criticism of Scala, but rather an attempt to present an incomplete analysis of tradeoffs, which is I hope germane to the question. Scala and SML don't suffer from Haskell's inability to do diamond multiple inheritance, which is critical and I understand is why so many functions in the Haskell Prelude are repeated for different types.

How can I access Google Sheet spreadsheets only with Javascript?

'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:

http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/js.html

http://www.mail-archive.com/[email protected]/msg01924.html

May be these would help you out..

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

JavaScript Nested function

It's perfectly normal in Javascript (and many languages) to have functions inside functions.

Take the time to learn the language, don't use it on the basis that it's similar to what you already know. I'd suggest watching Douglas Crockford's series of YUI presentations on Javascript, with special focus on Act III: Function the Ultimate (link to video download, slides, and transcript)

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your content files to this folder.
  3. Right click on your folder and click on Details.
  4. Copy Hosting URL and paste it on your browser.(e.g. https://googledrive.com/host/0B716ywBKT84AcHZfMWgtNk5aeXM)
  5. It will launch index.html if it exist in your folder other wise list all files in your folder.

What is meant by Ems? (Android TextView)

To add to the other answers in Android, Ems size, can, by default, vary in each language and input.

It means that if you want to set a minimum width to a text field, defined by number of chars, you have to calculate the Ems properly and set it, according to your typeface and font size with the Ems attribute.

To those of you struggle with this, you can calculate the hint size yourself to avoid messing with Ems:

val tf = TextField()
val layout = TextInputLayout()
val hint = "Hint"

val measureText = tf.paint.measureText(hint).toInt()
tf.width = tf.paddingLeft + tf.paddingRight + measureText.toInt()
layout.hint = hint

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Quantile-Quantile Plot using SciPy

I came up with this. Maybe you can improve it. Especially the method of generating the quantiles of the distribution seems cumbersome to me.

You could replace np.random.normal with any other distribution from np.random to compare data against other distributions.

#!/bin/python

import numpy as np

measurements = np.random.normal(loc = 20, scale = 5, size=100000)

def qq_plot(data, sample_size):
    qq = np.ones([sample_size, 2])
    np.random.shuffle(data)
    qq[:, 0] = np.sort(data[0:sample_size])
    qq[:, 1] = np.sort(np.random.normal(size = sample_size))
    return qq

print qq_plot(measurements, 1000)

How can I access my localhost from my Android device?

Another thing to check is that some routers have issues bridging the requests when both 2.4G and 5G are enabled and the devices are on different frequencies. Trying disabling one of the frequencies so both devices are connected to the same interface.

Error message "Strict standards: Only variables should be passed by reference"

The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].

The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift() in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.

Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.

Reproduce code:

function get_arr()
{
    return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);

Is std::vector copying the objects with a push_back?

From C++11 onwards, all the standard containers (std::vector, std::map, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:

// Example object class.
class object
{
private:
    int             m_val1;
    std::string     m_val2;

public:
    // Constructor for object class.
    object(int val1, std::string &&val2) :
        m_val1(val1),
        m_val2(std::move(val2))
    {

    }
};

std::vector<object> myList;

// #1 Copy into the vector.
object foo1(1, "foo");
myList.push_back(foo1);

// #2 Move into the vector (no copy).
object foo2(1024, "bar");
myList.push_back(std::move(foo2));

// #3 Move temporary into vector (no copy).
myList.push_back(object(453, "baz"));

// #4 Create instance of object directly inside the vector (no copy, no move).
myList.emplace_back(453, "qux");

Alternatively you can use various smart pointers to get mostly the same effect:

std::unique_ptr example

std::vector<std::unique_ptr<object>> myPtrList;

// #5a unique_ptr can only ever be moved.
auto pFoo = std::make_unique<object>(1, "foo");
myPtrList.push_back(std::move(pFoo));

// #5b unique_ptr can only ever be moved.
myPtrList.push_back(std::make_unique<object>(1, "foo"));

std::shared_ptr example

std::vector<std::shared_ptr<object>> objectPtrList2;

// #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
// value and the local copy simultaneously.
auto pFooShared = std::make_shared<object>(1, "foo");
objectPtrList2.push_back(pFooShared);
// Pointer to object stored in the vector, but pFooShared is still valid.

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

Escaping HTML strings with jQuery

I've enhanced the mustache.js example adding the escapeHTML() method to the string object.

var __entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

String.prototype.escapeHTML = function() {
    return String(this).replace(/[&<>"'\/]/g, function (s) {
        return __entityMap[s];
    });
}

That way it is quite easy to use "Some <text>, more Text&Text".escapeHTML()

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

Copying files using rsync from remote server to local machine

From your local machine:

rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage

From your local machine with a non standard ssh port:

rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path

Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:

rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage

See man rsync for an explanation of my usual switches.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

I was unsatisfied that until know Google hasn't yet released their new designs as font or svg icon set. Therefore I put together a small npm package to solve the problem.

https://www.npmjs.com/package/ts-material-icons-svg

Simply import the icons you wanna use and add them to your registry. This also supports tree shaking since only those icons are added to your project that you really want and/or need.

npm i --save https://github.com/MarcusCalidus/ts-material-icons-svg.git

to use two tone icons for example

import {icon_edit} from 'ts-material-icons-svg/dist/twotone';

matIconRegistry.addSvgIcon(
            'edit',
            domSanitizer.bypassSecurityTrustResourceUrl(icon_edit),
        );

In your html template you now can use the new icon

<mat-icon svgIcon="edit"></mat-icon>

How to disable 'X-Frame-Options' response header in Spring Security?

Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN. If you are using the Java Configs (Spring Boot) and would like to allow the X-Frame-Options: SAMEORIGIN, then you would need to use the following.


For older Spring Security versions:

http
   .headers()
       .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))

For newer versions like Spring Security 4.0.2:

http
   .headers()
      .frameOptions()
         .sameOrigin();

How to install mongoDB on windows?

Update Nov -2017

1) Go to Mongo DB download center https://www.mongodb.com/download-center#community and pick a flavor of MongoDB you want to install. You can pick from

  • MongoDB Atlas - MongoDB database in the cloud
  • Communiy Server - MongoDb for windows (with and without SSL),iOS, Linux
  • OpManger- Mongo Db for Data Center
  • Compass - UI tool for MongoDB

To know your OS version run this command in cmd prompt

wmic os get caption

To know your CPU architecture(32 or 64 bit) run this command in cmd prompt

wmic os get osarchitecture

I am using Community version (150MBs- GNU license)

2) Click on MSI and go through installation Process. Exe will install MongoDb and SSL required by the DB.

enter image description here

Mongo DB should be installed on your C drive

C:\Program Files\MongoDB

MongoDB is self-contained, it means and does not have any other system dependencies. If you are low on disk in C drive then you can run MongoDB from any folder you choose.

You can now run mongodb.exe from bin folder. If you get Visual C++ error for missing dlls then download Visual C++ Redistributable from

https://www.microsoft.com/en-in/download/details.aspx?id=48145

After installation, try to rerun mongo.exe.

Send POST request using NSURLSession

If you are using Swift, the Just library does this for you. Example from it's readme file:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

SQL how to make null values come last when sorting ascending

order by coalesce(date-time-field,large date in future)

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...

Update: The page states that the tight_layout() function is the easiest way to go, which attempts to automatically correct spacing.

Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

Bulk Insert Correctly Quoted CSV File in SQL Server

You could also look at using OpenRowSet with the CSV text file data provider.

This should be possible with any version of SQL Server >= 2005 although you need to enable the feature.

http://social.msdn.microsoft.com/forums/en-US/sqldataaccess/thread/5869d247-f0a0-4224-80b3-ff2e414be402

What is the difference between `new Object()` and object literal notation?

Memory usage is different if you create 10 thousand instances. new Object() will only keep only one copy while {} will keep 10 thousand copies.

[Vue warn]: Property or method is not defined on the instance but referenced during render

In my case the reason was, I only forgot the closing

</script>

tag.

But that caused the same error message.

Copy a git repo without history

Use the following command:

git clone --depth <depth> -b <branch> <repo_url>

Where:

  • depth is the amount of commits you want to include. i.e. if you just want the latest commit use git clone --depth 1
  • branch is the name of the remote branch that you want to clone from. i.e. if you want the last 3 commits from master branch use git clone --depth 3 -b master
  • repo_url is the url of your repository

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

notifyDataSetChanged not working on RecyclerView

I had same problem. I just solved it with declaring adapter public before onCreate of class.

PostAdapter postAdapter;

after that

postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);

at last I have called:

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    // Display the size of your ArrayList
    Log.i("TAG", "Size : " + posts.size());
    progressBar.setVisibility(View.GONE);
    postAdapter.notifyDataSetChanged();
}

May this will helps you.

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first version is preferable:

  • It works for all kinds of keys, so you can, for example, say {1: 'one', 2: 'two'}. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency.
  • It is faster:

    $ python -m timeit "dict(a='value', another='value')"
    1000000 loops, best of 3: 0.79 usec per loop
    $ python -m timeit "{'a': 'value','another': 'value'}"
    1000000 loops, best of 3: 0.305 usec per loop
    
  • If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.

Consistency of hashCode() on a Java string

I found something about JDK 1.0 and 1.1 and >= 1.2:

In JDK 1.0.x and 1.1.x the hashCode function for long Strings worked by sampling every nth character. This pretty well guaranteed you would have many Strings hashing to the same value, thus slowing down Hashtable lookup. In JDK 1.2 the function has been improved to multiply the result so far by 31 then add the next character in sequence. This is a little slower, but is much better at avoiding collisions. Source: http://mindprod.com/jgloss/hashcode.html

Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all...

MySQL: Error dropping database (errno 13; errno 17; errno 39)

As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:

rm -f /var/lib/mysql/<database_name>/

And then drop the database from your tool of choice or using the command:

DROP DATABASE <database_name>

How do I determine the size of an object in Python?

Having run into this problem many times myself, I wrote up a small function (inspired by @aaron-hall's answer) & tests that does what I would have expected sys.getsizeof to do:

https://github.com/bosswissam/pysize

If you're interested in the backstory, here it is

EDIT: Attaching the code below for easy reference. To see the most up-to-date code, please check the github link.

    import sys

    def get_size(obj, seen=None):
        """Recursively finds size of objects"""
        size = sys.getsizeof(obj)
        if seen is None:
            seen = set()
        obj_id = id(obj)
        if obj_id in seen:
            return 0
        # Important mark as seen *before* entering recursion to gracefully handle
        # self-referential objects
        seen.add(obj_id)
        if isinstance(obj, dict):
            size += sum([get_size(v, seen) for v in obj.values()])
            size += sum([get_size(k, seen) for k in obj.keys()])
        elif hasattr(obj, '__dict__'):
            size += get_size(obj.__dict__, seen)
        elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
            size += sum([get_size(i, seen) for i in obj])
        return size

Test method is inconclusive: Test wasn't run. Error?

My solution:

NUnit 3.2.0 has some issues with Resharper - downgrade to 2.6.4:

update-package nunit -version 2.6.4

Best way to read a large file into a byte array in C#?

use this:

 bytesRead = responseStream.ReadAsync(buffer, 0, Length).Result;

How do I clear my Jenkins/Hudson build history?

Use the script console (Manage Jenkins > Script Console) and something like this script to bulk delete a job's build history https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/bulkDeleteBuilds.groovy

That script assumes you want to only delete a range of builds. To delete all builds for a given job, use this (tested):

// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)

job.getBuilds().each { it.delete() }
// uncomment these lines to reset the build number to 1:
//job.nextBuildNumber = 1
//job.save()

Angular 2 Sibling Component Communication

I have been passing down setter methods from the parent to one of its children through a binding, calling that method with the data from the child component, meaning that the parent component is updated and can then update its second child component with the new data. It does require binding 'this' or using an arrow function though.

This has the benefit that the children aren't so coupled to each other as they don't need a specific shared service.

I am not entirely sure that this is best practice, would be interesting to hear others views on this.

What are the undocumented features and limitations of the Windows FINDSTR command?

FINDSTR has a color bug that I described and solved at https://superuser.com/questions/1535810/is-there-a-better-way-to-mitigate-this-obscure-color-bug-when-piping-to-findstr/1538802?noredirect=1#comment2339443_1538802

To summarize that thread, the bug is that if input is piped to FINDSTR within a parenthesized block of code, inline ANSI escape colorcodes stop working in commands executed later. An example of inline colorcodes is: echo %magenta%Alert: Something bad happened%yellow% (where magenta and yellow are vars defined earlier in the .bat file as the corresponding ANSI escape colorcodes).

My initial solution was to call a do-nothing subroutine after the FINDSTR. Somehow the call or the return "resets" whatever needs to be reset.

Later I discovered another solution that presumably is more efficient: place the FINDSTR phrase within parentheses, as in the following example: echo success | ( FINDSTR /R success ) Placing the FINDSTR phrase within a nested block of code appears to isolate FINDSTR's colorcode bug so it won't affect what's outside the nested block. Perhaps this technique will solve some other undesired FINDSTR side effects too.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.

Create parameterized VIEW in SQL Server 2008

As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.

(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)

Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.

Reverting to a previous revision using TortoiseSVN

I have used the same instructions Stefan used, taken from Tortoise website.

But it's important to click COMMIT right after. I was getting crazy until I realized that.

If you need to make an older revision your head revision do the following:

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

  3. Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

  4. Make a commit.

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

Valid characters in a Java class name

Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:

http://www.oracle.com/technetwork/java/codeconventions-135099.html

nodejs vs node on ubuntu 12.04

It's optional to remove the existing node and nodejs, but have to do alternatively install the latest 7.x nodejs.

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs

Setting timezone in Python

Be aware that running

import os
os.system("tzutil /s \"Central Standard Time\"");

will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()

which will only set in the current environment time (in Unix only)

Using sed, how do you print the first 'N' characters of a line?

colrm x

For example, if you need the first 100 characters:

cat file |colrm 101 

It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm.

Inherit CSS class

You don't need to add extra two classes (button button-primary), you just use the child class (button-primary) with css and it will apply parent as well as child css class. Here is the link:

CSS-Inheritance

Thanks to Jacob Lichner!

Iterating over a numpy array

If you only need the indices, you could try numpy.ndindex:

>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;
}

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

http://jsfiddle.net/weaversnap/7FqsX/1/

Remove the first character of a string

Just do this:

r = "hello"
r = r[1:]
print(r) # ello

How to correctly dismiss a DialogFragment?

I gave an upvote to Terel's answer. I just wanted to post this for any Kotlin users:

supportFragmentManager.findFragmentByTag(TAG_DIALOG)?.let {
    (it as DialogFragment).dismiss()
}

CSS3 Spin Animation

You haven't specified any keyframes. I made it work here.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation: spin 4s infinite linear;
}

@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

You can actually do lots of really cool stuff with this. Here is one I made earlier.

:)

N.B. You can skip having to write out all the prefixes if you use -prefix-free.

Best way to do nested case statement logic in SQL Server

Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression

select  datediff(dd,Invdate,'2009/01/31')+1 as DaysOld, 
    case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
        case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else 
            case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else 
                case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else 
                    case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else 
                        case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end 
                    end
                end
            end
        end
    end as Bucket
from rm20090131atb

Just make sure you have an end statement for every case statement

Updating GUI (WPF) using a different thread

You can use Dispatcher.Invoke to update your GUI from a secondary thread.

Here is an example:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
    }
    public void DoSomething()
    {
        for (int i = 0; i < 100000000; i++)
        {
               this.Dispatcher.Invoke(()=>{
               textbox.Text=i.ToString();
               });    
        } 
    }

how to set the background image fit to browser using html

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}

windows batch file rename

I rename in code

echo off

setlocal EnableDelayedExpansion

for %%a in (*.txt) do (
    REM echo %%a
    set x=%%a
    set mes=!x:~17,3!

    if !mes!==JAN (
        set mes=01
    )

    if !mes!==ENE (
        set mes=01
    )

    if !mes!==FEB (
        set mes=02
    )

    if !mes!==MAR (
        set mes=03
    )

    if !mes!==APR (
        set mes=04
    )

    if !mes!==MAY (
        set mes=05
    )

    if !mes!==JUN (
        set mes=06
    )

    if !mes!==JUL (
        set mes=07
    )

    if !mes!==AUG (
        set mes=08
    )

    if !mes!==SEP (
        set mes=09
    )

    if !mes!==OCT (
        set mes=10
    )

    if !mes!==NOV (
        set mes=11
    )

    if !mes!==DEC (
        set mes=12
    )

    ren %%a !x:~20,4!!mes!!x:~15,2!.txt 

    echo !x:~20,4!!mes!!x:~15,2!.txt 

)

Powershell 2 copy-item which creates a folder if doesn't exist

Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

How to query a CLOB column in Oracle

If it's a CLOB why can't we to_char the column and then search normally ?

Create a table

CREATE TABLE MY_TABLE(Id integer PRIMARY KEY, Name varchar2(20), message clob);

Create few records in this table

INSERT INTO MY_TABLE VALUES(1,'Tom','Hi This is Row one');
INSERT INTO MY_TABLE VALUES(2,'Lucy', 'Hi This is Row two');
INSERT INTO MY_TABLE VALUES(3,'Frank', 'Hi This is Row three');
INSERT INTO MY_TABLE VALUES(4,'Jane', 'Hi This is Row four');
INSERT INTO MY_TABLE VALUES(5,'Robert', 'Hi This is Row five');
COMMIT;

Search in the clob column

SELECT * FROM MY_TABLE where to_char(message) like '%e%';

Results

ID   NAME    MESSAGE   
===============================  
1    Tom     Hi This is Row one         
3    Frank   Hi This is Row three
5    Robert  Hi This is Row five

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

In my case finish() executed immediately after a dialog has shown.

Why can't I define a default constructor for a struct in .NET?

You can't define a default constructor because you are using C#.

Structs can have default constructors in .NET, though I don't know of any specific language that supports it.

How To Check If A Key in **kwargs Exists?

You want

if 'errormessage' in kwargs:
    print("found it")

To get the value of errormessage

if 'errormessage' in kwargs:
    print("errormessage equals " + kwargs.get("errormessage"))

In this way, kwargs is just another dict. Your first example, if kwargs['errormessage'], means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError.

Your second example, if errormessage in kwargs:, means "if kwargs contains the element named by "errormessage", and unless "errormessage" is the name of a variable, you'll get a NameError.

I should mention that dictionaries also have a method .get() which accepts a default parameter (itself defaulting to None), so that kwargs.get("errormessage") returns the value if that key exists and None otherwise (similarly kwargs.get("errormessage", 17) does what you might think it does). When you don't care about the difference between the key existing and having None as a value or the key not existing, this can be handy.

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

How to center HTML5 Videos?

I had a similar problem in revamping a web site in Dreamweaver. The site structure is based on a complex set of tables, and this video was in one of the main layout cells. I created a nested table just for the video and then added an align=center attribute to the new table:

<table align=center><tr><td>
    <video width=420 height=236 controls="controls" autoplay="autoplay">
        <source src="video/video.ogv" type='video/ogg; codecs="theora, vorbis"'/>
        <source src="video/video.webm" type='video/webm' >
        <source src="video/video.mp4" type='video/mp4'>
        <p class="sidebar">If video is not visible, your browser does not support HTML5 video</p>
    </video>
</td></tr></table>

Check if string begins with something?

String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};

Remove leading and trailing spaces?

Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.

How can I find out the current route in Rails?

If you are trying to special case something in a view, you can use current_page? as in:

<% if current_page?(:controller => 'users', :action => 'index') %>

...or an action and id...

<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>

...or a named route...

<% if current_page?(users_path) %>

...and

<% if current_page?(user_path(1)) %>

Because current_page? requires both a controller and action, when I care about just the controller I make a current_controller? method in ApplicationController:

  def current_controller?(names)
    names.include?(current_controller)
  end

And use it like this:

<% if current_controller?('users') %>

...which also works with multiple controller names...

<% if current_controller?(['users', 'comments']) %>

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

event.preventDefault() function not working in IE

To disable a keyboard key after IE9, use : e.preventDefault();

To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;

If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :

try {
    e.keyCode = 0;
}catch (e) {}

Here is a full example for IE7/8 only :

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Reference : How to disable keyboard shortcuts in IE7 / IE8

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

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

I know this may be too late for a better answer but a desired perfect solution must be a system like positioner. I mean, when system makes a positioning for an Editor field it places the field just up to the keyboard, so as UI/UX rules it is perfect.

What below code makes is the Android way positioning smoothly. First of all we keep the current scroll point as a reference point. Second thing is to find the best positioning scroll point for an editor, to do this we scroll to top, and then request the editor fields to make the ScrollView component to do the best positioning. Gatcha! We've learned the best position. Now, what we'll do is scroll smoothly from the previous point to the point we've found newly. If you want you may omit smooth scrolling by using scrollTo instead of smoothScrollTo only.

NOTE: The main container ScrollView is a member field named scrollViewSignup, because my example was a signup screen, as you may figure out a lot.

view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(final View view, boolean b) {
            if (b) {
                scrollViewSignup.post(new Runnable() {
                    @Override
                    public void run() {
                        int scrollY = scrollViewSignup.getScrollY();
                        scrollViewSignup.scrollTo(0, 0);
                        final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
                        view.requestRectangleOnScreen(rect, true);

                        int new_scrollY = scrollViewSignup.getScrollY();
                        scrollViewSignup.scrollTo(0, scrollY);
                        scrollViewSignup.smoothScrollTo(0, new_scrollY);
                    }
                });
            }
        }
    });

If you want to use this block for all EditText instances, and quickly integrate it with your screen code. You can simply make a traverser like below. To do this, I've made the main OnFocusChangeListener a member field named focusChangeListenerToScrollEditor, and call it during onCreate as below.

traverseEditTextChildren(scrollViewSignup, focusChangeListenerToScrollEditor);

And the method implementation is as below.

private void traverseEditTextChildren(ViewGroup viewGroup, View.OnFocusChangeListener focusChangeListenerToScrollEditor) {
    int childCount = viewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof EditText)
        {
            ((EditText) view).setOnFocusChangeListener(focusChangeListenerToScrollEditor);
        }
        else if (view instanceof ViewGroup)
        {
            traverseEditTextChildren((ViewGroup) view, focusChangeListenerToScrollEditor);
        }
    }
}

So, what we've done here is making all EditText instance children to call the listener at focus.

To reach this solution, I've checked it out all the solutions here, and generated a new solution for better UI/UX result.

Many thanks to all other answers inspiring me much.

Open new Terminal Tab from command line (Mac OS X)

I added these to my .bash_profile so I can have access to tabname and newtab

tabname() {
  printf "\e]1;$1\a"
}

new_tab() {
  TAB_NAME=$1
  COMMAND=$2
  osascript \
    -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"printf '\\\e]1;$TAB_NAME\\\a'; $COMMAND\" in front window" \
    -e "end tell" > /dev/null
}

So when you're on a particular tab you can just type

tabname "New TabName"

to organize all the open tabs you have. It's much better than getting info on the tab and changing it there.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

firestore: PERMISSION_DENIED: Missing or insufficient permissions

I had this error with Firebase Admin, the solution was configure the Firebase Admin correctly following this link

What HTTP traffic monitor would you recommend for Windows?

I now use CharlesProxy for development, but previously I have used Fiddler

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

AmazonS3 putObject with InputStream length example

Because the original question was never answered, and I had to run into this same problem, the solution for the MD5 problem is that S3 doesn't want the Hex encoded MD5 string we normally think about.

Instead, I had to do this.

// content is a passed in InputStream
byte[] resultByte = DigestUtils.md5(content);
String streamMD5 = new String(Base64.encodeBase64(resultByte));
metaData.setContentMD5(streamMD5);

Essentially what they want for the MD5 value is the Base64 encoded raw MD5 byte-array, not the Hex string. When I switched to this it started working great for me.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

Using Pipes within ngModel on INPUT Elements in Angular

because of two way binding, To prevent error of:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was 
checked.

you can call a function to change model like this:

<input [ngModel]="item.value" 
  (ngModelChange)="getNewValue($event)" name="inputField" type="text" />


import { UseMyPipeToFormatThatValuePipe } from './path';

constructor({
    private UseMyPipeToFormatThatValue: UseMyPipeToFormatThatValuePipe,
})

getNewValue(ev: any): any {
    item.value= this.useMyPipeToFormatThatValue.transform(ev);
}

it'll be good if there is a better solution to prevent this error.

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

What is the perfect counterpart in Python for "while not EOF"

While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --

try:
    line = raw_input()
    ... whatever needs to be done incase of no EOF ...
except EOFError:
    ... whatever needs to be done incase of EOF ...

Example:

$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
  File "<string>", line 1, in <module> 
EOFError: EOF when reading a line

Or press Ctrl-Z at a raw_input() prompt (Windows, Ctrl-Z Linux)

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

How can I turn a JSONArray into a JSONObject?

Code:

List<String> list = new ArrayList<String>();

list.add("a");

JSONArray array = new JSONArray();

for (int i = 0; i < list.size(); i++) {
    array.put(list.get(i));
}
JSONObject obj = new JSONObject();

try {
    obj.put("result", array);
} catch (JSONException e) {
    e.printStackTrace();
}

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Selenium WebDriver and DropDown Boxes

select = driver.FindElement(By.CssSelector("select[uniq id']"));
                selectElement = new SelectElement(select);
                var optionList =
                    driver.FindElements(By.CssSelector("select[uniq id']>option"));
                selectElement.SelectByText(optionList[GenerateRandomNumber(1, optionList.Count())].Text);

Convert List<DerivedClass> to List<BaseClass>

The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:

List<A> listOfA = new List<C>().ConvertAll(x => (A)x);

You could also use Linq:

List<A> listOfA = new List<C>().Cast<A>().ToList();

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

How do I POST JSON data with cURL?

If you're testing a lot of JSON send/responses against a RESTful interface, you may want to check out the Postman plug-in for Chrome (which allows you to manually define web service tests) and its Node.js-based Newman command-line companion (which allows you to automate tests against "collections" of Postman tests.) Both free and open!

How can I find the length of a number?

You should go for the simplest one (stringLength), readability always beats speed. But if you care about speed here are some below.

Three different methods all with varying speed.

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}

What's the right way to decode a string that has special HTML entities in it?

If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:

function parseHtmlEntities(str) {
    return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
        var num = parseInt(numStr, 10); // read num as normal number
        return String.fromCharCode(num);
    });
}

[Edit]

Note: this would only work for numeric html-entities, and not stuff like &oring;.

[Edit 2]

Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/

How can I get CMake to find my alternative Boost installation?

I spent most of my evening trying to get this working. I tried all of the -DBOOST_* &c. directives with CMake, but it kept linking to my system Boost libraries, even after clearing and re-configuring my build area repeatedly.

At the end I modified the generated Makefile and voided the cmake_check_build_system target to do nothing (like 'echo ""') so that it wouldn't overwrite my changes when I ran make, and then did 'grep -rl "lboost_python" * | xargs sed -i "s:-lboost_python:-L/opt/sw/gcc5/usr/lib/ -lboost_python:g' in my build/ directory to explicitly point all the build commands to the Boost installation I wanted to use. Finally, that worked.

I acknowledge that it is an ugly kludge, but I am just putting it out here for the benefit of those who come up against the same brick wall, and just want to work around it and get work done.

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

Laravel Soft Delete posts

In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task. In Model, inside the class just write 'use SoftDeletes'. Example

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

And In Controller, you can do deletion. Example

User::where('email', '[email protected]')->delete();

or

User::where('email', '[email protected]')->softDeletes();

Make sure that you must have 'deleted_at' column in the users Table.

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

How to escape single quotes in MySQL

You can use this code,

<?php
     $var = "This is Ashok's Pen.";
     addslashes($var);
?>

if mysqli_real_escape_string() does not work.

how to resolve DTS_E_OLEDBERROR. in ssis

I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables to 1.

Sorting a Data Table

private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;

DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}

//clear the incoming dt
dt.Rows.Clear();

for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}

DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}

C/C++ line number

As part of the C++ standard there exists some pre-defined macros that you can use. Section 16.8 of the C++ standard defines amongst other things, the __LINE__ macro.

__LINE__: The line number of the current source line (a decimal constant).
__FILE__: The presumed name of the source file (a character string literal).
__DATE__: The date of translation of the source file (a character string literal...)
__TIME__: The time of translation of the source file (a character string literal...)
__STDC__: Whether__STDC__ is predefined
__cplusplus: The name __cplusplus is defined to the value 199711L when compiling a C ++ translation unit

So your code would be:

if(!Logical)
  printf("Not logical value at line number %d \n",__LINE__);

What is the difference between UTF-8 and Unicode?

Unicode is a standard that defines, along with ISO/IEC 10646, Universal Character Set (UCS) which is a superset of all existing characters required to represent practically all known languages.

Unicode assigns a Name and a Number (Character Code, or Code-Point) to each character in its repertoire.

UTF-8 encoding, is a way to represent these characters digitally in computer memory. UTF-8 maps each code-point into a sequence of octets (8-bit bytes)

For e.g.,

UCS Character = Unicode Han Character

UCS code-point = U+24B62

UTF-8 encoding = F0 A4 AD A2 (hex) = 11110000 10100100 10101101 10100010 (bin)

requestFeature() must be called before adding content

I had this issue with Dialogs based on an extended DialogFragment which worked fine on devices running API 26 but failed with API 23. The above strategies didn't work but I resolved the issue by removing the onCreateView method (which had been added by a more recent Android Studio template) from the DialogFragment and creating the dialog in onCreateDialog.

How to import or copy images to the "res" folder in Android Studio?

You can simply use the terminal that comes with Android Studio. It is listed at the bottom of Android Studio. Just open it and use the cp command.

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Hide text using css

Use Condition tag for different browser and using css you have to place height:0px and width:0px also you have to place font-size:0px.

How to force Sequential Javascript Execution?

I had the same problem, this is my solution:

_x000D_
_x000D_
var functionsToCall = new Array();_x000D_
_x000D_
function f1() {_x000D_
    $.ajax({_x000D_
        type:"POST",_x000D_
        url: "/some/url",_x000D_
        success: function(data) {_x000D_
            doSomethingWith(data);_x000D_
            //When done, call the next function.._x000D_
            callAFunction("parameter");_x000D_
        }_x000D_
    });_x000D_
}_x000D_
_x000D_
function f2() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter2");_x000D_
}_x000D_
function f3() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter3");_x000D_
}_x000D_
function f4() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter4");_x000D_
}_x000D_
function f5() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter5");_x000D_
}_x000D_
function f6() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter6");_x000D_
}_x000D_
function f7() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter7");_x000D_
}_x000D_
function f8() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter8");_x000D_
}_x000D_
function f9() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter9");_x000D_
}_x000D_
    _x000D_
function callAllFunctionsSy(params) {_x000D_
 functionsToCall.push(f1);_x000D_
 functionsToCall.push(f2);_x000D_
 functionsToCall.push(f3);_x000D_
 functionsToCall.push(f4);_x000D_
 functionsToCall.push(f5);_x000D_
 functionsToCall.push(f6);_x000D_
 functionsToCall.push(f7);_x000D_
 functionsToCall.push(f8);_x000D_
 functionsToCall.push(f9);_x000D_
 functionsToCall.reverse();_x000D_
 callAFunction(params);_x000D_
}_x000D_
_x000D_
function callAFunction(params) {_x000D_
 if (functionsToCall.length > 0) {_x000D_
  var f=functionsToCall.pop();_x000D_
  f(params);_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Which MySQL datatype to use for an IP address?

For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED. You can use MySQL's INET_ATON() function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN queries

INET_ATON() MySQL function

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

One reason MATLAB is popular with universities is the same reason a lot of things are popular with universities: there's a lot of professors familiar with it, and it's fairly robust.

I've spoken to a lot of folks who are especially interested in MATLAB's nascent ability to tap into the GPU instead of working serially. Having used Python in grad school, I kind of wish I had the licks to work with MATLAB in that case. It sure would make vector space calculations a breeze.

Compiler warning - suggest parentheses around assignment used as truth value

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

Python Dictionary Comprehension

There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

Getting number of elements in an iterator in Python

An iterator is just an object which has a pointer to the next object to be read by some kind of buffer or stream, it's like a LinkedList where you don't know how many things you have until you iterate through them. Iterators are meant to be efficient because all they do is tell you what is next by references instead of using indexing (but as you saw you lose the ability to see how many entries are next).

How do I refresh a DIV content?

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

Try this:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

Laravel 4: Redirect to a given url

Yes, it's

use Illuminate\Support\Facades\Redirect;

return Redirect::to('http://heera.it');

Check the documentation.

Update: Redirect::away('url') (For external link, Laravel Version 4.19):

public function away($path, $status = 302, $headers = array())
{
    return $this->createRedirect($path, $status, $headers);
}

How to convert int to string on Arduino?

The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.

char *i2str(int i, char *buf){
  byte l=0;
  if(i<0) buf[l++]='-';
  boolean leadingZ=true;
  for(int div=10000, mod=0; div>0; div/=10){
    mod=i%div;
    i/=div;
    if(!leadingZ || i!=0){
       leadingZ=false;
       buf[l++]=i+'0';
    }
    i=mod;
  }
  buf[l]=0;
  return buf;
}

Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.

Operation Not Permitted when on root - El Capitan (rootless disabled)

Correct solution is to copy or install to /usr/local/bin not /usr/bin.This is due to System Integrity Protection (SIP). SIP makes /usr/bin read-only but leaves /usr/local as read-write.

SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.

As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."

Convert a PHP object to an associative array

Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.

Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.

    /**
     * Converts given object to array, recursively.
     * Just outputs public properties.
     *
     * @param object|array $object
     * @return array|string
     */
    protected function objectToArray($object) {
        if (in_array($object, $this->usedObjects, TRUE)) {
            return '**recursive**';
        }
        if (is_array($object) || is_object($object)) {
            if (is_object($object)) {
                $this->usedObjects[] = $object;
            }
            $result = array();
            $reflectorClass = new \ReflectionClass(get_class($this));
            foreach ($object as $key => $value) {
                if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
                    $result[$key] = $this->objectToArray($value);
                }
            }
            return $result;
        }
        return $object;
    }

To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.

How do I calculate the date six months from the current date using the datetime Python module?

So, here is an example of the dateutil.relativedelta which I found useful for iterating through the past year, skipping a month each time to the present date:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
...  day = today - relativedelta(months=month_count)
...  print day
...  month_count += 1
... 
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968

As with the other answers, you have to figure out what you actually mean by "6 months from now." If you mean "today's day of the month in the month six years in the future" then this would do:

datetime.datetime.now() + relativedelta(months=6)

Express.js req.body undefined

This is also one possibility: Make Sure that you should write this code before the route in your app.js(or index.js) file.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

How to enable authentication on MongoDB through Docker?

a. You can use environment variables via terminal:

$ docker run -d --name container_name \
      -e MONGO_INITDB_ROOT_USERNAME=admin \
      -e MONGO_INITDB_ROOT_PASSWORD=password \
      mongo

If you like to test if everything works:

// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash

// Enter into mongo shell
$ mongo

// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())

// Show available databases
$> show dbs

If you like to instantiate a database on first run, check option b.

b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.

As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your yaml file:

mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth flag accordingly.

c. You can also use docker secrets.

MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE variables:

mongo:
    image: mongo
    environment:
        - MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
        - MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
    secrets:
      - db_root_username
      - db_root_password

docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE to MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD.

You can use MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your .sh or .js scripts in docker-entrypoint-initdb.d folder while initializing database instance.

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

This last method is not in the reference docs, so it may not survive an update.

String representation of an Enum

Just use the ToString() method

public enum any{Tomato=0,Melon,Watermelon}

To reference the string Tomato, just use

any.Tomato.ToString();

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case, i was calling twice the import...

@click="$router.push({ path: 'searcherresult' })"

import SearcherResult from "../views/SearcherResult"; --- ERROR

Cause i call in other component...

Resize HTML5 canvas to fit window

Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.

Something like that

_x000D_
_x000D_
$( window ).resize(function() {_x000D_
   $("#myCanvas").width($( window ).width())_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
_x000D_
_x000D_
_x000D_

Using IF ELSE statement based on Count to execute different Insert statements

If this is in SQL Server, your syntax is correct; however, you need to reference the COUNT(*) as the Total Count from your nested query. This should give you what you need:

SELECT CASE WHEN TotalCount >0 THEN 'TRUE' ELSE 'FALSE' END FROM
(
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) DerivedTable

Using this, you could assign TotalCount to a variable and then use an IF ELSE statement to execute your INSERT statements:

DECLARE @TotalCount int
SELECT @TotalCount = TotalCount FROM
(
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) DerivedTable
IF @TotalCount > 0
    -- INSERT STATEMENT 1 GOES HERE
ELSE
    -- INSERT STATEMENT 2 GOES HERE

How to run vi on docker container?

If you actually want a small editor for simple housekeeping in a docker, use this in your Dockerfile:

RUN apt-get install -y busybox && ln -s /bin/busybox /bin/vi

I used it on an Ubuntu 18 based docker. (Of course you might need an RUN apt-get update before it but if you are making your own Docker file you probably already have that.)

npm install doesn't create node_modules directory

As soon as you have run npm init and you start installing npm packages it'll create the node_moduals folder after that first install

e.g

npm init

(Asks you to set up your package.json file)

npm install <package name here> --save-dev

installs package & creates the node modules directory

SQL Server check case-sensitivity?

You're interested in the collation. You could build something based on this snippet:

SELECT DATABASEPROPERTYEX('master', 'Collation');

Update
Based on your edit — If @test and @TEST can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL, because NULL = NULL returns `false.

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

I removed whole css under in head, which was loading colors and images for error/highlighting messages in page.And the website is working fine now.

How to get the first column of a pandas DataFrame as a Series?

Isn't this the simplest way?

By column name:

In [20]: df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
In [21]: df
Out[21]:
    x   y
0   1   4
1   2   5
2   3   6
3   4   7

In [23]: df.x
Out[23]:
0    1
1    2
2    3
3    4
Name: x, dtype: int64

In [24]: type(df.x)
Out[24]:
pandas.core.series.Series

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

For django 1.9+
You can use Fields disabled argument to make field disable. e.g. In following code snippet from forms.py file , I have made employee_code field disabled

class EmployeeForm(forms.ModelForm):
    employee_code = forms.CharField(disabled=True)
    class Meta:
        model = Employee
        fields = ('employee_code', 'designation', 'salary')

Reference https://docs.djangoproject.com/en/dev/ref/forms/fields/#disabled

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

if you get this error

Gradle: 
FAILURE: Could not determine which tasks to execute.
* What went wrong:
Task 'assemble' not found in root project 'MyProject'.
* Try:
Run gradle tasks to get a list of available tasks.

You need to edit your Projects .iml file. not the one under src. the one that is like myappProject.iml' delete the whole component name = facetmanager

<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
...remove this element and everything inside such as <facet> elements...
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
...keep this part...
</component

Dark Theme for Visual Studio 2010 With Productivity Power Tools

There is a style that I've created based on dark style from VS 2015 to use on my VS 2010. You can download this style from Dark Style from VS 2015.

After download it, just import through menu Tools -> Import and Export Settings...

How do I get the last four characters from a string in C#?

Using Substring is actually quite short and readable:

 var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
 // result == "d124"

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

XPath test if node value is number

You could always use something like this:

string(//Sesscode) castable as xs:decimal

castable is documented by W3C here.

How to set the font size in Emacs?

M-x customize-face RET default will allow you to set the face default face, on which all other faces base on. There you can set the font-size.

Here is what is in my .emacs. actually, color-theme will set the basics, then my custom face setting will override some stuff. the custom-set-faces is written by emacs's customize-face mechanism:

;; my colour theme is whateveryouwant :)
(require 'color-theme)
(color-theme-initialize)
(color-theme-whateveryouwant)

(custom-set-faces
  ;; custom-set-faces was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(default ((t (:stipple nil :background "white" :foreground "black" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 98 :width normal :foundry "unknown" :family "DejaVu Sans Mono"))))
 '(font-lock-comment-face ((t (:foreground "darkorange4"))))
 '(font-lock-function-name-face ((t (:foreground "navy"))))
 '(font-lock-keyword-face ((t (:foreground "red4"))))
 '(font-lock-type-face ((t (:foreground "black"))))
 '(linum ((t (:inherit shadow :background "gray95"))))
 '(mode-line ((t (nil nil nil nil :background "grey90" (:line-width -1 :color nil :style released-button) "black" :box nil :width condensed :foundry "unknown" :family "DejaVu Sans Mono")))))

How to autosize a textarea using Prototype?

For those that are coding for IE and encounter this problem. IE has a little trick that makes it 100% CSS.

<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>

You can even provide a value for rows="n" which IE will ignore, but other browsers will use. I really hate coding that implements IE hacks, but this one is very helpful. It is possible that it only works in Quirks mode.

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

On an Ubuntu box, I started getting this error after moving /tmp to a different volume (symlink). Even after setting the required permission 1777, the issue was not resolved.

MySQL is protected by AppArmor, which was disallowing writes to the new tmp location /mnt/tmp. I had to add the following lines to /etc/apparmor.d/abstractions/user-tmp to fix this

owner /mnt/tmp/** rwkl,

/mnt/tmp/ rw,

add a string prefix to each value in a string column using Pandas

df['col'] = 'str' + df['col'].astype(str)

Example:

>>> df = pd.DataFrame({'col':['a',0]})
>>> df
  col
0   a
1   0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
    col
0  stra
1  str0

jQuery find events handlers registered with an object

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    }

    // jQuery version < 1.7.?
    if (typeof(this.data) === 'function') {
        return this.data('events') || {};
    }

    return {};
};

But beware, this function can only return events that were set using jQuery itself.

Convert hex color value ( #ffffff ) to integer value

I have the same problem that I found some color in form of #AAAAAA and I want to conver that into a form that android could make use of. I found that you can just use 0xFFAAAAAA so that android could automatically tell the color. Notice the first FF is telling alpha value. Hope it helps

Print a variable in hexadecimal in Python

Use

print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))

like this:

>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>

On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

It is working fine for me, but with a different command:

root@ubuntu:/usr/bin# sudo apt-get install sun-java6

Error message:

Couldn't find package sun-java6.

root@ubuntu:/usr/bin# sudo apt-get install sun-java*

Bam, it worked.

Get client IP address via third party web service

Well, if in the HTML you import a script...

<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>

You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.

To redirect: <script>if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}</script>

Or to show it on the page: document.write (userIP);

DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.

<?php //Gets the IP address $ip = getenv("REMOTE_ADDR") ; Echo "var userIP = '" . $ip . "';"; ?>

How to force the browser to reload cached CSS and JavaScript files

I am not sure why you guys/gals are taking so much pain to implement this solution.

All you need to do if get the file's modified timestamp and append it as a querystring to the file.

In PHP I would do it as:

<link href="mycss.css?v=<?= filemtime('mycss.css') ?>" rel="stylesheet">

filemtime() is a PHP function that returns the file modified timestamp.

How can I delete multiple lines in vi?

If you want to delete a range AFTER a specific line trigger you can use something like this

:g/^TMPDIR/ :.,+11d

That deletes 11 lines (inclusive) after every encounter of ^TMPDIR.

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.

http://localhost:8080/env-vars.html/

Just replace localhost with your Jenkins hostname, if its different

Get DOS path instead of Windows path

similar to this answer but uses a sub-routine

@echo off
CLS

:: my code goes here
set "my_variable=C:\Program Files (x86)\Microsoft Office"

echo %my_variable%

call :_sub_Short_Path "%my_variable%"
set "my_variable=%_s_Short_Path%"

echo %my_variable%

:: rest of my code goes here
goto EOF

:_sub_Short_Path
set _s_Short_Path=%~s1
EXIT /b

:EOF

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

dynamically add and remove view to viewpager

I was looking for simple solution to remove views from viewpager (no fragments) dynamically. So, if you have some info, that your pages belongs to, you can set it to View as tag. Just like that (adapter code):

@Override
public Object instantiateItem(ViewGroup collection, int position)
{
    ImageView iv = new ImageView(mContext);
    MediaMessage msg = mMessages.get(position);
    ...

    iv.setTag(media);
    return iv;
}

@Override
public int getItemPosition (Object object)
{
    View o = (View) object;
    int index = mMessages.indexOf(o.getTag());
    if (index == -1)
        return POSITION_NONE;
    else
        return index;
}

You just need remove your info from mMessages, and then call notifyDataSetChanged() for your adapter. Bad news there is no animation in this case.

Not able to change TextField Border Color

That is not changing due to the default theme set to the screen.

So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()

child: new Theme(
          data: new ThemeData(
            primaryColor: Colors.redAccent,
            primaryColorDark: Colors.red,
          ),
          child: new TextField(
            decoration: new InputDecoration(
                border: new OutlineInputBorder(
                    borderSide: new BorderSide(color: Colors.teal)),
                hintText: 'Tell us about yourself',
                helperText: 'Keep it short, this is just a demo.',
                labelText: 'Life story',
                prefixIcon: const Icon(
                  Icons.person,
                  color: Colors.green,
                ),
                prefixText: ' ',
                suffixText: 'USD',
                suffixStyle: const TextStyle(color: Colors.green)),
          ),
        ));

enter image description here

How to open a local disk file with JavaScript?

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.

Convert seconds to hh:mm:ss in Python

If you use divmod, you are immune to different flavors of integer division:

# show time strings for 3800 seconds

# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)

# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
    reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
        [(3800,),60,60])


# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
    return "%02d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(round(t*1000),),1000,60,60])

print secondsToStr(3800.123)

Prints:

63:20
01:03:20
01:03:20.123

Is there a way to style a TextView to uppercase all of its letters?

It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).

In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.

At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.

Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.

This is the class:

package com.realactionsoft.android.widget;

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.widget.TextView;


public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {

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

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text.toString().toUpperCase(), type);
    }

}

And whenever you need to use it, just declare it with all the package in the XML layout:

<com.realactionsoft.android.widget.CapitalizedTextView 
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.

C# Wait until condition is true

This implementation is totally based on Sinaesthetic's, but adding CancellationToken and keeping the same execution thread and context; that is, delegating the use of Task.Run() up to the caller depending on whether condition needs to be evaluated in the same thread or not.

Also, notice that, if you don't really need to throw a TimeoutException and breaking the loop is enough, you might want to make use of cts.CancelAfter() or new CancellationTokenSource(millisecondsDelay) instead of using timeoutTask with Task.Delay plus Task.WhenAny.

public static class AsyncUtils
{
    /// <summary>
    ///     Blocks while condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks until condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (!condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     The cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitWhileAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }

    /// <summary>
    ///     Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitUntilAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }
}

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

DateTime fields from SQL Server display incorrectly in Excel

Here's a hack which might be helpful... it puts an apostrophe in front of the time value, so when you right-click on the output in SSMS and say "Copy with Headers", then paste into Excel, it preserves the milliseconds / nanoseconds for datetime2 values. It's a bit ugly that it puts the apostrophe there, but it's better than the frustration of dealing with Excel doing unwanted rounding on the time value. The date is a UK format but you can look at the CONVERT function page in MSDN.

SELECT CONVERT(VARCHAR(23), sm.MilestoneDate, 103) AS MilestoneDate, '''' + CONVERT(VARCHAR(23), sm.MilestoneDate, 114) AS MilestoneTime FROM SomeTable sm

Eclipse cannot load SWT libraries

If you start eclipse using oracle java, then eclipse might fail in finding native libraries like SWT or SVN libraries. The SWT-JNI libraries are located in /usr/lib/jni/ and the SVN-JNI libraries are located in /usr/lib/x86_64-linux-gnu/jni/.

Instead of starting eclipse with the command

eclipse

you can use the command

env LD_LIBRARY_PATH=/usr/lib/jni/:/usr/lib/x86_64-linux-gnu/jni/:$LD_LIBRARY_PATH eclipse

to pass the environment variable LD_LIBRARY_PATH to eclipse. Eclipse will find the native libraries and will run properly.

The Definitive C Book Guide and List

Warning!

This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.

Reference (All Levels)

  • The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.

  • C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.

  • C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).

  • The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.

  • Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.

  • The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.

  • Rationale for C99 Standard.


Beginner

  • C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.

  • Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.

Intermediate

  • Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.

  • C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.

  • The C Puzzle Book - Alan R. Feuer (1998)

  • The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.

  • 21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).

  • Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.

  • Extreme C: Push the limits of what C and you can do - Kamran Amini (2019). This book builds on your existing C knowledge to help you become a more expert C programmer. You will gain insights into algorithm design, functions, and structures, and understand both multi-threading and multi-processing in a POSIX environment.

Expert


Uncategorized

  • Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing // comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.

  • C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.

  • C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.

  • Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.

  • The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.

  • C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.

    Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.

  • MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.

    Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).

    Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)

  • Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.


Warnings

There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).

Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.

Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++) and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets, %[\n]s in scanf, storing return value of getchar in a variable of type char or using fflush on stdin.

Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:

To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).

"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler


Outdated


Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood, Ben Jackson, Bubbles, claws, coledot, Dana Robinson, Daniel Holden, desbest, Dervin Thunk, dwc, Erci Hou, Garen, haziz, Johan Bezem, Jonathan Leffler, Joshua Partogi, Lucas, Lundin, Matt K., mossplix, Matthieu M., midor, Nietzche-jou, Norman Ramsey, r3st0r3, ridthyself, Robert S. Barnes, Steve Summit, Tim Ring, Tony Bai, VMAtm

.htaccess redirect www to non-www with SSL/HTTPS

Ref: Apache redirect www to non-www and HTTP to HTTPS

http://example.com

http://www.example.com

https://www.example.com

to

https://example.com

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

How to send post request to the below post method using postman rest client

  1. Open Postman.
  2. Enter URL in the URL bar http://{server:port}/json/metallica/post.
  3. Click Headers button and enter Content-Type as header and application/json in value.
  4. Select POST from the dropdown next to the URL text box.
  5. Select raw from the buttons available below URL text box.
  6. Select JSON from the following dropdown.
  7. In the textarea available below, post your request object:

    {
     "title" : "test title",
     "singer" : "some singer"
    }
    
  8. Hit Send.

  9. Refer to screenshot below: enter image description here

Inserting multiple rows in a single SQL query?

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

Can RDP clients launch remote applications and not desktops

Using an RDP connection file you can set the alternate shell to be your application; the file syntax is like

alternate shell:s:c:\winnt\system32\notepad.exe

and you pass that as a command-line argument to mstsc.exe; this similar to chrissr's solution, but without affecting every RDP session you launch. A fuller summary of settings here.

In Python try until no error

Many different answers here but I used a combination of a few of the brilliant answers and threw in my own not-so-secret sauce to come up with the following recipe:

def actioin_one(self):
    action = # define attempted action here
    failure = bool(action.status_code != 200) # example ... replace this.
    self.attempt_action_repeatedly(action, 5, failure)

def action_two(self):
    action = # define attempted action here
    failure = bool(action.status_code != 200) # example ... replace this.
    self.attempt_action_repeatedly(action, 5, failure)

def attempt_action_repeatedly(self, action, authorized_attempts, failure):
    attempts = 0
    sleep_time = 2 # seconds
    more_attempts_left = bool(attempts < authorized_attempts)
    while failure and more_attempts_left:
        action
        attempts += 1
        sleep(sleep_time)

    if not more_attempts_left:
        print("Max number of attempts exceeded. Attempts failed because:")
        data = action.json() # customize this 
        print(data['detail']) # customize this       

How to force C# .net app to run only one instance in Windows?

another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public Main()
    {
        InitializeComponent();

        Process current = Process.GetCurrentProcess();
        string currentmd5 = md5hash(current.MainModule.FileName);
        Process[] processlist = Process.GetProcesses();
        foreach (Process process in processlist)
        {
            if (process.Id != current.Id)
            {
                try
                {
                    if (currentmd5 == md5hash(process.MainModule.FileName))
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        Environment.Exit(0);
                    }
                }
                catch (/* your exception */) { /* your exception goes here */ }
            }
        }
    }

    private string md5hash(string file)
    {
        string check;
        using (FileStream FileCheck = File.OpenRead(file))
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] md5Hash = md5.ComputeHash(FileCheck);
            check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
        }

        return check;
    }

it checks only md5 sums by process id.

if an instance of this application was found, it focuses the running application and exit itself.

you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.

may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

How to get name of the computer in VBA?

You can do like this:

Sub Get_Environmental_Variable()

Dim sHostName As String
Dim sUserName As String

' Get Host Name / Get Computer Name    
sHostName = Environ$("computername")

' Get Current User Name    
sUserName = Environ$("username")

End Sub

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader

Pandas: Convert Timestamp to datetime.date

Use the .date method:

In [11]: t = pd.Timestamp('2013-12-25 00:00:00')

In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)

In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True

To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:

In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')

In [22]: ts = pd.DatetimeIndex([t])

In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)

Drawing Circle with OpenGL

I have done it using the following code,

glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

Difference between HashSet and HashMap?

A HashSet uses a HashMap internally to store its entries. Each entry in the internal HashMap is keyed by a single Object, so all entries hash into the same bucket. I don't recall what the internal HashMap uses to store its values, but it doesn't really matter since that internal container will never contain duplicate values.

EDIT: To address Matthew's comment, he's right; I had it backwards. The internal HashMap is keyed with the Objects that make up the Set elements. The values of the HashMap are an Object that's just simply stored in the HashMap buckets.

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

How can I create a dynamic button click event on a dynamic button?

Simply add the eventhandler to the button when creating it.

 button.Click += new EventHandler(this.button_Click);

void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}

Form inside a form, is that alright?

If you have a master form and are forced to have a "form with a form" Here is what you can do... in my case I had a link in the globalHeader and I wanted to perform a post when it was clicked:

Example form post with link button submit:

Instead of a form... wrap your input in a div:

 <div id="gap_form"><input type="hidden" name="PostVar"/><a id="myLink" href="javascript:Form2.submit()">A Link</a></div>

js file:

$(document).ready(function () {
(function () {
    $('#gap_form').wrap('<form id="Form2" action="http://sitetopostto.com/postpage" method="post" target="_blank"></form>');
})();});

This would wrap everything inside the div "gap_form" inside a form on the fly and the link would submit that form. I have this exact example working on a page now... (In my example...You could accomplish the same thing by redirecting to a new page and submitting the form on that page... but I like this better)

HTML5 Local storage vs. Session storage

Few other points which might be helpful to understand differences between local and session storage

  1. Both local storage and session storage are scoped to document origin, so

    https://mydomain.com/
    http://mydomain.com/
    https://mydomain.com:8080/

    All of the above URL's will not share the same storage. (Notice path of the web page does not affect the web storage)

  2. Session storage is different even for the document with same origin policy open in different tabs, so same web page open in two different tabs cannot share the same session storage.

  3. Both local and session storage are also scoped by browser vendors. So storage data saved by IE cannot be read by Chrome or FF.

Hope this helps.