Programs & Examples On #Sqlcachedependency

AsyncTask Android example

My full answer is here, but here is an explanatory image to supplement the other answers on this page. For me, understanding where all the variables were going was the most confusing part in the beginning.

enter image description here

How to get post slug from post in WordPress?

Here is most advanced and updated version what cover many cases:

if(!function_exists('the_slug')):
    function the_slug($post_id=false, $echo=true) {
        global $product, $page;

        if(is_numeric($post_id) && $post_id == intval($post_id)) {} else {
            if(!is_object($post_id)){}else if(property_exists($post_id, 'ID')){
                $post_id = $post_id->ID;
            }
            if(empty($post_id) && property_exists($product, 'ID')) $post_id = $product->ID;
            if(empty($post_id)) $post_id =  get_the_ID();

            if(empty($post_id) && property_exists($page, 'ID')) $post_id =  $page->ID;
        }

        if(!empty($post_id))
            $slug = basename(get_permalink($post_id));
        else
            $slug = basename(get_permalink());
        do_action('before_slug', $slug);
        $slug = apply_filters('slug_filter', $slug);
        if( $echo ) echo $slug;
        do_action('after_slug', $slug);
        return $slug;
      }
endif;

This is collections from the best answers and few my updates.

JavaScript hashmap equivalent

JavaScript does not have a built-in map/hashmap. It should be called an associative array.

hash["X"] is equal to hash.X, but it allows "X" as a string variable. In other words, hash[x] is functionally equal to eval("hash."+x.toString()).

It is more similar to object.properties rather than key-value mapping. If you are looking for a better key/value mapping in JavaScript, please use the Map object.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

How to close TCP and UDP ports via windows command line

you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

After you exit the eclipse, there would be an specific failed reason. Mine is that the DISK IS FULL so the eclipse can't write into it anymore.

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

OpenSSL and error in reading openssl.conf file

Just add to your command line the parameter -config c:\your_openssl_path\openssl.cfg, changing your_openssl_path to the real installed path.

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

How to request a random row in SQL?

For SQL Server 2005 and 2008, if we want a random sample of individual rows (from Books Online):

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)
/ CAST (0x7fffffff AS int)

How to convert int to Integer

int iInt = 10;
Integer iInteger = new Integer(iInt);

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

Owl Carousel Won't Autoplay

If you using v1.3.3 then use following property

autoPlay : 5000

Or using latest version then use following property

autoPlay : true

How do I resolve ClassNotFoundException?

If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

How to write a foreach in SQL Server?

Although cursors usually considered horrible evil I believe this is a case for FAST_FORWARD cursor - the closest thing you can get to FOREACH in TSQL.

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

How do I "select Android SDK" in Android Studio?

Press " ? + Shift + A" on Mac (or "Ctrl+Shift+A" on Windows) and in the pop-up EditText, write "Sync Project with Gradle Files". After that double click on the appeared option. It will then sync your Gradle file SDK with the project file.

Limit text length to n lines using CSS

.class{
   word-break: break-word;
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   line-height: 16px; /* fallback */
   max-height: 32px; /* fallback */
   -webkit-line-clamp: 2; /* number of lines to show */
   -webkit-box-orient: vertical;
}

get enum name from enum value

If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.

import java.util.HashMap;
import java.util.Map;

/**
 * Example of enum with a getter that need a value in parameter, and that return the Choice/Instance 
 * of the enum which has the same value.
 * The value of each choice can be random.
 */
public enum MyEnum {
    /** a random choice */
    Choice1(4),
    /** a nother one */
    Choice2(2),
    /** another one again */
    Choice3(9);
    /** a map that contains every choices of the enum ordered by their value. */
    private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
    static {
        // populating the map
        for (MyEnum myEnum : values()) {
            MY_MAP.put(myEnum.getValue(), myEnum);
        }
    }
    /** the value of the choice */
    private int value;

    /**
     * constructor
     * @param value the value
     */
    private MyEnum(int value) {
        this.value = value;
    }

    /**
     * getter of the value
     * @return int
     */
    public int getValue() {
        return value;
    }

    /**
     * Return one of the choice of the enum by its value.
     * May return null if there is no choice for this value.
     * @param value value
     * @return MyEnum
     */
    public static MyEnum getByValue(int value) {
        return MY_MAP.get(value);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.Enum#toString()
     */
    public String toString() {
        return name() + "=" + value;
    }

    /**
     * Exemple of how to use this class.
     * @param args args
     */
    public static void main(String[] args) {
        MyEnum enum1 = MyEnum.Choice1;
        System.out.println("enum1==>" + String.valueOf(enum1));
        MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
        System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
        MyEnum enum3Unknown = MyEnum.getByValue(4);
        System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
    }
}

Convert base64 string to ArrayBuffer

Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.

var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
   var byteArray = new Uint8Array(e.target.response);
   // var shortArray = new Int16Array(e.target.response);
   // var unsignedShortArray = new Int16Array(e.target.response);
   // etc.
}
req.send();

The send request fails if the base 64 string is badly formed.

The mime type (application/octet) is probably unnecessary.

Tested in chrome. Should work in other browsers.

Is there a way to collapse all code blocks in Eclipse?

I had the same problem and found out Folding can be enabled or disabled, and in my case got disabled somehow.

To solve it, simply right click on the line numbers/breakpoint section (vertical bar in the left of the editor), then under the 'Folding' section chose 'Enable folding'.

ctrlshift/ should be working fine after.

How do you comment an MS-access Query?

if you are trying to add a general note to the overall object (query or table etc..)

Access 2016 go to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory "table last last updated 05/31/17"

How to change language settings in R

For mac users, I found this on the R for Mac FAQ

If you use a non-standard setup (e.g. different language than formats), you can override the auto-detection performed by setting `force.LANG' defaults setting, such as for example

 defaults write org.R-project.R force.LANG en_US.UTF-8 

when run in Terminal it will enforce US-english setting regardless of the system setting. If you don't know what Terminal is you can use this R command instead:

 system("defaults write org.R-project.R force.LANG en_US.UTF-8") 

but do not forget to quit R and start R.app again afterwards. Please note that you must always use `.UTF-8' version of the locale, otherwise R.app will not work properly.

This helped me to change my console language from Chinese to English.

Valid values for android:fontFamily and what they map to?

As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.

ie:

public class Museo500TextView extends TextView {
    public Museo500TextView(Context context, AttributeSet attrs) {
        super(context, attrs);      
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
    }
}

and

<my.package.views.Museo900TextView
        android:id="@+id/dialog_error_text_header"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="12sp" />

Rails DateTime.now without Time

What about Date.today.to_time?

IntelliJ IDEA JDK configuration on Mac OS

Quite late to this party, today I had the same problem. The right answer on macOs I think is use jenv

brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11

And then add into Intellij IDEA as new SDK the following path:

~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...

VBA Excel sort range by specific column

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

Export multiple classes in ES6 modules

Try this in your code:

import Foo from './Foo';
import Bar from './Bar';

// without default
export {
  Foo,
  Bar,
}

Btw, you can also do it this way:

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'

// and import somewhere..
import Baz, { Foo, Bar } from './bundle'

Using export

export const MyFunction = () => {}
export const MyFunction2 = () => {}

const Var = 1;
const Var2 = 2;

export {
   Var,
   Var2,
}


// Then import it this way
import {
  MyFunction,
  MyFunction2,
  Var,
  Var2,
} from './foo-bar-baz';

The difference with export default is that you can export something, and apply the name where you import it:

// export default
export default class UserClass {
  constructor() {}
};

// import it
import User from './user'

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

Python 3.4.0 with MySQL database

Maybe you can use a work around and try something like:

import datetime
#import mysql
import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1',user = 'someUser', passwd = 'foobar',db = 'foobardb')
cursor = conn.cursor()

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

Position a div container on the right side

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

Add alternating row color to SQL Server Reporting services report

I got the chess effect when I used Catch22's solution, I think because my matrix has more than one column in design. that expression worked fine for me :

=iif(RunningValue(Fields![rowgroupfield].Value.ToString,CountDistinct,Nothing) Mod 2,"Gainsboro", "White")

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Per batch, 65536 * Network Packet Size which is 4k so 256 MB

However, IN will stop way before that but it's not precise.

You end up with memory errors but I can't recall the exact error. A huge IN will be inefficient anyway.

Edit: Remus reminded me: the error is about "stack size"

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

Setting a spinner onClickListener() in Android

I suggest that all events for Spinner are divided on two types:

  1. User events (you meant as "click" event).

  2. Program events.

I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:

private void setSelectionWithoutDispatch(Spinner spinner, int position) {
    AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
    spinner.setOnItemSelectedListener(null);
    spinner.setSelection(position, false);
    spinner.setOnItemSelectedListener(onItemSelectedListener);
}

There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.

What is a Memory Heap?

It's a chunk of memory allocated from the operating system by the memory manager in use by a process. Calls to malloc() et alia then take memory from this heap instead of having to deal with the operating system directly.

Import JSON file in React

// rename the .json file to .js and keep in src folder

Declare the json object as a variable

var customData = {
   "key":"value"
};

Export it using module.exports

module.exports = customData;

From the component that needs it, make sure to back out two folders deep

import customData from '../customData';

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Android 'Unable to add window -- token null is not for an application' exception

I tried with this in the context field:

this.getActivity().getParent()

and it works fine for me. This was from a class which extends from "Fragment":

public class filtro extends Fragment{...

How to get english language word database?

I do not see http://wordlist.sourceforge.net/ mentioned here, but that is where I would start if I were looking for something like this (and I was, when I stumbled over this question).

If you cannot find what you want there, and what you want is a list of english words, then you should probably spend some extra time describing how to recognize what it is that you want.

git visual diff between branches

Have a look at git show-branch

There's a lot you can do with core git functionality. It might be good to specify what you'd like to include in your visual diff. Most answers focus on line-by-line diffs of commits, where your example focuses on names of files affected in a given commit.

One visual that seems not to be addressed is how to see the commits that branches contain (whether in common or uniquely).

For this visual, I'm a big fan of git show-branch; it breaks out a well organized table of commits per branch back to the common ancestor. - to try it on a repo with multiple branches with divergences, just type git show-branch and check the output - for a writeup with examples, see Compare Commits Between Git Branches

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

JSP tricks to make templating easier?

As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.

Let's take your simple example.

Put the following in WEB-INF/tags/wrapper.tag

<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
  <jsp:doBody/>
</body></html>

Now in your example.jsp page:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>
    <h1>Welcome</h1>
</t:wrapper>

That does exactly what you think it does.


So, lets expand upon that to something a bit more general. WEB-INF/tags/genericpage.tag

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
  <body>
    <div id="pageheader">
      <jsp:invoke fragment="header"/>
    </div>
    <div id="body">
      <jsp:doBody/>
    </div>
    <div id="pagefooter">
      <jsp:invoke fragment="footer"/>
    </div>
  </body>
</html>

To use this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <p>Hi I'm the heart of the message</p>
    </jsp:body>
</t:genericpage>

What does that buy you? A lot really, but it gets even better...


WEB-INF/tags/userpage.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome ${userName}</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <jsp:doBody/>
    </jsp:body>
</t:genericpage>

To use this: (assume we have a user variable in the request)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    First Name: ${user.firstName} <br/>
    Last Name: ${user.lastName} <br/>
    Phone: ${user.phone}<br/>
  </p>
</t:userpage>

But it turns you like to use that user detail block in other places. So, we'll refactor it. WEB-INF/tags/userdetail.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>

First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>

Now the previous example becomes:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    <t:userdetail user="${user}"/>
  </p>
</t:userpage>

The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.

JSP Tag Files have pretty much usurped things like Tiles etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).

Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:

<t:table items="${actionBean.customerList}" var="obj" css_class="display">
  <t:col css_class="checkboxcol">
    <s:checkbox name="customerIds" value="${obj.customerId}"
                onclick="handleCheckboxRangeSelection(this, event);"/>
  </t:col>
  <t:col name="customerId" title="ID"/>
  <t:col name="firstName" title="First Name"/>
  <t:col name="lastName" title="Last Name"/>
  <t:col>
    <s:link href="/Customer.action" event="preEdit">
      Edit
      <s:param name="customer.customerId" value="${obj.customerId}"/>
      <s:param name="page" value="${actionBean.page}"/>
    </s:link>
  </t:col>
</t:table>

Of course the tags work with the JSTL tags (like c:if, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.

So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.

At a higher level, you can do sophisticated things like this table tag I have here.

Call break in nested if statements

But there is switch-case :)

switch (true) {
    case true:
        console.log("Yes, its ture :) Break from the switch-case");
        break;
    case false:
        console.log("Nope, but if the condition was set to false this would be used and then break");
        break;

    default:
        console.log("If all else fails");
        break;
}

inherit from two classes in C#

Do you mean you want Class C to be the base class for A & B in that case.

public abstract class C
{
    public abstract void Method1();

    public abstract void Method2();
}

public class A : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}


public class B : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}

How do you know a variable type in java?

I would like to expand on Martin's answer there...

His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

Martins Solution:

a.getClass().getName()

However, If you want it to work with anything you can do this:

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

I myself used it like this:

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

Using Generics:

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

How to apply CSS to iframe?

If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.

Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.

This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.

How to pick element inside iframe using document.getElementById

(this is to add to the chosen answer)

Make sure the iframe is loaded before you

contentWindow.document

Otherwise, your getElementById will be null.

PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe load before selecting the inner-iframe element.

Why isn't .ico file defined when setting window's icon?

You need to have favicon.ico in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:

from tkinter import *
root = Tk()

root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()

But this blows up with your same error:

from tkinter import *
root = Tk()

root.iconbitmap('py.ico')
root.mainloop()

Select element by exact match of its content

No, there's no jQuery (or CSS) selector that does that.

You can readily use filter:

$("p").filter(function() {
    return $(this).text() === "hello";
}).css("font-weight", "bold");

It's not a selector, but it does the job. :-)

If you want to handle whitespace before or after the "hello", you might throw a $.trim in there:

return $.trim($(this).text()) === "hello";

For the premature optimizers out there, if you don't care that it doesn't match <p><span>hello</span></p> and similar, you can avoid the calls to $ and text by using innerHTML directly:

return this.innerHTML === "hello";

...but you'd have to have a lot of paragraphs for it to matter, so many that you'd probably have other issues first. :-)

Python constructors and __init__

Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.

What you typically use them for is create variables for that object like this:

>>> class testing:
...     def __init__(self, init_value):
...         self.some_value = init_value

So what you could do then is to create an object from this class like this:

>>> testobject = testing(5)

The testobject will then have an object called some_value that in this sample will be 5.

>>> testobject.some_value
5

But you don't need to set a value for each object like i did in my sample. You can also do like this:

>>> class testing:
...     def __init__(self):
...         self.some_value = 5

then the value of some_value will be 5 and you don't have to set it when you create the object.

>>> testobject = testing()
>>> testobject.some_value
5

the >>> and ... in my sample is not what you write. It's how it would look in pyshell...

How to get access to job parameters from ItemReader, in Spring Batch?

Pretty late, but you can also do this by annotating a @BeforeStep method:

@BeforeStep
    public void beforeStep(final StepExecution stepExecution) {
        JobParameters parameters = stepExecution.getJobExecution().getJobParameters();
        //use your parameters
}

Why does "return list.sort()" return None, not the list?

The problem is here:

answer = newList.sort()

sort does not return the sorted list; rather, it sorts the list in place.

Use:

answer = sorted(newList)

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

Save Screen (program) output to a file

Existing screen log can be saved by :

Ctrl+A : hardcopy -h filename

How to decrypt hash stored by bcrypt

You're HASHING, not ENCRYPTING!

What's the difference?

The difference is that hashing is a one way function, where encryption is a two-way function.

So, how do you ascertain that the password is right?

Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt operation on the user input and compare the hashes. If they're identical, you accept the authentication.

Should you hash or encrypt passwords?

What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt) to gain that knowledge.

As your users probably use their passwords in more than one place, this will help to protect them.

JDBC connection to MSSQL server in windows authentication mode

After struggling a lot, I finally found a solution, here we go -

Download the file jtds-1.3.1.jar and ntlmauth.dll and save it in Program File -> Java -> JDK -> jre -> bin.

Then use the following code -

String pPSSDBDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(pPSSDBDriverName);
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://<ur_server:port>;UseNTLMv2=true;Domain=AD;Trusted_Connection=yes");
stmt = conn.createStatement();
String sql = " DELETE FROM <data> where <condition>;
stmt.executeUpdate(sql);

"Char cannot be dereferenced" error

I guess ch is a declared as char. Since char is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch).

Add a column to a table, if it does not already exist

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

How to backup MySQL database in PHP?

for using Cron Job, below is the php function

public function runback() {

    $filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';

    /*
     *  db backup
     */

    $command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass yourdb_name > $filename";
    system($command);
    if ($command == '') {
        /* no output is good */
        echo 'not done';
    } else {
       /* we have something to log the output here */
        echo 'done';
    }
}

There should not be any space between -u and username also no space between -p and password. CRON JOB command to run this script every sunday 8.30 am:

>> crontab -e

30 8 * * 7 curl -k https://www.websitename.com/takebackup

How to stretch in width a WPF user control to its window?

Does setting the HorizontalAlignment to Stretch, and the Width to Auto on the user control achieve the desired results?

How do I import a .bak file into Microsoft SQL Server 2012?

.bak is a backup file generated in SQL Server.

Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.

You restore database by using following command...

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery

You want to learn about how to restore .bak file follow the below link:

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

Filter data.frame rows by a logical condition

we can use data.table library

  library(data.table)
  expr <- data.table(expr)
  expr[cell_type == "hesc"]
  expr[cell_type %in% c("hesc","fibroblast")]

or filter using %like% operator for pattern matching

 expr[cell_type %like% "hesc"|cell_type %like% "fibroblast"]

Showing empty view when ListView is empty

I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.

The xml file:

<RelativeLayout
    android:id="@+id/header_main_page_clist1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:paddingBottom="10dp"
    android:background="#ffffff" >

    <ListView
        android:id="@+id/lv_msglist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/divider_color"
        android:dividerHeight="1dp" />

    <TextView
        android:id="@+id/emptyElement"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="NO MESSAGES AVAILABLE!"
        android:textColor="#525252"
        android:textSize="19.0sp"
        android:visibility="gone" />
</RelativeLayout>

The textView ("@+id/emptyElement") is the placeholder for the empty listview.

Here is the code for java page:

lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));

Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.

Output:

enter image description here

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

How to extract IP Address in Spring MVC Controller get call?

See below. This code works with spring-boot and spring-boot + apache CXF/SOAP.

    // in your class RequestUtil
    private static final String[] IP_HEADER_NAMES = { 
                                                        "X-Forwarded-For",
                                                        "Proxy-Client-IP",
                                                        "WL-Proxy-Client-IP",
                                                        "HTTP_X_FORWARDED_FOR",
                                                        "HTTP_X_FORWARDED",
                                                        "HTTP_X_CLUSTER_CLIENT_IP",
                                                        "HTTP_CLIENT_IP",
                                                        "HTTP_FORWARDED_FOR",
                                                        "HTTP_FORWARDED",
                                                        "HTTP_VIA",
                                                        "REMOTE_ADDR"
                                                    };

    public static String getRemoteIP(RequestAttributes requestAttributes)
    {
        if (requestAttributes == null)
        {
            return "0.0.0.0";
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String ip = Arrays.asList(IP_HEADER_NAMES)
            .stream()
            .map(request::getHeader)
            .filter(h -> h != null && h.length() != 0 && !"unknown".equalsIgnoreCase(h))
            .map(h -> h.split(",")[0])
            .reduce("", (h1, h2) -> h1 + ":" + h2);
        return ip + request.getRemoteAddr();
    }

    //... in service class:
    String remoteAddress = RequestUtil.getRemoteIP(RequestContextHolder.currentRequestAttributes());

:)

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

I want to calculate the distance between two points in Java

Unlike maths-on-paper notation, most programming languages (Java included) need a * sign to do multiplication. Your distance calculation should therefore read:

distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Or alternatively:

distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

SQL "select where not in subquery" returns no results

select *
from Common c
where not exists (select t1.commonid from table1 t1 where t1.commonid = c.commonid)
and not exists (select t2.commonid from table2 t2 where t2.commonid = c.commonid)

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

HTTP Ajax Request via HTTPS Page

From the javascript I tried from several ways and I could not.

You need an server side solution, for example on c# I did create an controller that call to the http, en deserialize the object, and the result is that when I call from javascript, I'm doing an request from my https://domain to my htpps://domain. Please see my c# code:

[Authorize]
public class CurrencyServicesController : Controller
{
    HttpClient client;
    //GET: CurrencyServices/Consultar?url=valores?moedas=USD&alt=json
    public async Task<dynamic> Consultar(string url)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("http://api.promasters.net.br/cotacao/v1/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;

        var FromURL = response.Content.ReadAsStringAsync().Result;

        return JsonConvert.DeserializeObject(FromURL);
    }

And let me show to you my client side (Javascript)

<script async>
$(document).ready(function (data) {

    var TheUrl = '@Url.Action("Consultar", "CurrencyServices")?url=valores';
    $.getJSON(TheUrl)
        .done(function (data) {
            $('#DolarQuotation').html(
                '$ ' + data.valores.USD.valor.toFixed(2) + ','
            );
            $('#EuroQuotation').html(
                '€ ' + data.valores.EUR.valor.toFixed(2) + ','
            );

            $('#ARGPesoQuotation').html(
                'Ar$ ' + data.valores.ARS.valor.toFixed(2) + ''
            );

        });       

});

I wish that this help you! Greetings

Various ways to remove local Git changes

For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.

This will stash all changes in {0} key and instantly drop it from {0}

git stash && git stash drop

What is the difference between hg forget and hg remove?

A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

How to list all the files in a commit?

$ git log 88ee8^..88ee8 --name-only --pretty="format:"

How to output numbers with leading zeros in JavaScript?

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

pad.zeros = new Array(5).join('0');
function pad(num, len) {
    var str = String(num),
        diff = len - str.length;
    if(diff <= 0) return str;
    if(diff > pad.zeros.length)
        pad.zeros = new Array(diff + 1).join('0');
    return pad.zeros.substr(0, diff) + str;
}

If the padding count is large and the function is called often enough, it actually outperforms the other methods...

Strip spaces/tabs/newlines - python

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Demo:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']

Use str.join on the returned list to get this output:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'

Making sure at least one checkbox is checked

if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
            || ($("#checkboxid3").is(":checked"))) {
 //Your Code here
}

You can use this code to verify that checkbox is checked at least one.

Thanks!!

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

WPF Timer Like C# Timer

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

If you are just testing your PL/SQL in SQL Plus you can direct it to a file like this:

spool output.txt
set serveroutput on

begin
  SELECT systimestamp FROM dual INTO time_db;
  DBMS_OUTPUT.PUT_LINE('time before procedure ' || time_db);
end;
/

spool off

IDEs like Toad and SQL Developer can capture the output in other ways, but I'm not familiar with how.

<img>: Unsafe value used in a resource URL context

Use Safe Pipe to fix it.

  • Create a safe pipe if u haven't any.

    ng g pipe safe

  • add Safe pipe in app.module.ts

    declarations: [SafePipe]

  • declare safe pipe in your ts

Import Dom Sanitizer and Safe Pipe to access url safely

import { Pipe, PipeTransform} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
  • Add safe with src url

    <img width="900" height="500" [src]="link | safe"/>

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

How to click or tap on a TextView text

in textView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:onClick="onClick"
    android:clickable="true"

You must also implement View.OnClickListener and in On Click method can use intent

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
           intent.setData(Uri.parse("https://youraddress.com"));    
            startActivity(intent);

I tested this solution works fine.

UnsatisfiedDependencyException: Error creating bean with name

If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

SOLUTION!

just set -config parameter location correctly, i.e :

openssl ....................  -config C:\bin\apache\apache2.4.9\conf\openssl.cnf

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

=> just what jay said just delete those registry entries which are pointing to other paths other than on c:\windows\system32.Those are the culprits of the error.I got those errors on my vb6 IDE and after deleting those anomalous registry entries the problem was fixed. works like a charm.

Run a Command Prompt command from Desktop Shortcut

  1. first goto that folder from where you to what to open command prompt where its desktop or some other location
  2. make a text file in that location just write cmd -c and save name.bat
  3. double click so your CMD path will be of that folder enter image description here

How to create windows service from java jar?

Another option is winsw: https://github.com/kohsuke/winsw/

Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples

I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.

PS the service is installed by running your-service.exe install

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

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

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

happy coding gl hf nerds

How to scroll to an element inside a div?

This is what has finally served me

/** Set parent scroll to show element
 * @param element {object} The HTML object to show
 * @param parent {object} The HTML object where the element is shown  */
var scrollToView = function(element, parent) {
    //Algorithm: Accumulate the height of the previous elements and add half the height of the parent
    var offsetAccumulator = 0;
    parent = $(parent);
    parent.children().each(function() {
        if(this == element) {
            return false; //brake each loop
        }
        offsetAccumulator += $(this).innerHeight();
    });
    parent.scrollTop(offsetAccumulator - parent.innerHeight()/2);
}

How to lock specific cells but allow filtering and sorting

Here is an article that explains the problem and solution with alot more detail:

Sorting Locked Cells in Protected Worksheets

The thing to understand is that the purpose of locking cells is to prevent them from being changed, and sorting permanently changes cell values. You can write a macro, but a much better solution is to use the "Allow Users to Edit Ranges" feature. This makes the cells editable so sorting can work, but because the cells are still technically locked you can prevent users from selecting them.

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Hey! I'm the developer of wxMathPlot! The project is active: I just took a long time to get a new release, because the code needed a partial rewriting to introduce new features. Take a look to the new 0.1.0 release: it is a great improvement from old versions. Anyway, it doesn't provide 3D (even if I always thinking about it...).

How may I reference the script tag that loaded the currently-executing script?

I have found the following code to be the most consistent, performant, and simple.

var scripts = document.getElementsByTagName('script');
var thisScript = null;
var i = scripts.length;
while (i--) {
  if (scripts[i].src && (scripts[i].src.indexOf('yourscript.js') !== -1)) {
    thisScript = scripts[i];
    break;
  }
}
console.log(thisScript);

How to get access token from FB.login method in javascript SDK

You can get access token using FB.getAuthResponse()['accessToken']:

FB.login(function(response) {
   if (response.authResponse) {
     var access_token =   FB.getAuthResponse()['accessToken'];
     console.log('Access Token = '+ access_token);
     FB.api('/me', function(response) {
     console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 }, {scope: ''});

Edit: Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse(); If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:

if (typeof(console) == "undefined") { console = {}; } 
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }

mingw-w64 threads: posix vs win32

Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads

From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.

How to get share counts using graph API

There is a ruby gem for it - SocialShares

Currently it supports following social networks:

  • facebook
  • twitter
  • google plus
  • reddit
  • linkedin
  • pinterest
  • stumbleupon
  • vkontakte
  • mail.ru
  • odnoklassniki

Usage:

:000 > url = 'http://www.apple.com/'
  => "http://www.apple.com/"
:000 > SocialShares.facebook url
  => 394927
:000 > SocialShares.google url
  => 28289
:000 > SocialShares.twitter url
  => 1164675
:000 > SocialShares.all url
  => {:vkontakte=>44, :facebook=>399027, :google=>28346, :twitter=>1836, :mail_ru=>37, :odnoklassniki=>1, :reddit=>2361, :linkedin=>nil, :pinterest=>21011, :stumbleupon=>43035}
:000 > SocialShares.selected url, %w(facebook google linkedin)
  => {:facebook=>394927, :google=>28289, :linkedin=>nil}
:000 > SocialShares.total url, %w(facebook google)
  => 423216
:000 > SocialShares.has_any? url, %w(twitter linkedin)
  => true

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

How to create materialized views in SQL Server?

Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.

If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.

That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.

I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them

getOutputStream() has already been called for this response

Add the following inside the end of the try/catch to avoid the error that appears when the JSP engine flushes the response via getWriter()

out.clear(); // where out is a JspWriter
out = pageContext.pushBody();

As has been noted, this isn't best practice, but it avoids the errors in your logs.

Case insensitive comparison of strings in shell script

All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):

if [ "${var1,,}" = "${var2,,}" ]; then
  echo ":)"
fi

All you're doing there is converting both strings to lowercase and comparing the results.

Git: How to pull a single file from a server repository in Git?

https://raw.githubusercontent.com/[USER-NAME]/[REPOSITORY-NAME]/[BRANCH-NAME]/[FILE-PATH]

Ex. https://raw.githubusercontent.com/vipinbihari/apana-result/master/index.php

Through this you would get the contents of an individual file as a row text. You can download that text with wget.

Ex. https://raw.githubusercontent.com/vipinbihari/apana-result/master/index.php

Remove all non-"word characters" from a String in Java, leaving accented characters?

At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:

import java.text.Normalizer;
import java.text.Normalizer.Form;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for String manipulation.
 * 
 * @author Stefan Haberl
 */
public abstract class TextUtils {
    private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
    private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
            "sz" };

    /**
     * Normalizes a String by removing all accents to original 127 US-ASCII
     * characters. This method handles German umlauts and "sharp-s" correctly
     * 
     * @param s
     *            The String to normalize
     * @return The normalized String
     */
    public static String normalize(String s) {
        if (s == null)
            return null;

        String n = null;

        n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
        n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");

        return n;
    }

    /**
     * Returns a clean representation of a String which might be used safely
     * within an URL. Slugs are a more human friendly form of URL encoding a
     * String.
     * <p>
     * The method first normalizes a String, then converts it to lowercase and
     * removes ASCII characters, which might be problematic in URLs:
     * <ul>
     * <li>all whitespaces
     * <li>dots ('.')
     * <li>(semi-)colons (';' and ':')
     * <li>equals ('=')
     * <li>ampersands ('&')
     * <li>slashes ('/')
     * <li>angle brackets ('<' and '>')
     * </ul>
     * 
     * @param s
     *            The String to slugify
     * @return The slugified String
     * @see #normalize(String)
     */
    public static String slugify(String s) {

        if (s == null)
            return null;

        String n = normalize(s);
        n = StringUtils.lowerCase(n);
        n = n.replaceAll("[\\s.:;&=<>/]", "");

        return n;
    }
}

Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.

HTH

EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Use jackson-bom which will have all the three jackson versions.i.e.jackson-annotations, jackson-core and jackson-databind. This will resolve the dependencies related to those versions

Get current date/time in seconds

I use this:

Math.round(Date.now() / 1000)

No need for new object creation (see doc Date.now())

Javascript how to split newline

You should parse newlines regardless of the platform (operation system) This split is universal with regular expressions. You may consider using this:

var ks = $('#keywords').val().split(/\r?\n/);

E.g.

"a\nb\r\nc\r\nlala".split(/\r?\n/) // ["a", "b", "c", "lala"]

How to find the port for MS SQL Server 2008?

I came across this because I just had problems creating a remote connection and couldn't understand why setting up 1433 port in firewall is not doing the job. I finally have the full picture now, so I thought I should share.

First of all is a must to enable "TCP/IP" using the SQL Server Configuration Manager under Protocols for SQLEXPRESS!

When a named instance is used ("SQLExpress" in this case), this will listen on a dynamic port. To find this dynamic port you have couple of options; to name a few:

  • checking ERRORLOG of SQL Server located in '{MS SQL Server Path}\{MS SQL Server instance name}\MSSQL\Log' (inside you'll find a line similar to this: "2013-07-25 10:30:36.83 Server Server is listening on [ 'any' <ipv4> 51118]" --> so 51118 is the dynamic port in this case.

  • checking registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\{MSSQL instance name}\MSSQLServer\SuperSocketNetLib\Tcp\IPAll, for my case TcpDynamicPorts=51118.

    Edit: {MSSQL instance name} is something like: MSSQL10_50.SQLEXPRESS, not only SQLEXPRESS

Of course, allowing this TCP port in firewall and creating a remote connection by passing in: "x.x.x.x,51118" (where x.x.x.x is the server ip) already solves it at this point.

But then I wanted to connect remotely by passing in the instance name (e.g: x.x.x.x\SQLExpress). This is when SQL Browser service comes into play. This is the unit which resolves the instance name into the 51118 port. SQL Browser service listens on UDP port 1434 (standard & static), so I had to allow this also in server's firewall.

To extend a bit the actual answer: if someone else doesn't like dynamic ports and wants a static port for his SQL Server instance, should try this link.

Insert default value when parameter is null

You can use default values for the parameters of stored procedures:

CREATE PROCEDURE MyTestProcedure ( @MyParam1 INT,
@MyParam2 VARCHAR(20) = ‘ABC’,
@MyParam3 INT = NULL)
AS
BEGIN
    -- Procedure body here

END

If @MyParam2 is not supplied, it will have the 'ABC' value...

Can I call methods in constructor in Java?

The constructor is called only once, so you can safely do what you want, however the disadvantage of calling methods from within the constructor, rather than directly, is that you don't get direct feedback if the method fails. This gets more difficult the more methods you call.

One solution is to provide methods that you can call to query the 'health' of the object once it's been constructed. For example the method isConfigOK() can be used to see if the config read operation was OK.

Another solution is to throw exceptions in the constructor upon failure, but it really depends on how 'fatal' these failures are.

class A
{
    Map <String,String> config = null;
    public A()
    {
        readConfig();
    }

    protected boolean readConfig()
    {
        ...
    }

    public boolean isConfigOK()
    {
        // Check config here
        return true;
    }
};

TypeError: 'list' object is not callable in python

Seems like you've shadowed the builtin name list pointing at a class by the same name pointing at its instance. Here is an example:

>>> example = list('easyhoss')  # here `list` refers to the builtin class
>>> list = list('abc')  # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss')  # here `list` refers to the instance
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'list' object is not callable

I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:

  1. Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.

  2. Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.

Here is a simple illustration.

>>> example = list("abc")  # Works fine
>>> 
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>> 
>>> example = list("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>> 
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name. 
>>> example = list("abc")  # It works.

So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.

You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).

If you want to know more about builtins, please read the answer by Christian Dean.

P.S. When you start an interactive Python session, you create a temporary module.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You won't be able to draw images directly from another server into a canvas and then use getImageData. It's a security issue and the canvas will be considered "tainted".

Would it work for you to save a copy of the image to your server using PHP and then just load the new image? For example, you could send the URL to the PHP script and save it to your server, then return the new filename to your javascript like this:

<?php //The name of this file in this example is imgdata.php

  $url=$_GET['url'];

  // prevent hackers from uploading PHP scripts and pwning your system
  if(!@is_array(getimagesize($url))){
    echo "path/to/placeholderImage.png";
    exit("wrong file type.");
  }

  $img = file_get_contents($url);

  $fn = substr(strrchr($url, "/"), 1);
  file_put_contents($fn,$img);
  echo $fn;

?>

You'd use the PHP script with some ajax javascript like this:

xi=new XMLHttpRequest();
xi.open("GET","imgdata.php?url="+yourImageURL,true);
xi.send();

xi.onreadystatechange=function() {
  if(xi.readyState==4 && xi.status==200) {
    img=new Image;
    img.onload=function(){ 
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    }
    img.src=xi.responseText;
  }
}

If you use getImageData on the canvas after that, it will work fine.

Alternatively, if you don't want to save the whole image, you could pass x & y coordinates to your PHP script and calculate the pixel's rgba value on that side. I think there are good libraries for doing that kind of image processing in PHP.

If you want to use this approach, let me know if you need help implementing it.

edit-1: peeps pointed out that the php script is exposed and allows the internet to potentially use it maliciously. there are a million ways to handle this, one of the simplest being some sort of URL obfuscation... i reckon secure php practices deserves a separate google ;P

edit-2: by popular demand, I've added a check to ensure it is an image and not a php script (from: PHP check if file is an image).

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

How to escape indicator characters (i.e. : or - ) in YAML

Quotes, but I prefer them on the just the value:

url: "http://www.example.com/"

Putting them across the whole line looks like it might cause problems.

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

Java - removing first character of a string

public String removeFirst(String input)
{
    return input.substring(1);
}

Check with jquery if div has overflowing elements

One method is to check scrollTop against itself. Give the content a scroll value larger than its size and then check to see if its scrollTop is 0 or not (if it is not 0, it has overflow.)

http://jsfiddle.net/ukvBf/

How to add a single item to a Pandas Series

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

how get yesterday and tomorrow datetime in c#

Today :

DateTime.Today

Tomorrow :

DateTime.Today.AddDays(1)

Yesterday :

DateTime.Today.AddDays(-1)

MySQL select 10 random rows from 600K rows fast

I've looked through all of the answers, and I don't think anyone mentions this possibility at all, and I'm not sure why.

If you want utmost simplicity and speed, at a minor cost, then to me it seems to make sense to store a random number against each row in the DB. Just create an extra column, random_number, and set it's default to RAND(). Create an index on this column.

Then when you want to retrieve a row generate a random number in your code (PHP, Perl, whatever) and compare that to the column.

SELECT FROM tbl WHERE random_number >= :random LIMIT 1

I guess although it's very neat for a single row, for ten rows like the OP asked you'd have to call it ten separate times (or come up with a clever tweak that escapes me immediately)

Export and import table dump (.sql) using pgAdmin

follow he steps. in pgadmin

host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.

note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/

enter image description here

Set cursor position on contentEditable <div>

Update

I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.

Previous answer

You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.

I might put something together to do this, will post back here if and when I do.

EDIT:

I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.

http://www.timdown.co.uk/code/selections/

Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.

I will write this up fully at some point soon.

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

Xcode 7.2 no matching provisioning profiles found

I've also the same problem, in Xcode 7.2

It solved by followings steps:-

1) Open Xcode preference,

2) Select the appropriate team,

3) Click the "View Details..".

4) In section "Signing Identities": click on "Reset" for each of them.

5) In section "Provisioning Profiles". Click on "Download All".

6) Click on "Done."

7) Go in Xcode, build settings, select it. In General tab, the issues should get removed.

8) Restart the Xcode.

9) Do the Final build.

That's all.

Reset push notification settings for app

The same tech note as refered to in the accepted answer (TN2265 - Troubleshooting Push Notifications) has since been updated with a solution for iOS 5 and above.

In short: create a backup and restore from it every time.

On iOS 5 and later, reset the push notifications permissions alert by restoring the device from a backup (r. 11450187). Here are the steps to do this efficiently:

  1. Use the Xcode Organizer to install your app on the device. The key is to install the app for the first time without running it.
  2. Use iTunes to back up the device.
  3. Run the app. The push notifications permissions alert will be presented.
  4. When you want to reset the push notifications permissions alert, restore the device from the backup you created in the first step.

SQL Server: Best way to concatenate multiple columns?

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')

How to convert a Bitmap to Drawable in android?

And you can try this:

public static Bitmap mirrorBitmap(Bitmap bInput)
    {
        Bitmap  bOutput;
        Matrix matrix = new Matrix();
        matrix.preScale(-1.0f, 1.0f);
        bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
        return bOutput;
    }

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

The answer posted here by simon-sarris helped me.

This helped me solve my issue.

The Visual Studio installer must have added an errant line to the registry.

open up regedit and take a look at this registry key:

enter image description here

See that key? The Content Type key? change its value from text/plain to text/javascript.

Finally chrome can breathe easy again.

I should note that neither Content Type nor PercievedType are there by default on Windows 7, so you could probably safely delete them both, but the minimum you need to do is that edit.

Anyway I hope this fixes it for you too!

Don't forget to restart your system after the changes.

Correct way to populate an Array with a Range in Ruby

You can create an array with a range using splat,

>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

using Kernel Array method,

Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

or using to_a

(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Best way of invoking getter by reflection

You can use Reflections framework for this

import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

jQuery: how to get which button was clicked upon form submission?

This one worked for me

$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);

}

CodeIgniter: Load controller within controller

Just to add more information to what Zain Abbas said:

Load the controller that way, and use it like he said:

$this->load->library('../controllers/instructor');

$this->instructor->functioname();

Or you can create an object and use it this way:

$this->load->library('../controllers/your_controller');

$obj = new $this->your_controller();

$obj->your_function();

Hope this can help.

How can I use std::maps with user-defined types as key?

You don't have to define operator< for your class, actually. You can also make a comparator function object class for it, and use that to specialize std::map. To extend your example:

struct Class1Compare
{
   bool operator() (const Class1& lhs, const Class1& rhs) const
   {
       return lhs.id < rhs.id;
   }
};

std::map<Class1, int, Class1Compare> c2int;

It just so happens that the default for the third template parameter of std::map is std::less, which will delegate to operator< defined for your class (and fail if there is none). But sometimes you want objects to be usable as map keys, but you do not actually have any meaningful comparison semantics, and so you don't want to confuse people by providing operator< on your class just for that. If that's the case, you can use the above trick.

Yet another way to achieve the same is to specialize std::less:

namespace std
{
    template<> struct less<Class1>
    {
       bool operator() (const Class1& lhs, const Class1& rhs) const
       {
           return lhs.id < rhs.id;
       }
    };
}

The advantage of this is that it will be picked by std::map "by default", and yet you do not expose operator< to client code otherwise.

Maintain the aspect ratio of a div with CSS

Well, we've recently received the ability to use the aspect-ratio property in CSS.

https://twitter.com/Una/status/1260980901934137345/photo/1

Note: Support is not the best yet ...

https://caniuse.com/#search=aspect-ratio

EDIT: Aspect ratio is now available !

https://web.dev/aspect-ratio/

ssl.SSLError: tlsv1 alert protocol version

I believe TLSV1_ALERT_PROTOCOL_VERSION is alerting you that the server doesn't want to talk TLS v1.0 to you. Try to specify TLS v1.2 only by sticking in these lines:

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

# Create HTTPS connection
c = HTTPSConnection("0.0.0.0", context=context)

Note, you may need sufficiently new versions of Python (2.7.9+ perhaps?) and possibly OpenSSL (I have "OpenSSL 1.0.2k 26 Jan 2017" and the above seems to work, YMMV)

How can I maintain fragment state when added to the back stack?

Perfect solution that find old fragment in stack and load it if exist in stack.

/**
     * replace or add fragment to the container
     *
     * @param fragment pass android.support.v4.app.Fragment
     * @param bundle pass your extra bundle if any
     * @param popBackStack if true it will clear back stack
     * @param findInStack if true it will load old fragment if found
     */
    public void replaceFragment(Fragment fragment, @Nullable Bundle bundle, boolean popBackStack, boolean findInStack) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        String tag = fragment.getClass().getName();
        Fragment parentFragment;
        if (findInStack && fm.findFragmentByTag(tag) != null) {
            parentFragment = fm.findFragmentByTag(tag);
        } else {
            parentFragment = fragment;
        }
        // if user passes the @bundle in not null, then can be added to the fragment
        if (bundle != null)
            parentFragment.setArguments(bundle);
        else parentFragment.setArguments(null);
        // this is for the very first fragment not to be added into the back stack.
        if (popBackStack) {
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } else {
            ft.addToBackStack(parentFragment.getClass().getName() + "");
        }
        ft.replace(R.id.contenedor_principal, parentFragment, tag);
        ft.commit();
        fm.executePendingTransactions();
    }

use it like

Fragment f = new YourFragment();
replaceFragment(f, null, boolean true, true); 

XPath: difference between dot and text()

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.

In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

Get current directory name (without full path) in a Bash script

echo "$PWD" | sed 's!.*/!!'

If you are using Bourne shell or ${PWD##*/} is not available.

What is the most effective way for float and double comparison?

The comparison with an epsilon value is what most people do (even in game programming).

You should change your implementation a little though:

bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}

Edit: Christer has added a stack of great info on this topic on a recent blog post. Enjoy.

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I did encounter the same problem while trying to read data from a Firebird Database. After many hours of searching, I found out that the problem was caused by an error I made in the query. Fixing it made it work perfectly. It had nothing to do with the version of the Framework

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
    <table>
        <tbody>
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>
            </tr>
        </tbody>
    </table>
</div>

How to trim a string after a specific character in java

How about

Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33

How to count the number of set bits in a 32-bit integer?

I think the Brian Kernighan's method will be useful too... It goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.

int countSetBits(unsigned int n) { 
    unsigned int n; // count the number of bits set in n
    unsigned int c; // c accumulates the total bits set in n
    for (c=0;n>0;n=n&(n-1)) c++; 
    return c; 
}

Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)"

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

I had quite a number of these exceptions thrown, the fastest and easiest way I found to solve them was to find unique values in the exceptions which I then searched for in the storyboard source code. This helped me to find the actual view(s) and constraint(s) causing the problem (I use meaningful userLabels on all of the views, which makes it a lot easier to track the constraints and views)...

So, using the above exceptions I would open the storyboard as "source code" in xcode (or another editor) and look for something I can find...

<NSLayoutConstraint:0x72bf860 V:[UILabel:0x72bf7c0(17)]> 

.. this looks like a vertical (V) constraint on a UILabel with a value of (17).

Looking through the exceptions I also find

<NSLayoutConstraint:0x72c22b0 V:[UILabel:0x72bf7c0]-(NSSpace(8))-[UIButton:0x886efe0]>

Which looks like the UILabel(0x72bf7c0) is close to a UIButton(0x886efe0) with some vertical spacing (8)..

That will hopefully be enough for me to find the specific views in the storyboard source code (probably by searching the text for "17" initially), or at least a few likely candidates. From there I should be able to actually figure out which views these are in the storyboard which will make it a lot easier to identify the problem (look for "duplicated" pinning or pinning that conflicts with size constraints).

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Apple has changed the rules on this. I read through all the Apple docs and as many of the US export regs as I could find.

My view on this was until recently even using HTTPS for most apps meant Apple would require the export certificate. Some apps such as banking would be OK but for many apps they did not fall into the excempt category which is very, very broad.

However Apple has now introduced a getout under the exempt category for apps that JUST use https. I do not know when they did this but I think it was either Dec 2016 or Jan 2017. We are now submitting our apps without the certificate from the US Govt.

How to define a connection string to a SQL Server 2008 database?

You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:

Integrated Security = True;

If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:

User ID = "username"; Password = "password";

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

How do I enable C++11 in gcc?

H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.

Here's a simple one :

CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog

SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)

all: $(OBJ)
    $(CXX) -o $(BIN) $^

%.o: %.c
    $(CXX) $@ -c $<

clean:
    rm -f *.o
    rm $(BIN)

It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.

Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.

ASP.NET MVC get textbox input value

Try This.

View:

@using (Html.BeginForm("Login", "Accounts", FormMethod.Post)) 
{
   <input type="text" name="IP" id="IP" />
   <input type="text" name="Name" id="Name" />

   <input type="submit" value="Login" />
}

Controller:

[HttpPost]
public ActionResult Login(string IP, string Name)
{
    string s1=IP;//
    string s2=Name;//
}

If you can use model class

[HttpPost]
public ActionResult Login(ModelClassName obj)
{
    string s1=obj.IP;//
    string s2=obj.Name;//
}

How do I look inside a Python object?

Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:

/usr/lib/python2.5/string.py

I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.

How do I catch an Ajax query post error?

Since jQuery 1.5 you can use the deferred objects mechanism:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

Another way is using .ajax:

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});

How to create a bash script to check the SSH connection?

I feel like you're trying to solve the wrong problem here. Shouldn't you be trying to make the ssh daemons more stable? Try running something like monit, which will check to see if the daemon is running and restart it if it isn't (giving you time to find the root problem behind sshd shutting down on you). Or is the network service troublesome? Try looking at man ifup. Does the Whole Damn Thing just like to shut down on you? Well, that's a bigger problem ... try looking at your logs (start with syslog) to find hardware failures or services that are shutting your boxen down (maybe a temperature monitor?).

Making your scripts fault tolerant is great, but you might also want to make your boxen fault tolerant.

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

The best answer I have ever seen is How to run 32-bit applications on Ubuntu 64-bit?

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
sudo ./adb

Moment.js transform to date object

As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.

You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().

Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().

Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:

momentObj.format("YYYY-MM-DD HH:mm:ss")

Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.

A couple of other little things:

  • While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.

  • Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.

Cut Corners using CSS

If the parent element has a solid color background, you can use pseudo-elements to create the effect:

_x000D_
_x000D_
div {_x000D_
    height: 300px;_x000D_
    background: red;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
div:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 0; right: 0;_x000D_
    border-top: 80px solid white;_x000D_
    border-left: 80px solid red;_x000D_
    width: 0;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/2bZAW/


P.S. The upcoming border-corner-shape is exactly what you're looking for. Too bad it might get cut out of the spec, and never make it into any browsers in the wild :(

IntelliJ show JavaDocs tooltip on mouse over

It is possible in 12.1.

Find idea.properties in the BIN folder inside of wherever your IDE is installed, e.g. C:\Program Files (x86)\JetBrains\IntelliJ\bin

Add a new line to the end of that file:

auto.show.quick.doc=true

Start IDEA and just hover your mouse over something:

enter image description here

Swift UIView background color opacity

in Swift 3.0

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

This works for me in xcode 8.2.

It may helps you.

How to query values from xml nodes?

SELECT  b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);

Demo: SQLFiddle

Run/install/debug Android applications over Wi-Fi?

1- For this I am considering you have already installed the latest version of Android studio. If not you can download it from here.

2 - You can set the platform tools path in environment variable (optional).

3 - Make sure your device and pc connected to same network.

  • plug in the data cable from pc to device.

  • Now, type adb tcpip 5555

  • remove data cable.

  • Then type adb connect 192.168.43.95

  • here 5555 is the port number and 192.168.43.95 is the ip address of the mobile device you can get id address from the mobile settings .

  • Then go to About device and go to status you can see the ip address of the device.

  • You can connect multiple device from different ports which can give ease in development.

  • Or you can go to this link for brief description with screenshots. http://blogssolutions.co.in/connect-your-android-phone-wirelessly-by-adb

SQL 'LIKE' query using '%' where the search criteria contains '%'

If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]

... where name like '%' + replace(search_criteria, '%', '[%]') + '%'

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

How to identify all stored procedures referring a particular table

In management studio you can just right click to table and click to 'View Dependencies' enter image description here

than you can see a list of Objects that have dependencies with your table :enter image description here

Convert object of any type to JObject with Json.NET

This will work:

var cycles = cycleSource.AllCycles();

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var vm = new JArray();

foreach (var cycle in cycles)
{
    var cycleJson = JObject.FromObject(cycle);
    // extend cycleJson ......
    vm.Add(cycleJson);
}

return vm;

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

php artisan dump-autoload was deprecated on Laravel 5, so you need to use composer dump-autoload

<DIV> inside link (<a href="">) tag

I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...

How to remove leading zeros from alphanumeric text?

I made some benchmark tests and found, that the fastest way (by far) is this solution:

    private static String removeLeadingZeros(String s) {
      try {
          Integer intVal = Integer.parseInt(s);
          s = intVal.toString();
      } catch (Exception ex) {
          // whatever
      }
      return s;
    }

Especially regular expressions are very slow in a long iteration. (I needed to find out the fastest way for a batchjob.)

Where does Console.WriteLine go in ASP.NET?

The TraceContext object in ASP.NET writes to the DefaultTraceListener which outputs to the host process’ standard output. Rather than using Console.Write(), if you use Trace.Write, output will go to the standard output of the process.

You could use the System.Diagnostics.Process object to get the ASP.NET process for your site and monitor standard output using the OutputDataRecieved event.

How to wait in a batch script?

I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html

System.Runtime.InteropServices.COMException (0x800A03EC)

Some googling reveals that potentially you've got a corrupt file:

http://bitterolives.blogspot.com/2009/03/excel-interop-comexception-hresult.html

and that you can tell excel to open it anyway with the CorruptLoad parameter, with something like...

Workbook workbook = excelApplicationObject.Workbooks.Open(path, CorruptLoad: true);

Mounting multiple volumes on a docker container?

You can have Read only or Read and Write only on the volume

docker -v /on/my/host/1:/on/the/container/1:ro \

docker -v /on/my/host/2:/on/the/container/2:rw \

How to check java bit version on Linux?

Works for every binary, not only java:

file - < $(which java) # heavyly bashic

cat `which java` | file - # universal

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

Here are two approaches:

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%

::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%


::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Unable to resolve host "<insert URL here>" No address associated with hostname

This error because of you host cann't be translate to IP addresses via DNS.

Solve of this problem :

1- Make sure you connect to the internet (check quality of network).

2- Make sure you take proper permission to access network

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence