Programs & Examples On #Lightweight processes

How to Copy Text to Clip Board in Android?

int sdk = android.os.Build.VERSION.SDK_INT;

    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText("" + yourMessage.toString());
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("message", "" + yourMessage.toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    }

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a) 
{
    return a | ' ';  
}

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

OpenCV NoneType object has no attribute shape

I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder. enter image description here

How do you check what version of SQL Server for a database using TSQL?

Try

SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber

For more information see: Querying for version/edition info

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

How to remove line breaks (no characters!) from the string?

$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";

echo str_replace(array("\n", "\r"), '', $str);  // echo $str in a single line

Passing multiple variables to another page in url

Use & for this. Using & you can put as many variables as you want!

$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

Change link color of the current page with CSS

Best and easiest solution:

For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:

<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;} 
</style>

For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.

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

In my case I created an async test method which returned void. Returning of Task instead of void solved the issue.

How to use a Bootstrap 3 glyphicon in an html select

To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.

<select class="form-control glyphicon">
    <option value="">&#x2212; &#x2212; &#x2212; Hello</option>
    <option value="glyphicon-list-alt">&#xe032; Text</option>
</select>

Here's a list of the icons with their unicode:

http://glyphicons.bootstrapcheatsheets.com/

SQL "IF", "BEGIN", "END", "END IF"?

If this is MS Sql Server then what you have should work fine... In fact, technically, you don;t need the Begin & End at all, snce there's only one statement in the begin-End Block... (I assume @Classes is a table variable ?)

If @Term = 3
   INSERT INTO @Classes
    SELECT                  XXXXXX  
     FROM XXXX blah blah blah
-- -----------------------------

 -- This next should always run, if the first code did not throw an exception... 
 INSERT INTO @Classes    
 SELECT XXXXXXXX        
 FROM XXXXXX (more code)

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

What function is to replace a substring from a string in C?

You could build your own replace function using strstr to find the substrings and strncpy to copy in parts to a new buffer.

Unless what you want to replace_with is the same length as what you you want to replace, then it's probably best to use a new buffer to copy the new string to.

MAMP mysql server won't start. No mysql processes are running

What worked for me was:

I had a process called "mysqld" running even when MAMP had been quit. I force quit the process, restarted MAMP and it worked again.

React.js, wait for setState to finish before triggering a function?

setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

// Form Input
this.setState(
  {
    originId: input.originId,
    destinationId: input.destinationId,
    radius: input.radius,
    search: input.search
  },
  this.findRoutes         // here is where you put the callback
);

Notice the call to findRoutes is now inside the setState() call, as the second parameter.
Without () because you are passing the function.

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

Heroku deployment error H10 (App crashed)

I encountered the same problem today. I did heroku run rake db:migrate though I migrated the model before, and the app doesn't crash.

pythonic way to do something N times without an index variable?

I just use for _ in range(n), it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.

How do you change text to bold in Android?

You can use this for font

create a Class Name TypefaceTextView and extend the TextView

private static Map mTypefaces;

public TypefaceTextView(final Context context) {
    this(context, null);
}

public TypefaceTextView(final Context context, final AttributeSet attrs) {
    this(context, attrs, 0);
}

public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);
    if (mTypefaces == null) {
        mTypefaces = new HashMap<String, Typeface>();
    }

    if (this.isInEditMode()) {
        return;
    }

    final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
    if (array != null) {
        final String typefaceAssetPath = array.getString(
                R.styleable.TypefaceTextView_customTypeface);

        if (typefaceAssetPath != null) {
            Typeface typeface = null;

            if (mTypefaces.containsKey(typefaceAssetPath)) {
                typeface = mTypefaces.get(typefaceAssetPath);
            } else {
                AssetManager assets = context.getAssets();
                typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                mTypefaces.put(typefaceAssetPath, typeface);
            }

            setTypeface(typeface);
        }
        array.recycle();
    }
}

paste the font in the fonts folder created in the asset folder

<packagename.TypefaceTextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1.5"
        android:gravity="center"
        android:text="TRENDING TURFS"
        android:textColor="#000"
        android:textSize="20sp"
        app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**

Place the lines in the parent layout in the xml

 xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"

Set maxlength in Html Textarea

As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea has newline characters, at least on Windows.

I've change his answer slightly thus:

$(function() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        //I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
        //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
        var newlines = ($(this).val().match(/\n/g) || []).length
        if ($(this).val().length + newlines > maxLength) {
            $(this).val($(this).val().substring(0, maxLength - newlines));
        }
    })
});

Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.

How to check if two arrays are equal with JavaScript?

Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:

[1, 2, 3].toString() == [1, 2, 3].toString()
true
[1, 2, 3,].toString() == [1, 2, 3].toString()
true
[1,2,3].toString() == [1, 2, 3].toString()
true

However, this doesn't work for mode advanced cases such as:

[[1,2],[3]].toString() == [[1],[2,3]].toString()
true

It depends what you need.

Get Enum from Description attribute

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}

Usage:

var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");

mysql.h file can't be found

For CentOS/RHEL:

yum install mysql-devel -y

How to load local file in sc.textFile, instead of HDFS

This has been discussed into spark mailing list, and please refer this mail.

You should use hadoop fs -put <localsrc> ... <dst> copy the file into hdfs:

${HADOOP_COMMON_HOME}/bin/hadoop fs -put /path/to/README.md README.md

jquery smooth scroll to an anchor?

Here is how I do it:

    var hashTagActive = "";
    $(".scroll").on("click touchstart" , function (event) {
        if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
            event.preventDefault();
            //calculate destination place
            var dest = 0;
            if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                dest = $(document).height() - $(window).height();
            } else {
                dest = $(this.hash).offset().top;
            }
            //go to destination
            $('html,body').animate({
                scrollTop: dest
            }, 2000, 'swing');
            hashTagActive = this.hash;
        }
    });

Then you just need to create your anchor like this:

<a class="scroll" href="#destination1">Destination 1</a>

You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.

To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on "Use Project Settings" and disable the ones that you do not wish for.

Also, are you sure you are compiling with the C++11 compiler?

Callback after all asynchronous forEach callbacks are completed

Hope this will fix your problem, i usually work with this when i need to execute forEach with asynchronous tasks inside.

foo = [a,b,c,d];
waiting = foo.length;
foo.forEach(function(entry){
      doAsynchronousFunction(entry,finish) //call finish after each entry
}
function finish(){
      waiting--;
      if (waiting==0) {
          //do your Job intended to be done after forEach is completed
      } 
}

with

function doAsynchronousFunction(entry,callback){
       //asynchronousjob with entry
       callback();
}

Dots in URL causes 404 with ASP.NET mvc and IIS

I got this working by editing my site's HTTP handlers. For my needs this works well and resolves my issue.

I simply added a new HTTP handler that looks for specific path criteria. If the request matches it is correctly sent to .NET for processing. I'm much happier with this solution that the URLRewrite hack or enabling RAMMFAR.

For example to have .NET process the URL www.example.com/people/michael.phelps add the following line to your site's web.config within the system.webServer / handlers element:

<add name="ApiURIs-ISAPI-Integrated-4.0"
     path="/people/*"
     verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />

Edit

There are other posts suggesting that the solution to this issue is RAMMFAR or RunAllManagedModulesForAllRequests. Enabling this option will enable all managed modules for all requests. That means static files such as images, PDFs and everything else will be processed by .NET when they don't need to be. This options is best left off unless you have a specific case for it.

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

Checking the install state for the product via MsiQueryProductState is pretty much equivalent to checking the registry directly, but you still need the GUID for the ProductCode.

As mentioned elsewhere, one drawback with these approaches is that each update has its own ProductCode!

Thankfully, MSI provides an UpgradeCode which identifies a 'family' of products. You can use orca to open up one of the MSIs to extract this information. For example, the UpgradeCode for VS2015's redistributable is {65E5BD06-6392-3027-8C26-853107D3CF1A}

You can use MsiEnumRelatedProducts to get all Product IDs for that UpgradeCode. In practice, since each redist update replaces the previous one, this will only yield one ProductCode - such as {B5FC62F5-A367-37A5-9FD2-A6E137C0096F} for VS2015 Update 2 x86.

Regardless, you can then check the version via MsiGetProductInfo(productCode, INSTALLPROPERTY_VERSIONSTRING, ...) or similar functions to compare with the version you want, eg to check for an equivalent or later version.

Note that within a C++ application, you can also use _VC_CRT_MAJOR_VERSION, _VC_CRT_MINOR_VERSION, _VC_CRT_BUILD_VERSION if you #include <crtversion.h> -- this way you can determine calculate the CRT version that your binary was built with.

Understanding repr( ) function in Python

The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?

I'm not sure what you're asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr.

Also note that the eval(repr(x)) == x analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr output.

How can I remount my Android/system as read-write in a bash script using adb?

I could not get the mount command to work without specifying the dev block to mount as /system

#cat /proc/mounts returns ( only the system line here )
/dev/stl12 /system rfs ro,relatime,vfat,log_off,check=no,gid/uid/rwx,iocharset=utf8 0 0

so my working command is
mount -o rw,remount -t rfs /dev/stl12 /system

Swift - iOS - Dates and times in different format

Current date time to formated string:

let currentDate = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM

More Date Time Formats

Failed to execute removeChild on Node

I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine

Graphviz's executables are not found (Python 3.4)

I also had this problem on Ubuntu 16.04.

Fixed by running sudo apt-get install graphviz in addition to the pip install I had already performed.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...

Good luck!

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

All of the answers here use the Class.forName("my.vandor.Driver"); line to load the driver.

As an (better) alternative you can use the DriverManager helper class which provides you with a handful of methods to handle your JDBC driver/s.

You might want to

  1. Use DriverManager.registerDriver(driverObject); to register your driver to it's list of drivers

Registers the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager. If the driver is currently registered, no action is taken

  1. Use DriverManager.deregisterDriver(driverObject); to remove it.

Removes the specified driver from the DriverManager's list of registered drivers.

Example:

Driver driver = new oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
// ... 
// and when you don't need anything else from the driver
DriverManager.deregisterDriver(driver);

or better yet, use a DataSource

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to replace all spaces in a string

I came across this as well, for me this has worked (covers most browsers):

myString.replace(/[\s\uFEFF\xA0]/g, ';');

Inspired by this trim polyfill after hitting some bumps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

Bootstrap full responsive navbar with logo or brand name text

I set .navbar-brand { min-height: inherit } which solved the issue for me (thanks @creimers for inspiration).

Can iterators be reset in Python?

For small files, you may consider using more_itertools.seekable - a third-party tool that offers resetting iterables.

Demo

import csv

import more_itertools as mit


filename = "data/iris.csv"
with open(filename, "r") as f:
    reader = csv.DictReader(f)
    iterable = mit.seekable(reader)                    # 1
    print(next(iterable))                              # 2
    print(next(iterable))
    print(next(iterable))

    print("\nReset iterable\n--------------")
    iterable.seek(0)                                   # 3
    print(next(iterable))
    print(next(iterable))
    print(next(iterable))

Output

{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}

Reset iterable
--------------
{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}

Here a DictReader is wrapped in a seekable object (1) and advanced (2). The seek() method is used to reset/rewind the iterator to the 0th position (3).

Note: memory consumption grows with iteration, so be wary applying this tool to large files, as indicated in the docs.

.htaccess not working apache

For completeness, if "AllowOverride All" doesn't fix your problem, you could debug this problem using:

  1. Run apachectl -S and see if you have more than one namevhost. It might be that httpd is looking for .htaccess of another DocumentRoot.

  2. Use strace -f apachectl -X and look for where it's loading (or not loading) .htaccess from.

How can I close a dropdown on click outside?

I've done it this way.

Added an event listener on document click and in that handler checked if my container contains event.target, if not - hide the dropdown.

It would look like this.

@Component({})
class SomeComponent {
    @ViewChild('container') container;
    @ViewChild('dropdown') dropdown;

    constructor() {
        document.addEventListener('click', this.offClickHandler.bind(this)); // bind on doc
    }

    offClickHandler(event:any) {
        if (!this.container.nativeElement.contains(event.target)) { // check click origin
            this.dropdown.nativeElement.style.display = "none";
        }
    }
}

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

When should you use a class vs a struct in C++?

I never use "struct" in C++.

I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.

It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.

E.g.

class PublicInputData {
    //data members
 };

How to import and use image in a Vue single file component?

It is heavily suggested to make use of webpack when importing pictures from assets and in general for optimisation and pathing purposes

If you wish to load them by webpack you can simply use :src='require('path/to/file')' Make sure you use : otherwise it won't execute the require statement as Javascript.

In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"

Why the following is generally considered bad practice:

<template>
  <div id="app">
    <img src="./assets/logo.png">
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</style> 

When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static folder and use: <img src="./static/logo.png">

Pandas: Return Hour from Datetime Column Directly

Assuming timestamp is the index of the data frame, you can just do the following:

hours = sales.index.hour

If you want to add that to your sales data frame, just do:

import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)

Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:

hours = sales['date'].hour

Edit2: If you want to adjust a column in your data frame you have to include dt:

sales['datehour'] = sales['date'].dt.hour

ReactJS SyntheticEvent stopPropagation() only works with React events?

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

Working JSFiddle with the fixes from below.

React Stop Propagation on jQuery Event

Use Event.stopImmediatePropagation to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
},
  • Caveat: Listeners are called in the order in which they are bound. React must be initialized before other code (jQuery here) for this to work.

jQuery Stop Propagation on React Event

Your jQuery code uses event delegation as well, which means calling stopPropagation in the handler is not stopping anything; the event has already propagated to document, and React's listener will be triggered.

// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){
    e.stopPropagation();
});

To prevent propagation beyond the element, the listener must be bound to the element itself:

// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){
    e.stopPropagation();
});

Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.

JSON Structure for List of Objects

The second is almost correct:

{
    "foos" : [{
        "prop1":"value1",
        "prop2":"value2"
    }, {
        "prop1":"value3", 
        "prop2":"value4"
    }]
}

How to access environment variable values?

You can also try this

First, install python-decouple

pip install python-decouple

import it in your file

from decouple import config

Then get the env variable

SECRET_KEY=config('SECRET_KEY')

Read more about the python library here

How can I check if an element exists in the visible DOM?

this condition chick all cases.

_x000D_
_x000D_
function del() {_x000D_
//chick if dom has this element _x000D_
//if not true condition means null or undifind or false ._x000D_
_x000D_
if (!document.querySelector("#ul_list ")===true){_x000D_
_x000D_
// msg to user_x000D_
    alert("click btn load ");_x000D_
_x000D_
// if console chick for you and show null clear console._x000D_
    console.clear();_x000D_
_x000D_
// the function will stop._x000D_
    return false;_x000D_
}_x000D_
_x000D_
// if its true function will log delet ._x000D_
console.log("delet");_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

iPad/iPhone hover problem causes the user to double click a link

cduruk's solution was quite effective, but caused problems on a few parts of my site. Because I was already using jQuery to add the CSS hover class, the easiest solution was to simply not add the CSS hover class on mobile devices (or more precisely, to ONLY add it when NOT on a mobile device).

Here was the general idea:

var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);

if (!(ios)) {
    $(".portfolio-style").hover(
        function(){
            $(this).stop().animate({opacity: 1}, 100);
            $(this).addClass("portfolio-red-text");
        },
        function(){
            $(this).stop().animate({opacity: 0.85}, 100);
            $(this).removeClass("portfolio-red-text");
        }
    );
}

*code reduced for illustrative purposes

Can not connect to local PostgreSQL

I had this problem plaguing me, and upon further investigation (running rake db:setup), I saw that rails was trying to connect to a previously used postgres instance - one which was stored in env variables as DATABASE_URL.

The fix: unset DATABASE_URL

source: https://stackoverflow.com/a/17420624/2577622

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Let's say you have the DLLs build for both platforms, and they are in the following location:

C:\whatever\x86\whatever.dll
C:\whatever\x64\whatever.dll

You simply need to edit your .csproj file from this:

<HintPath>C:\whatever\x86\whatever.dll</HintPath>

To this:

<HintPath>C:\whatever\$(Platform)\whatever.dll</HintPath>

You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

What is the difference between null=True and blank=True in Django?

It's crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.

When it comes to null and blank, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:

  • null=False, blank=False: This is the default configuration and means that the value is required in all circumstances.

  • null=True, blank=True: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)

  • null=False, blank=True: This means that the form doesn't require a value but the database does. There are a number of use cases for this:

    • The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value.

    • Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don't want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False).

    • Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations.

  • null=True, blank=False: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it:

    • It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn't need the same stringent validation that you want to require of a human editor.

    • Another use case that I've seen is when you have a ForeignKey for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

There are two ways to resolve this error:

  1. Include /etc/apache2/httpd.conf

    Add the above line in file /etc/apache2/apache2.conf

  2. Add this line at the end of the file /etc/apache2/apache2.conf:

    ServerName localhost

How to change the name of an iOS app?

I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.

http://github.com/ytbryan/rename

NOTE: you will need to manually change the scheme's name.

How to display custom view in ActionBar?

I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.

You'll need to set the LayoutParams.FILL_PARENT when adding the view:

//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout); 

This way it completely fills the available space. (You may need to use Tomik's solution too).

Max length UITextField

You need to check whether the existing string plus the input is greater than 10.

   func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,    replacementString string: String!) -> Bool {
      NSUInteger newLength = textField.text.length + string.length - range.length;
      return !(newLength > 10)
   }

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Thanks to Damian...

TCP/IP Named Pipes ... both enabled

Web Config....(for localhost)

<add name="FooData" connectionString="Data Source=localhost\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

Playing a MP3 file in a WinForm application

The link below, gives a very good tutorial, about playing mp3 files from a windows form with c#:

http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c

This link will lead you to a topic, which contains a lot information about how to play an mp3 song, using Windows forms. It also contains a lot of other projects, trying to achieve the same thing:

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/3dbfb9a3-4e14-41d1-afbb-1790420706fe

For example use this code for .mp3:

WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

wplayer.URL = "My MP3 file.mp3";
wplayer.Controls.Play();

Then only put the wplayer.Controls.Play(); in the Button_Click event.

For example use this code for .wav:

System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.SoundLocation = "Sound.wav";
player.Play();

Put the player.Play(); in the Button_Click event, and it will work.

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

c# datagridview doubleclick on row with FullRowSelect

I think you are looking for this: RowHeaderMouseDoubleClick event

private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}

to get the row index:

int indice = e.RowIndex

flutter run: No connected devices

I ran mine with Genymotion, probably the best for Flutter.

Setting up is less painful and

Make sure setting ADB under

enter image description here

--YOUR ANDROID SDK PATH --

Mine is C:\Users\user\AppData\Local\Android\Sdk

Insert HTML with React Variable Statements (JSX)

Note that dangerouslySetInnerHTML can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.

It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.

Example:

import DOMPurify from 'dompurify'

const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
    );
}

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

Xcode is not currently available from the Software Update server

I had to run Xcode.app and agree to the License Agreement

Setup: Brand new MacBook with Mavericks, then brew install and other c/l type things 'just work'.

How to access global variables

I suggest use the common way of import.

First I will explain the way it called "relative import" maybe this way cause of some error

Second I will explain the common way of import.

FIRST:

In go version >= 1.12 there is some new tips about import file and somethings changed.

1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"

2- You have to use uppercase when you want to import a file!

3- Use Uppercase for variables, structures and functions that you want to import in another files

Notice: There is no way to import the main.go in another file.

file directory is:

root
|_____main.go
|_____model
          |_____example.go

this is a example.go:

package model

import (
    "time"
)

var StartTime = time.Now()

and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase

package main

import (
    Mod "./model"
    "fmt"
)

func main() {
    fmt.Println(Mod.StartTime)
}

NOTE!!!

NOTE: I don't recommend this this type of import!

SECOND:

(normal import)

the better way import file is:

your structure should be like this:

root
|_____github.com
         |_________Your-account-name-in-github
         |                |__________Your-project-name
         |                                |________main.go
         |                                |________handlers
         |                                |________models
         |               
         |_________gorilla
                         |__________sessions

and this is a example:

package main

import (
    "github.com/gorilla/sessions"
)

func main(){
     //you can use sessions here
}

so you can import "github.com/gorilla/sessions" in every where that you want...just import it.

How to exit from the application and show the home screen?

System.exit(0);

Is probably what you are looking for. It will close the entire application and take you to the home Screen.

Android "hello world" pushnotification example

you can follow this tutorial

http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/

it helped me to do a push notification; or you can follow this other tutorial

http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html

but it's in spanish but you can download the code.

Convert String into a Class Object

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

Setting the value of checkbox to true or false with jQuery

var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );

This will set the value of the checkbox to "true" or "false" (value property is a string), depending whether it's unchecked or checked.

Works in jQuery >= 1.0

Getting realtime output using subprocess

You can try this:

import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

If you use readline instead of read, there will be some cases where the input message is not printed. Try it with a command the requires an inline input and see for yourself.

How can I find my php.ini on wordpress?

Okay. Answer for self hosted wordpress installations - you'll have to find the file yourself. For my WordPres site I use nginx with php7.3-fpm.

Running php -i | grep ini from console gives me several lines including: Loaded Configuration File => /etc/php/7.3/cli/php.ini. This is ini configuration when running php command from command line, a.k.a. cli.

Then looking around I see there is also a file: /etc/php/7.3/fpm/php.ini I use FPM service so that is it! I edit it and THEN reload the service to apply my changes using: service php7.3-fpm reload.

That was it. Now I can upload bigger files to my WordPress. Good luck

Difference between style = "position:absolute" and style = "position:relative"

You'll definitely want to check out this positioning article from 'A List Apart'. Helped demystify CSS positioning (which seemed insane to me, prior to this article).

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

fork() child and parent processes

It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0

Try something like this:

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );

How do I enable MSDTC on SQL Server?

I've found that the best way to debug is to use the microsoft tool called DTCPing

  1. Copy the file to both the server (DB) and the client (Application server/client pc)
    • Start it at the server and the client
    • At the server: fill in the client netbios computer name and try to setup a DTC connection
    • Restart both applications.
    • At the client: fill in the server netbios computer name and try to setup a DTC connection

I've had my fare deal of problems in our old company network, and I've got a few tips:

  • if you get the error message "Gethostbyname failed" it means the computer can not find the other computer by its netbios name. The server could for instance resolve and ping the client, but that works on a DNS level. Not on a netbios lookup level. Using WINS servers or changing the LMHOST (dirty) will solve this problem.
  • if you get an error "Acces Denied", the security settings don't match. You should compare the security tab for the msdtc and get the server and client to match. One other thing to look at is the RestrictRemoteClients value. Depending on your OS version and more importantly the Service Pack, this value can be different.
  • Other connection problems:
    • The firewall between the server and the client must allow communication over port 135. And more importantly the connection can be initiated from both sites (I had a lot of problems with the firewall people in my company because they assumed only the server would open an connection on to that port)
    • The protocol returns a random port to connect to for the real transaction communication. Firewall people don't like that, they like to restrict the ports to a certain range. You can restrict the RPC dynamic port generation to a certain range using the keys as described in How to configure RPC dynamic port allocation to work with firewalls.

In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.

How to enable multidexing with the new Android Multidex support library

Edit:

Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion is 21 or higher, the multidex support library is not needed.


Modify your build.gradle:

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"

         defaultConfig {
             minSdkVersion 14 //lower than 14 doesn't support multidex
             targetSdkVersion 22

             // Enabling multidex support.
             multiDexEnabled true
         }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

If you are running unit tests, you will want to include this in your Application class:

public class YouApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}

Or just make your application class extend MultiDexApplication

public class Application extends MultiDexApplication {

}

For more info, this is a good guide.

How to write character & in android strings.xml

For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0

What's the best practice to "git clone" into an existing folder?

Just use the . at the end of the git clone command (being in that directory), like this:

cd your_dir_to_clone_in/
git clone [email protected]/somerepo/ .

virtualenvwrapper and Python 3

If you already have python3 installed as well virtualenvwrapper the only thing you would need to do to use python3 with the virtual environment is creating an environment using:

which python3 #Output: /usr/bin/python3
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

Or, (at least on OSX using brew):

mkvirtualenv --python=`which python3` nameOfEnvironment

Start using the environment and you'll see that as soon as you type python you'll start using python3

How can I combine two HashMap objects containing the same types?

One-liner using Java 8 Stream API:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue))

Among the benefits of this method is ability to pass a merge function, which will deal with values that have the same key, for example:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::max))

Removing Java 8 JDK from Mac

I was able to unistall jdk 8 in mavericks successfully doing the following steps:

Run this command to just remove the JDK

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk<version>.jdk

Run these commands if you want to remove plugins

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Angular 4 checkbox change value

Inside your component class:

checkValue(event: any) {
  this.userForm.patchValue({
    state: event
  })
}

Now in controls you have value A or B

Differences between git pull origin master & git pull origin/master

git pull origin master will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master is throwing the error.

Good Linux (Ubuntu) SVN client

Since you're using Ubuntu, and not Kubuntu, I assume you're using GNOME. You might be interested in Nautilus Subversion Integration described on that link.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

How organize uploaded media in WP?

The plugin Media File Manager advanced is amazing and allow you to create folders and subfolders very easily and move files with a simple drag & drop.

Check it at: http://wordpress.org/plugins/media-file-manager-advanced/

embedding image in html email

If you are using Outlook to send a static image with hyperlink, an easy way would be to use Word.

  1. Open MS Word
  2. Copy the image onto a blank page
  3. Add hyperlink to the image (Ctrl + K)
  4. Copy the image to your email

What is the difference between a static and const variable?

Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.

Check out this site.

Convert multidimensional array into single array

Problem array:

array:2 [?
  0 => array:3 [?
    0 => array:4 [?
      "id" => 8
      "name" => "Veggie Burger"
      "image" => ""
      "Category_type" => "product"
    ]
    1 => array:4 [?
      "id" => 9
      "name" => "Veggie Pitta"
      "image" => ""
      "Category_type" => "product"
    ]
    2 => array:4 [?
      "id" => 10
      "name" => "Veggie Wrap"
      "image" => ""
      "Category_type" => "product"
    ]
  ]
  1 => array:2 [?
    0 => array:4 [?
      "id" => 18
      "name" => "Cans 330ml"
      "image" => ""
      "Category_type" => "product"
    ]
    1 => array:4 [?
      "id" => 19
      "name" => "Bottles 1.5 Ltr"
      "image" => ""
      "Category_type" => "product"
    ]
  ]
]

Solution array:

array:5 [?
  0 => array:4 [?
    "id" => 8
    "name" => "Veggie Burger"
    "image" => ""
    "Category_type" => "product"
  ]
  1 => array:4 [?
    "id" => 9
    "name" => "Veggie Pitta"
    "image" => ""
    "Category_type" => "product"
  ]
  2 => array:4 [?
    "id" => 10
    "name" => "Veggie Wrap"
    "image" => ""
    "Category_type" => "product"
  ]
  3 => array:4 [?
    "id" => 18
    "name" => "Cans 330ml"
    "image" => ""
    "Category_type" => "product"
  ]
  4 => array:4 [?
    "id" => 19
    "name" => "Bottles 1.5 Ltr"
    "image" => ""
    "Category_type" => "product"
  ]
]

Write this code and get your solution , $subcate is your multi dimensional array.

$singleArrayForCategory = array_reduce($subcate, 'array_merge', array());

How do I put double quotes in a string in vba?

I find the easiest way is to double up on the quotes to handle a quote.

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)" 

Some people like to use CHR(34)*:

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)" 

*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

How to post JSON to a server using C#?

If you need to call is asynchronously then use

var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/json";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        // End the stream request operation

        Stream postStream = request.EndGetRequestStream(asynchronousResult);


        // Create the post data
        string postData = JsonConvert.SerializeObject(edit).ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);


        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        //Start the web request
        request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
    }

    void GetResponceStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result = httpWebStreamReader.ReadToEnd();
            stat.Text = result;
        }

    }

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

Genymotion Android emulator - adb access?

I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.

I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:

adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK *failed to start daemon* error:
So I tried adb connect [ip] as suggested here, but I didn't work either, the same error came up.

What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices will give me the error above, but /yourdownloadpath/adb devices works just fine for me.

Hope it helped.

How do I make a batch file terminate upon encountering an error?

The shortest:

command || exit /b

If you need, you can set the exit code:

command || exit /b 666

And you can also log:

command || echo ERROR && exit /b

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

Unrecognized SSL message, plaintext connection? Exception

If you are running local using spring i'd suggest use:

@Bean
public AmazonDynamoDB amazonDynamoDB() throws IOException {
    return AmazonDynamoDBClientBuilder.standard()
            .withCredentials(
                    new AWSStaticCredentialsProvider(
                            new BasicAWSCredentials("fake", "credencial")
                    )
            )
            .withClientConfiguration(new ClientConfigurationFactory().getConfig().withProtocol(Protocol.HTTP))
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("localhost:8443", "central"))
            .build();
}

It works for me using unit test.

Hope it's help!

Adding days to $Date in PHP

Here has an easy way to solve this.

<?php
   $date = "2015-11-17";
   echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>

Output will be:

2015-11-22

Solution has found from here - How to Add Days to Date in PHP

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

How to serialize Joda DateTime with Jackson JSON processor?

As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule on your ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

For custom serialization/de-serialization of DateTime, you need to implement your own StdScalarSerializer and StdScalarDeserializer; it's pretty convoluted, but anyway.

For example, here's a DateTime serializer that uses the ISODateFormat with the UTC time zone:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

And the corresponding de-serializer:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

Then tie these together with a module:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

Then register the module on your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());

Best way to restrict a text field to numbers only?

The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:

<script type="text/javascript">
    // Restrict user input in a text field
    // create as many regular expressions here as you need:
    var digitsOnly = /[1234567890]/g;
    var integerOnly = /[0-9\.]/g;
    var alphaOnly = /[A-Za-z]/g;
    var usernameOnly = /[0-9A-Za-z\._-]/g;

    function restrictInput(myfield, e, restrictionType, checkdot){
        if (!e) var e = window.event
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        // if user pressed esc... remove focus from field...
        if (code==27) { this.blur(); return false; }

        // ignore if the user presses other keys
        // strange because code: 39 is the down key AND ' key...
        // and DEL also equals .
        if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
            if (character.match(restrictionType)) {
                if(checkdot == "checkdot"){
                    return !isNaN(myfield.value.toString() + character);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
</script>

Different usage methods would be:

<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">

Where are static methods and static variables stored in Java?

Static methods (in fact all methods) as well as static variables are stored in the PermGen section of the heap, since they are part of the reflection data (class related data, not instance related).

Update for clarification:

Note that only the variables and their technical values (primitives or references) are stored in PermGen space.

If your static variable is a reference to an object that object itself is stored in the normal sections of the heap (young/old generation or survivor space). Those objects (unless they are internal objects like classes etc.) are not stored in PermGen space.

Example:

static int i = 1; //the value 1 is stored in the PermGen section
static Object o = new SomeObject(); //the reference(pointer/memory address) is stored in the PermGen section, the object itself is not.


A word on garbage collection:

Do not rely on finalize() as it's not guaranteed to run. It is totally up to the JVM to decide when to run the garbage collector and what to collect, even if an object is eligible for garbage collection.

Of course you can set a static variable to null and thus remove the reference to the object on the heap but that doesn't mean the garbage collector will collect it (even if there are no more references).

Additionally finalize() is run only once, so you have to make sure it doesn't throw exceptions or otherwise prevent the object to be collected. If you halt finalization through some exception, finalize() won't be invoked on the same object a second time.

A final note: how code, runtime data etc. are stored depends on the JVM which is used, i.e. HotSpot might do it differently than JRockit and this might even differ between versions of the same JVM. The above is based on HotSpot for Java 5 and 6 (those are basically the same) since at the time of answering I'd say that most people used those JVMs. Due to major changes in the memory model as of Java 8, the statements above might not be true for Java 8 HotSpot - and I didn't check the changes of Java 7 HotSpot, so I guess the above is still true for that version, but I'm not sure here.

Suppress output of a function

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document

How is Docker different from a virtual machine?

In my opinion it depends, it can be seen from the needs of your application, why decide to deploy to Docker because Docker breaks the application into small parts according to its function, this becomes effective because when one application / function is an error it has no effect on other applications , in contrast to using full vm, it will be slower and more complex in configuration, but in some ways safer than docker

Is there a link to the "latest" jQuery library on Google APIs?

You can use the latest version of the jQuery library by any of the following.

  • Google Ajax API CDN (also supports SSL via HTTPS)

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
    

    /jquery.min.js

  • Microsoft CDN (also aupports SSL via HTTPS)

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    

    Ajax CDN Announcement, Microsoft Ajax CDN Documentation

  • jQuery CDN (via Media Temple)

     <script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
    

    ** Minified version

     <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
    

    ** Development (Full) version

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

Return only string message from Spring MVC 3 Controller

@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?

It's telling that the method returns some text and not to interpret it as a view etc.

  • You see that produces="text/plain" ?

It's just a good practice as it tells what will be returned from the method :)

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

ExtJs Gridpanel store refresh

Combination of Dasha's and MMT solutions:

  Ext.getCmp('yourGridId').getView().ds.reload();

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

Uninstall / remove a Homebrew package including all its dependencies

The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed:

brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install

How to initialize a dict with keys from a list and empty value in Python?

You could use dict.fromkeys as follows:

dict.fromkeys([1, 2, 3, 4], list())

This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).

How do I access the HTTP request header fields via JavaScript?

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

VBA error 1004 - select method of range class failed

Removing the range select before the copy worked for me. Thanks for the posts.

What is the difference between state and props in React?

The props vs state summary I like best is here: react-guide Big hat tip to those guys. Below is an edited version of that page:


props vs state

tl;dr If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.


props

Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.

state

The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

Changing props and state

                                                   props   state
    Can get initial value from parent Component?    Yes     Yes
    Can be changed by parent Component?             Yes     No
    Can set default values inside Component?*       Yes     Yes
    Can change inside Component?                    No      Yes
    Can set initial value for child Components?     Yes     Yes
    Can change in child Components?                 Yes     No
  • Note that both props and state initial values received from parents override default values defined inside a Component.

Should this Component have state?

State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.

Component types

Stateless Component Only props, no state. There's not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.

Stateful Component Both props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.

sources

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

How do you overcome the svn 'out of date' error?

Remove your file or your path using before execute the command do a bk of your changes

sudo rm -r /path/to/dir/

after :

svn up and commit or delete 

Adding form action in html in laravel

For Laravel 2020. Ok, an example:

<form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must 
....
 </form>

And then in web.php:

Route::post("/login_kun", "LoginController@login");

And one more in new created LoginController:

 public function login(Request $request){
    dd($request->all());
}

and you are done my friend.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link

http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html

How do I find a default constraint using INFORMATION_SCHEMA?

I am using folllowing script to retreive all defaults (sp_binddefaults) and all default constraint with following scripts:

SELECT 
    t.name AS TableName, c.name AS ColumnName, SC.COLUMN_DEFAULT AS DefaultValue, dc.name AS DefaultConstraintName
FROM  
    sys.all_columns c
    JOIN sys.tables t ON c.object_id = t.object_id
    JOIN sys.schemas s ON t.schema_id = s.schema_id
    LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
    LEFT JOIN INFORMATION_SCHEMA.COLUMNS SC ON (SC.TABLE_NAME = t.name AND SC.COLUMN_NAME = c.name)
WHERE 
    SC.COLUMN_DEFAULT IS NOT NULL
    --WHERE t.name = '' and c.name = ''

Border color on default input style

border-color: transparent; border: 1px solid red;

Call to a member function on a non-object

I realized that I wasn't passing $objPage into page_properties(). It works fine now.

Batch Files - Error Handling

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

Django REST Framework: adding additional field to ModelSerializer

With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property and source='field' raise an error.

class Foo(models.Model):
    . . .
    def foo(self):
        return 'stuff'
    . . .

class FooSerializer(ModelSerializer):
    foo = serializers.ReadOnlyField()

    class Meta:
        model = Foo
        fields = ('foo',)

Prevent direct access to a php include file

You can also try renaming the document you don't want people to be able to access. You could rename it to 47d8498d3w.php for instance. Just make something up that people most likely won't type as a http-request. If you include the file with SSI or PHP, the user won't be able to see the name of the document anyway.

php execute a background process

I am heavily using fast_cgi_finish_request()

In combination with a closure and register_shutdown_function()

$message ='job executed';
$backgroundJob = function() use ($message) {
     //do some work here
    echo $message;
}

Then register this closure to be executed before shutdown.

register_shutdown_function($backgroundJob);

Finally when the response was sent to the client you can close the connection to the client and continue working with the PHP process:

fast_cgi_finish_request();

The closure will be executed after fast_cgi_finish_request.

The $message will not be visible at any time. And you can register as much closures as you want, but take care about script execution time. This will only work if PHP is running as a Fast CGI module (was that right?!)

convert float into varchar in SQL server without scientific notation

Casting or converting to VARCHAR(MAX) or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.

What did work was STR().

How to turn on/off MySQL strict mode in localhost (xampp)?

on Debian 10 I start mysql from ./opt/lampp/xampp start

I do strace ./opt/lampp/sbin/mysqld and see that my.cnf is there:

stat("/opt/lampp/etc/my.cnf", {st_mode=S_IFREG|0644, st_size=5050, ...}) = 0
openat(AT_FDCWD, "/opt/lampp/etc/my.cnf", O_RDONLY|O_CLOEXEC) = 3

hence, I add sql_mode config to /opt/lampp/etc/my.cnf instead of /etc/mysql/my.cnf

iOS 9 not opening Instagram app with URL SCHEME

Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.

Command not found after npm install in zsh

If you installed Node.js using Homebrew, npm binaries can be found in /usr/local/share/npm/bin. You should make sure this directory is in your PATH environment variable. So, in your ~/.zshrc file add export PATH=/usr/local/share/npm/bin:$PATH.

What does the "$" sign mean in jQuery or JavaScript?

Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:

"test".match( /t(e)st/ );
alert( RegExp.$1 );

will alert "e"

But also here it's not "magic" but simply part of the properties name

How do I time a method's execution in Java?

long startTime = System.currentTimeMillis();
// code goes here
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime; // elapsed time in milliseconds

Checking length of dictionary object

Count and show keys in a dictionary (run in console):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

function size_dict(d){c=0; for (i in d) ++c; return c}

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

How to run php files on my computer

You have to run a web server (e.g. Apache) and browse to your localhost, mostly likely on port 80.

What you really ought to do is install an all-in-one package like XAMPP, it bundles Apache, MySQL PHP, and Perl (if you were so inclined) as well as a few other tools that work with Apache and MySQL - plus it's cross platform (that's what the 'X' in 'XAMPP' stands for).

Once you install XAMPP (and there is an installer, so it shouldn't be hard) open up the control panel for XAMPP and then click the "Start" button next to Apache - note that on applications that require a database, you'll also need to start MySQL (and you'll be able to interface with it through phpMyAdmin). Once you've started Apache, you can browse to http://localhost.

Again, regardless of whether or not you choose XAMPP (which I would recommend), you should just have to start Apache.

Neither BindingResult nor plain target object for bean name available as request attribute

If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.

How to start anonymous thread class

You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();

... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:

Thread t = new Thread() {
    public void run() {
        System.out.println("blah");
    }
};
t.start();

How can I submit a form using JavaScript?

You can use the below code to submit the form using JavaScript:

document.getElementById('FormID').submit();

Change app language programmatically in Android

https://stackoverflow.com/a/48531811/9609776

This is ok but do not split the updateResources into different versions, just use the solution below (kotlin). Key is in "Configuration(context.resources.configuration)" it makes deep copy.

100% solution for API 21+. I have not tested for lower ones, but should work.

private fun updateResources(context: Context, language: String): Context {
    return Configuration(context.resources.configuration).run {
        Locale.setDefault(Locale(language).also { locale ->
            setLocale(locale)
        }).let {
            context.createConfigurationContext(this)
        }
    }
}

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

TL;DR

The object returned by range() is actually a range object. This object implements the iterator interface so you can iterate over its values sequentially, just like a generator, list, or tuple.

But it also implements the __contains__ interface which is actually what gets called when an object appears on the right hand side of the in operator. The __contains__() method returns a bool of whether or not the item on the left-hand-side of the in is in the object. Since range objects know their bounds and stride, this is very easy to implement in O(1).

++i or i++ in for loops ??

++i is slightly more efficient due to its semantics:

++i;  // Fetch i, increment it, and return it
i++;  // Fetch i, copy it, increment i, return copy

For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).

As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):

std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
  vec.push_back(i);
}

That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.

How to resolve 'unrecognized selector sent to instance'?

You should note that this is not necessarily the best design pattern. From the looks of it, you are essentially using your App Delegate to store what amounts to a global variable.

Matt Gallagher covered the issue of globals well in his Cocoa with Love article at http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html. In all likelyhood, your ClassA should be a singleton rather than a global in the AppDelegate, although its possible you intent ClassA to be more general purpose and not simply a singleton. In that case, you'd probably be better off with either a class method to return a pre-configured instance of Class A, something like:

+ (ClassA*) applicationClassA
{
    static ClassA* appClassA = nil;
    if ( !appClassA ) {
        appClassA = [[ClassA alloc] init];
        appClassA.downloadURL = @"http://www.abc.com/";
    }
    return appClassA;
}

Or alternatively (since that would add application specific stuff to what is possibly a general purpose class), create a new class whose sole purpose is to contain that class method.

The point is that application globals do not need to be part of the AppDelegate. Just because the AppDelegate is a known singleton, does not mean every other app global should be mixed in with it even if they have nothing conceptually to do with handling the NSApplication delegate methods.

HTML inside Twitter Bootstrap popover

you can use attribute data-html="true":

<a href="#" id="example"  rel="popover" 
    data-content="<div>This <b>is</b> your div content</div>" 
    data-html="true" data-original-title="A Title">popover</a>

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

How to create JSON string in JavaScript?

json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

How to interpolate variables in strings in JavaScript, without concatenation?

Create a method similar to String.format() of Java

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

use

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'

QString to char* conversion

Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by "it deosn't seem to work".

How to set index.html as root file in Nginx?

The answer is to place the root dir to the location directives:

root   /srv/www/ducklington.org/public_html;

How do I set the figure title and axes labels font size in Matplotlib?

Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.

Globally setting font sizes via rcParams should be done with

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

The defaults can be restored using

plt.rcParams.update(plt.rcParamsDefault)

You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is

axes.labelsize: 16
axes.titlesize: 16

If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

You can also create (or modify) a matplotlibrc file which shares the format

axes.labelsize = 16
axes.titlesize = 16

Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.

A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)

  • axes.labelsize - Fontsize of the x and y labels
  • axes.titlesize - Fontsize of the axes title
  • figure.titlesize - Size of the figure title (Figure.suptitle())
  • xtick.labelsize - Fontsize of the tick labels
  • ytick.labelsize - Fontsize of the tick labels
  • legend.fontsize - Fontsize for legends (plt.legend(), fig.legend())
  • legend.title_fontsize - Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.

all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by

  • font.size - the default font size for text, given in pts. 10 pt is the standard value

Additionally, the weight can be specified (though only for the default it appears) by

  • font.weight - The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

How to extract text from a PDF file?

If wanting to extract text from a table, I've found tabula to be easily implemented, accurate, and fast:

to get a pandas dataframe:

import tabula

df = tabula.read_pdf('your.pdf')

df

By default, it ignores page content outside of the table. So far, I've only tested on a single-page, single-table file, but there are kwargs to accommodate multiple pages and/or multiple tables.

install via:

pip install tabula-py
# or
conda install -c conda-forge tabula-py 

In terms of straight-up text extraction see: https://stackoverflow.com/a/63190886/9249533

What is your favorite C programming trick?

I like the concept of container_of used for example in lists. Basically, you do not need to specify next and last fields for each structure which will be in the list. Instead, you append the list structure header to actual linked items.

Have a look on include/linux/list.h for real-life examples.

SLF4J: Class path contains multiple SLF4J bindings

Gradle version;

configurations.all {
    exclude module: 'slf4j-log4j12'
}

How to change the docker image installation directory?

On Fedora 26 and probably many other versions, you may encounter an error after moving your base folder location as described above. This is particularly true if you are moving it to somewhere under /home. This is because SeLinux kicks in and prevents the docker container from running many of its programs from under this location.

The short solution is to remove the --enable-selinux option when you add the -g parameter.

Can I do Model->where('id', ARRAY) multiple where conditions?

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

moving committed (but not pushed) changes to a new branch after pull

A simpler approach, which I have been using (assuming you want to move 4 commits):

git format-patch HEAD~4

(Look in the directory from which you executed the last command for the 4 .patch files)

git reset HEAD~4 --hard

git checkout -b tmp/my-new-branch

Then:

git apply /path/to/patch.patch

In whatever order you wanted.

Fatal error: Maximum execution time of 30 seconds exceeded

Edit php.ini

Find this line:

max_execution_time

Change its value to 300:

max_execution_time = 300

300 means 5 minutes of execution time for the http request.

DropdownList DataSource

It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add _CRT_SECURE_NO_WARNINGS symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

Also you can define it just before you include a header file which generates this warning. You should add something like this

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy_s instead of strcpy.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

avd manager has an option "ideal size of system partition", try setting that to 1024MB, or use the commandline launch option that does the same.

fyi, I only encountered this problem with the 4.0 emulator image.

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

Favicon dimensions?

the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO. - How to Add a Favicon to your Site - QA @ W3C

Using lambda expressions for event handlers

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

Create timestamp variable in bash script

I am using ubuntu 14.04.

The correct way in my system should be date +%s.

The output of date +%T is like 12:25:25.

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

How can I decrypt a password hash in PHP?

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

In your case, run the SQL query using only the username:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

And do the password validation in PHP using a code that is similar to the example above.

The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.

Programmatically Check an Item in Checkboxlist where text is equal to what I want

I tried adding dynamically created ListItem and assigning the selected value.

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

avoid using binding the DataSource as it will not bind the checked/unchecked from DB.

Initializing a two dimensional std::vector

I think the easiest way to make it done is :

std::vector<std::vector<int>>v(10,std::vector<int>(11,100));

10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100! That's my first help on stack, i think it helps someone.

MySql export schema without data

You Can Use MYSQL Administrator Tool its free http://dev.mysql.com/downloads/gui-tools/5.0.html

you'll find many options to export ur MYSQL DataBase

Google Maps Api v3 - find nearest markers

The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:

function find_closest_marker( lat1, lon1 ) {    
    var pi = Math.PI;
    var R = 6371; //equatorial radius
    var distances = [];
    var closest = -1;

    for( i=0;i<markers.length; i++ ) {  
        var lat2 = markers[i].position.lat();
        var lon2 = markers[i].position.lng();

        var chLat = lat2-lat1;
        var chLon = lon2-lon1;

        var dLat = chLat*(pi/180);
        var dLon = chLon*(pi/180);

        var rLat1 = lat1*(pi/180);
        var rLat2 = lat2*(pi/180);

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
                    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2); 
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        var d = R * c;

        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    // (debug) The closest marker is:
    console.log(markers[closest]);
}

chrome undo the action of "prevent this page from creating additional dialogs"

No. But you should really use console.log() instead of alert() for debugging.

In Chrome it even has the advantage of being able to print out entire objects (not just toString()).

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>