Programs & Examples On #Retain

Selected value for JSP drop down using JSTL

I think above examples are correct. but you dont' really need to set

request.setAttribute("selectedDept", selectedDept);

you can reuse that info from JSTL, just do something like this..

<!DOCTYPE html>
<html lang="en">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<head>
    <script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
    <c:set var="authors" value="aaa,bbb,ccc,ddd,eee,fff,ggg" scope="application" />
    <c:out value="Before : ${param.Author}"/>
    <form action="TestSelect.action">
        <label>Author
            <select id="Author" name="Author">
                <c:forEach items="${fn:split(authors, ',')}" var="author">
                    <option value="${author}" ${author == param.Author ? 'selected' : ''}>${author}</option>
                </c:forEach>
            </select>
        </label>
        <button type="submit" value="submit" name="Submit"></button>
        <Br>
        <c:out value="After :   ${param.Author}"/>
    </form>
</body>
</html>

How do I setup the InternetExplorerDriver so it works

Unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Basically, you have to set this property before you initialize driver

Reference:

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Turns out that the problem was with face that the script was running from a cPanel "email piped to script", so was running as the user, so is was a user problem, but was not affecting the web server at all.

The cause for the user not being able to access the /etc/pki directory was due to them only having jailed ssh access. Once I granted full access, it all worked fine.

Thanks for the info though, Remi.

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

This is basically a more detailed version of a previous answer.

In your Terminal, go to the location of your utility program, mysqladmin

For example, if you were doing local development and using an application like M/W/XAMP, you might go to the directory:

/Applications/MAMP/Library/bin

This is where mysqladmin resides.

If you're not using an application like MAMP, you may also be able to find your local installation of mysql at: /usr/local/mysql

And then if you go to: /usr/local/mysql/bin/

You are in the directory where mysqladmin resides.

Then, to change the password, you will do the following:

  1. At your Terminal prompt enter the exact command below (aka copy and paste) and press enter. The word "password" is part of the command, so don't be confused and come to the conclusion that you need to replace this word with some password you created previously or want to use in the future. You will have a chance to enter a new password soon enough, but it's not in this first command that you will do that:

    ./mysqladmin -u root -p password

  2. The Terminal will ask you to enter your original or initial password, not a new one yet. From the above image you provided, it looks like you have one already created, so enter it here:

Enter password: oldpassword

  1. The Terminal will ask you to enter a new password. Type it here and press enter:

New password: newpassword

  1. Then the Terminal will ask you to confirm the new password. Type it here and press enter:

Confirm new password: newpassword

Reset or restart your Terminal.

In some cases, as with M/W/XAMP, you will have to update this new password in various files in order to get your application running properly again.

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

I also had a similar issue. Someone might find what worked for me helpful.

Machine is running Ubuntu 16.04 and has Docker CE. After looking through the answers and links provided here, especially from the link from the Docker website given by Elliot Beach, I opened my /etc/apt/sources.list and examined it.

The file had both deb [arch=amd64] https://download.docker.com/linux/ubuntu (lsb_release -cs) stable and deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable.

Since the second one was what was needed, I simply commented out the first, saved the document and now the issue is fixed. As a test, I went back into the same document, removed the comment sign and ran sudo apt-get update again. The issue returned when I did that.

So to recap : not only did I have my parent Ubuntu distribution name as stated on the Docker website but I also commented out the line still containing (lsb_release -cs).

Bootstrap Modal sitting behind backdrop

For those using ASP.NET MVC,

Needing to move the modal div just before the </body> tag but can't do it because you are using a Layout page

Define a section in you _Layout.cshtml file just before the body tag, eg:

... some html in layout page ...
@RenderSection("bottomHTML", required: false)
</body>
</html>

Then in your view

@section bottomHTML 
{
<div class="modal fade" id="myModalID" role="dialog" tabindex="-1" aria-labelledby="demo-default-modal" aria-hidden="true">
... rest of the modal div HTML ...
}

This way, the modal HTML will be rendered before the body tag and the modal now should be displayed correctly..

FileProvider - IllegalArgumentException: Failed to find configured root

This may resolve everyones problem: All tags are added so you don't need to worry about folders path. Replace res/xml/file_paths.xml with:

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path
    name="external"
    path="." />
  <external-files-path
    name="external_files"
    path="." />
  <cache-path
    name="cache"
    path="." />
  <external-cache-path
    name="external_cache"
    path="." />
<files-path
    name="files"
    path="." />
</paths>

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

Custom Drawable for ProgressBar/ProgressDialog

Try setting:

android:indeterminateDrawable="@drawable/progress" 

It worked for me. Here is also the code for progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#4c737373"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate> 

CSS class for pointer cursor

I tried and found out that if you add a class called btn you can get that hand or cursor icon if you hover over the mouse to that element. Try and see.

Example:

<span class="btn">Hovering over must have mouse cursor set to hand or pointer!</span>

Cheers!

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Change app language programmatically in Android

Kotlin version of solution

private fun setLocale(activity: Activity, languageCode: String?) {
    val locale = Locale(languageCode)
    Locale.setDefault(locale)
    val config: Configuration = resources.configuration
    config.setLocale(locale)
    resources.updateConfiguration(config, resources.displayMetrics)

See this answer for list of the language codes https://stackoverflow.com/a/7989085/13139418

What is the purpose and use of **kwargs?

kwargs is just a dictionary that is added to the parameters.

A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.

The what for is not so simple.

For example (very hypothetical) you have an interface that just calls other routines to do the job:

def myDo(what, where, why):
   if what == 'swim':
      doSwim(where, why)
   elif what == 'walk':
      doWalk(where, why)
   ...

Now you get a new method "drive":

elif what == 'drive':
   doDrive(where, why, vehicle)

But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.

Here you can throw kwargs into play -- you just add kwargs to the signature:

def myDo(what, where, why, **kwargs):
   if what == 'drive':
      doDrive(where, why, **kwargs)
   elif what == 'swim':
      doSwim(where, why, **kwargs)

This way you don't need to change the signature of your interface function every time some of your called routines might change.

This is just one nice example you could find kwargs helpful.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had a workaround for this problem. I created dll project with viewer in vs2015 and used this dll in vs2017. Report showing perfectly.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

You can try this:

SELECT * FROM MYTABLE WHERE DATE BETWEEN '03/10/2014 06:25:00' and '03/12/2010 6:25:00'

How to set placeholder value using CSS?

You can do this for webkit:

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

http://jsfiddle.net/Z3tFG/1/

MyISAM versus InnoDB

For that ratio of read/writes I would guess InnoDB will perform better. Since you are fine with dirty reads, you might (if you afford) replicate to a slave and let all your reads go to the slave. Also, consider inserting in bulk, rather than one record at a time.

Disable Tensorflow debugging information

For compatibility with Tensorflow 2.0, you can use tf.get_logger

import logging
tf.get_logger().setLevel(logging.ERROR)

Git for beginners: The definitive practical guide

Console UI - Tig

Installation:

apt-get install tig

Usage

While inside a git repo, type 'tig', to view an interactive log, hit 'enter' on any log to see more information about it. h for help, which lists the basic functionality.

Trivia

"Tig" is "Git" backwards.

Using the Web.Config to set up my SQL database connection string?

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

Remove file extension from a file name string

I know it's an old question and Path.GetFileNameWithoutExtensionis a better and maybe cleaner option. But personally I've added this two methods to my project and wanted to share them. This requires C# 8.0 due to it using ranges and indices.

public static string RemoveExtension(this string file) => ReplaceExtension(file, null);

public static string ReplaceExtension(this string file, string extension)
{
    var split = file.Split('.');

    if (string.IsNullOrEmpty(extension))
        return string.Join(".", split[..^1]);

    split[^1] = extension;

    return string.Join(".", split);
}

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

Convert boolean to int in Java

public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

simple

When should I use git pull --rebase?

I think it boils down to a personal preference.

Do you want to hide your silly mistakes before pushing your changes? If so, git pull --rebase is perfect. It allows you to later squash your commits to a few (or one) commits. If you have merges in your (unpushed) history, it is not so easy to do a git rebase later one.

I personally don't mind publishing all my silly mistakes, so I tend to merge instead of rebase.

WPF What is the correct way of using SVG files as icons in WPF

You can use the resulting xaml from the SVG as a drawing brush on a rectangle. Something like this:

<Rectangle>
   <Rectangle.Fill>
      --- insert the converted xaml's geometry here ---
   </Rectangle.Fill>
</Rectangle>

Display a decimal in scientific notation

I prefer Python 3.x way.

cal = 123.4567
print(f"result {cal:.4E}")

4 indicates how many digits are shown shown in the floating part.

cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")

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

open node.js command prompt
run this command

node -v

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Capture close event on Bootstrap Modal

Though is answered in another stack overflow question Bind a function to Twitter Bootstrap Modal Close but for visual feel here is more detailed answer.

Source: http://getbootstrap.com/javascript/#modals-events

Difference between mkdir() and mkdirs() in java for java.io.File

mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.

How to convert int to QString?

Just for completeness, you can use the standard library and do QString qstr = QString::fromStdString(std::to_string(42));

How to change the status bar color in Android?

I had this requirement: Changing programmatically the status bar color keeping it transparent, to allow the Navigation Drawer to draw itself overlapping the trasparent status bar.

I cannot do that using the API

getWindow().setStatusBarColor(ContextCompat.getColor(activity ,R.color.my_statusbar_color)

If you check here in stack overflow everyone before that line of code set the transparency of the status bar to solid with

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)

I'm able to manage color and transparency of status bar like this:

  • Android 4: there's not much you can do, because you can't manage status bar color from the API ... the only thing you can do is to set the status bar as translucent and move a colored element of you UI under the status bar. To do this you need to play with

    android:fitsSystemWindows="false"
    

    in your main layout. This allows you to draw you layout under the status bar. Then you need to play with some padding with the top of your main layout.

  • Android 5 and above: you have to define a style with

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    

    this allows the navigation drawer to overlap the status bar.

    Then to change the color keeping the status bar transparent you have to set the status bar color with

    drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(activity, R.color.my_statusbar_color))
    

    where drawerLayout is defined like this

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
    

Check if Variable is Empty - Angular 2

Ar you looking for that:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

(found here)

or that :

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

found here

How do I round a double to two decimal places in Java?

You can use org.apache.commons.math.util.MathUtils from apache common

double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);

DisplayName attribute from Resources?

If you use MVC 3 and .NET 4, you can use the new Display attribute in the System.ComponentModel.DataAnnotations namespace. This attribute replaces the DisplayName attribute and provides much more functionality, including localization support.

In your case, you would use it like this:

public class MyModel
{
    [Required]
    [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
    public string name{ get; set; }
}

As a side note, this attribute will not work with resources inside App_GlobalResources or App_LocalResources. This has to do with the custom tool (GlobalResourceProxyGenerator) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.

(As a further side note, you shouldn't be using App_GlobalResources or App_LocalResources with MVC. You can read more about why this is the case here)

Label on the left side instead above an input field

I am sure you would've already found your answer... here is the solution I derived at.

That's my CSS.

.field, .actions {
    margin-bottom: 15px;
  }
  .field label {
    float: left;
    width: 30%;
    text-align: right;
    padding-right: 10px;
    margin: 5px 0px 5px 0px;
  }
  .field input {
    width: 70%;
    margin: 0px;
  }

And my HTML...

<h1>New customer</h1>
<div class="container form-center">
    <form accept-charset="UTF-8" action="/customers" class="new_customer" id="new_customer" method="post">
    <div style="margin:0;padding:0;display:inline"></div>

  <div class="field">
    <label for="customer_first_name">First name</label>
    <input class="form-control" id="customer_first_name" name="customer[first_name]" type="text" />
  </div>
  <div class="field">
    <label for="customer_last_name">Last name</label>
    <input class="form-control" id="customer_last_name" name="customer[last_name]" type="text" />
  </div>
  <div class="field">
    <label for="customer_addr1">Addr1</label>
    <input class="form-control" id="customer_addr1" name="customer[addr1]" type="text" />
  </div>
  <div class="field">
    <label for="customer_addr2">Addr2</label>
    <input class="form-control" id="customer_addr2" name="customer[addr2]" type="text" />
  </div>
  <div class="field">
    <label for="customer_city">City</label>
    <input class="form-control" id="customer_city" name="customer[city]" type="text" />
  </div>
  <div class="field">
    <label for="customer_pincode">Pincode</label>
    <input class="form-control" id="customer_pincode" name="customer[pincode]" type="text" />
  </div>
  <div class="field">
    <label for="customer_homephone">Homephone</label>
    <input class="form-control" id="customer_homephone" name="customer[homephone]" type="text" />
  </div>
  <div class="field">
    <label for="customer_mobile">Mobile</label>
    <input class="form-control" id="customer_mobile" name="customer[mobile]" type="text" />
  </div>
  <div class="actions">
    <input class="btn btn-primary btn-large btn-block" name="commit" type="submit" value="Create Customer" />
  </div>
</form>
</div>

You can see the working example here... http://jsfiddle.net/s6Ujm/

PS: I am a beginner too, pro designers... feel free share your reviews.

"NoClassDefFoundError: Could not initialize class" error

I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

Open your system command prompt/terminal -> Go to your Project folder path (root project folder ) -> Execute following command : command :- gradlew clean or ./gradlew clean

Make sure that all your gradle dependencies are of same version. -> Example :- your appcompat and recyclerview dependencies should have same version.

-> Change your gradle dependencies to same version like :-

compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'

-> Rebuild your project and it will work fine.

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Seaborn plots not showing up

To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.

In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline would not work.

I was just having the same issue and suggest you use Jupyter Notebook for the visualization.

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

How to get a random value from dictionary?

>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'

By calling random.choice on the keys of the dictionary (the countries).

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Return from a promise then()

Promises don't "return" values, they pass them to a callback (which you supply with .then()).

It's probably trying to say that you're supposed to do resolve(someObject); inside the promise implementation.

Then in your then code you can reference someObject to do what you want.

How to alert using jQuery

For each works with JQuery as in

$(<selector>).each(function() {
   //this points to item
   alert('<msg>');
});

JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/

Check it out, works really well.

HTH.

Custom pagination view in Laravel 5

Laravel 5 ships with a Bootstrap 4 paginator if anyone needs it.

First create a new service provider.

php artisan make:provider PaginationServiceProvider

In the register method pass a closure to Laravel's paginator class that creates and returns the new presenter.

<?php


namespace App\Providers;

use Illuminate\Pagination\BootstrapFourPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        Paginator::presenter(function($paginator)
        {
            return new BootstrapFourPresenter($paginator);
        });
    }
}

Register the new provider in config/app.php

'providers' => [
    //....
    App\Providers\PaginationServiceProvider::class,
]

I found this example at Bootstrap 4 Pagination With Laravel

How to easily consume a web service from PHP

I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.

Exiting from python Command Line

You can fix that.

Link PYTHONSTARTUP to a python file with the following

# Make exit work as expected
type(exit).__repr__ = type(exit).__call__

How does this work?

The python command line is a read-evaluate-print-loop, that is when you type text it will read that text, evaluate it, and eventually print the result.

When you type exit() it evaluates to a callable object of type site.Quitter and calls its __call__ function which exits the system. When you type exit it evaluates to the same callable object, without calling it the object is printed which in turn calls __repr__ on the object.

We can take advantage of this by linking __repr__ to __call__ and thus get the expected behavior of exiting the system even when we type exit without parentheses.

html table span entire width?

Try (in your <head> section, or existing css definitions)...

<style>
  body {
   margin:0;
   padding:0;
  }
</style>

400 vs 422 response to POST of data

There is no correct answer, since it depends on what the definition of "syntax" is for your request. The most important thing is that you:

  1. Use the response code(s) consistently
  2. Include as much additional information in the response body as you can to help the developer(s) using your API figure out what's going on.=

Before everyone jumps all over me for saying that there is no right or wrong answer here, let me explain a bit about how I came to the conclusion.

In this specific example, the OP's question is about a JSON request that contains a different key than expected. Now, the key name received is very similar, from a natural language standpoint, to the expected key, but it is, strictly, different, and hence not (usually) recognized by a machine as being equivalent.

As I said above, the deciding factor is what is meant by syntax. If the request was sent with a Content Type of application/json, then yes, the request is syntactically valid because it's valid JSON syntax, but not semantically valid, since it doesn't match what's expected. (assuming a strict definition of what makes the request in question semantically valid or not).

If, on the other hand, the request was sent with a more specific custom Content Type like application/vnd.mycorp.mydatatype+json that, perhaps, specifies exactly what fields are expected, then I would say that the request could easily be syntactically invalid, hence the 400 response.

In the case in question, since the key was wrong, not the value, there was a syntax error if there was a specification for what valid keys are. If there was no specification for valid keys, or the error was with a value, then it would be a semantic error.

Regular expression to match a dot

to escape non-alphanumeric characters of string variables, including dots, you could use re.escape:

import re

expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)

output:

whatever\.v1\.dfc

you can use the escaped expression to find/match the string literally.

Git merge errors

Change branch, discarding all local modifications

git checkout -f 9-sign-in-out 

Rename the current branch to master, discarding current master

git branch -M master 

Practical uses for AtomicInteger

In Java 8 atomic classes have been extended with two interesting functions:

  • int getAndUpdate(IntUnaryOperator updateFunction)
  • int updateAndGet(IntUnaryOperator updateFunction)

Both are using the updateFunction to perform update of the atomic value. The difference is that the first one returns old value and the second one return the new value. The updateFunction may be implemented to do more complex "compare and set" operations than the standard one. For example it can check that atomic counter doesn't go below zero, normally it would require synchronization, and here the code is lock-free:

    public class Counter {

      private final AtomicInteger number;

      public Counter(int number) {
        this.number = new AtomicInteger(number);
      }

      /** @return true if still can decrease */
      public boolean dec() {
        // updateAndGet(fn) executed atomically:
        return number.updateAndGet(n -> (n > 0) ? n - 1 : n) > 0;
      }
    }

The code is taken from Java Atomic Example.

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

CSS :not(:last-child):after selector

You can try this, I know is not the answers you are looking for but the concept is the same.

Where you are setting the styles for all the children and then removing it from the last child.

Code Snippet

li
  margin-right: 10px

  &:last-child
    margin-right: 0

Image

enter image description here

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to find whether a number belongs to a particular range in Python?

if num in range(min, max):
  """do stuff..."""
else:
  """do other stuff..."""

What is the default access modifier in Java?

Here is a code sample which should pretty much sum this up for you... In addition to the below, showing how you can't access a default in another package there is one more thing.

Default is not accessible in a subclass if the class that subclasses it is in another package, but it is accessible if the subclass is in the same package.

package main;

public class ClassA {
    private int privateVar;
    public int publicVar;
    int defaultVar;
}

package main;

public class ClassB {
    public static void main(String[] args) {
        ClassA a = new ClassA();
        int v1 = a.publicVar;   // Works
        int v2 = a.defaultVar;  // Works
        int v3 = a.privateVar;  // Doesn't work

    }
}

package other;

public class ClassC {
    public static void main(String[] args) {
        ClassA a = new ClassA();
        int v1 = a.publicVar;   // Works
        int v2 = a.defaultVar;  // Doesn't work
        int v3 = a.privateVar;  // Doesn't work
    }
}

How can getContentResolver() be called in Android?

getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance of Context ( Activity or Service for example).

How does Java handle integer underflows and overflows and how would you check for it?

Java doesn't do anything with integer overflow for either int or long primitive types and ignores overflow with positive and negative integers.

This answer first describes the of integer overflow, gives an example of how it can happen, even with intermediate values in expression evaluation, and then gives links to resources that give detailed techniques for preventing and detecting integer overflow.

Integer arithmetic and expressions reslulting in unexpected or undetected overflow are a common programming error. Unexpected or undetected integer overflow is also a well-known exploitable security issue, especially as it affects array, stack and list objects.

Overflow can occur in either a positive or negative direction where the positive or negative value would be beyond the maximum or minimum values for the primitive type in question. Overflow can occur in an intermediate value during expression or operation evaluation and affect the outcome of an expression or operation where the final value would be expected to be within range.

Sometimes negative overflow is mistakenly called underflow. Underflow is what happens when a value would be closer to zero than the representation allows. Underflow occurs in integer arithmetic and is expected. Integer underflow happens when an integer evaluation would be between -1 and 0 or 0 and 1. What would be a fractional result truncates to 0. This is normal and expected with integer arithmetic and not considered an error. However, it can lead to code throwing an exception. One example is an "ArithmeticException: / by zero" exception if the result of integer underflow is used as a divisor in an expression.

Consider the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue * 2 / 5;
int y = bigValue / x;

which results in x being assigned 0 and the subsequent evaluation of bigValue / x throws an exception, "ArithmeticException: / by zero" (i.e. divide by zero), instead of y being assigned the value 2.

The expected result for x would be 858,993,458 which is less than the maximum int value of 2,147,483,647. However, the intermediate result from evaluating Integer.MAX_Value * 2, would be 4,294,967,294, which exceeds the maximum int value and is -2 in accordance with 2s complement integer representations. The subsequent evaluation of -2 / 5 evaluates to 0 which gets assigned to x.

Rearranging the expression for computing x to an expression that, when evaluated, divides before multiplying, the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue / 5 * 2;
int y = bigValue / x;

results in x being assigned 858,993,458 and y being assigned 2, which is expected.

The intermediate result from bigValue / 5 is 429,496,729 which does not exceed the maximum value for an int. Subsequent evaluation of 429,496,729 * 2 doesn't exceed the maximum value for an int and the expected result gets assigned to x. The evaluation for y then does not divide by zero. The evaluations for x and y work as expected.

Java integer values are stored as and behave in accordance with 2s complement signed integer representations. When a resulting value would be larger or smaller than the maximum or minimum integer values, a 2's complement integer value results instead. In situations not expressly designed to use 2s complement behavior, which is most ordinary integer arithmetic situations, the resulting 2s complement value will cause a programming logic or computation error as was shown in the example above. An excellent Wikipedia article describes 2s compliment binary integers here: Two's complement - Wikipedia

There are techniques for avoiding unintentional integer overflow. Techinques may be categorized as using pre-condition testing, upcasting and BigInteger.

Pre-condition testing comprises examining the values going into an arithmetic operation or expression to ensure that an overflow won't occur with those values. Programming and design will need to create testing that ensures input values won't cause overflow and then determine what to do if input values occur that will cause overflow.

Upcasting comprises using a larger primitive type to perform the arithmetic operation or expression and then determining if the resulting value is beyond the maximum or minimum values for an integer. Even with upcasting, it is still possible that the value or some intermediate value in an operation or expression will be beyond the maximum or minimum values for the upcast type and cause overflow, which will also not be detected and will cause unexpected and undesired results. Through analysis or pre-conditions, it may be possible to prevent overflow with upcasting when prevention without upcasting is not possible or practical. If the integers in question are already long primitive types, then upcasting is not possible with primitive types in Java.

The BigInteger technique comprises using BigInteger for the arithmetic operation or expression using library methods that use BigInteger. BigInteger does not overflow. It will use all available memory, if necessary. Its arithmetic methods are normally only slightly less efficient than integer operations. It is still possible that a result using BigInteger may be beyond the maximum or minimum values for an integer, however, overflow will not occur in the arithmetic leading to the result. Programming and design will still need to determine what to do if a BigInteger result is beyond the maximum or minimum values for the desired primitive result type, e.g., int or long.

The Carnegie Mellon Software Engineering Institute's CERT program and Oracle have created a set of standards for secure Java programming. Included in the standards are techniques for preventing and detecting integer overflow. The standard is published as a freely accessible online resource here: The CERT Oracle Secure Coding Standard for Java

The standard's section that describes and contains practical examples of coding techniques for preventing or detecting integer overflow is here: NUM00-J. Detect or prevent integer overflow

Book form and PDF form of The CERT Oracle Secure Coding Standard for Java are also available.

Git: How to update/checkout a single file from remote origin master?

Or git stash (if you have changes) on the branch you're on, checkout master, pull for the latest changes, grab that file to your desktop (or the entire app). Checkout the branch you were on. Git stash apply back to the state you were at, then fix the changes manually or drag it replacing the file.

This way is not sooooo cool but it def works if you guys can't figure anything else out.

How to Deserialize XML document

You have two possibilities.

Method 1. XSD tool


Suppose that you have your XML file in this location C:\path\to\xml\file.xml

  1. Open Developer Command Prompt
    You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  3. Create XSD file from your xml file by typing xsd file.xml
  4. Create C# classes by typing xsd /c file.xsd

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

Method 2 - Paste special


Required Visual Studio 2012+

  1. Copy content of your XML file to clipboard
  2. Add to your solution new, empty class file (Shift+Alt+C)
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
    enter image description here

And that's it!

Usage


Usage is very simple with this helper class:

using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;

namespace Helpers
{
    internal static class ParseHelpers
    {
        private static JavaScriptSerializer json;
        private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }

        public static Stream ToStream(this string @this)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(@this);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }


        public static T ParseXML<T>(this string @this) where T : class
        {
            var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }

        public static T ParseJSON<T>(this string @this) where T : class
        {
            return JSON.Deserialize<T>(@this.Trim());
        }
    }
}

All you have to do now, is:

    public class JSONRoot
    {
        public catalog catalog { get; set; }
    }
    // ...

    string xml = File.ReadAllText(@"D:\file.xml");
    var catalog1 = xml.ParseXML<catalog>();

    string json = File.ReadAllText(@"D:\file.json");
    var catalog2 = json.ParseJSON<JSONRoot>();

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.

You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.

You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);

    final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
    final Button btn2 = (Button) findViewById(R.id.btnDate2);
    final Button btn3 = (Button) findViewById(R.id.btnVisibility);

    dp2.setVisibility(View.INVISIBLE);
    btn2.setVisibility(View.INVISIBLE);

    bt3.setOnClickListener(new View.OnCLickListener(){ 
    @Override
    public void onClick(View view)
    {
        dp2.setVisibility(View.VISIBLE);
        bt2.setVisibility(View.VISIBLE);
    }
  });
}

I think this should work easily. Hope this helps.

What does the "+=" operator do in Java?

  • x += y is x = x + y
  • x -= y is x = x - y
  • x *= y is x = x * y
  • x /= y is x = x / y
  • x %= y is x = x % y
  • x ^= y is x = x ^ y
  • x &= y is x = x & y
  • x |= y is x = x | y

and so on ...

How to pass data from Javascript to PHP and vice versa?

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->

Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

How to put spacing between floating divs?

A litte late answer.

If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.

jQuery selector to get form by name

    // this will give all the forms on the page.

    $('form')

   // If you know the name of form then.

    $('form[name="myFormName"]')

  //  If you don't know know the name but the position (starts with 0)

    $('form:eq(1)')  // 2nd form will be fetched.

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

Why doesn't Java support unsigned ints?

As soon as signed and unsigned ints are mixed in an expression things start to get messy and you probably will lose information. Restricting Java to signed ints only really clears things up. I’m glad I don’t have to worry about the whole signed/unsigned business, though I sometimes do miss the 8th bit in a byte.

Waiting until two async blocks are executed before starting another block

Swift 4.2 example:

let group = DispatchGroup.group(count: 2)
group.notify(queue: DispatchQueue.main) {
     self.renderingLine = false
     // all groups are done
}
DispatchQueue.main.async {
    self.renderTargetNode(floorPosition: targetPosition, animated: closedContour) {
        group.leave()
        // first done
    }
    self.renderCenterLine(position: targetPosition, animated: closedContour) {
        group.leave()
        // second done
    }
 }

Get the date (a day before current time) in Bash

You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':

echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'

In January of 2020 it will return 201912 ;-) But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)

Call a stored procedure with parameter in c#

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}

href="file://" doesn't work

Share your folder for "everyone" or some specific group and try this:

_x000D_
_x000D_
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a> 
_x000D_
_x000D_
_x000D_

How to hide Table Row Overflow?

If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).

To use the plugin just type

$('selector').tableoverflow();

Plugin: https://github.com/marcogrcr/jquery-tableoverflow

Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/

How do I find the CPU and RAM usage using PowerShell?

You can also use the Get-Counter cmdlet (PowerShell 2.0):

Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'

To get a list of memory counters:

Get-Counter -ListSet *memory* | Select-Object -ExpandProperty  Counter

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1

cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2

cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

Command CompileSwift failed with a nonzero exit code in Xcode 10

I did the following and it works like charm:

  • Open Xcode Preferences (Command,)
  • Go to the Locations tab
  • Click on the small gray arrow which shows URL path for Derived Data
  • The finder window will open up and show the following folders:

    • DerivedData
    • Archives
    • iOS DeviceSupport
    • UserData
    • DocumentationCache
    • iOS Device Logs
  • Quit Xcode

  • Delete the DerivedData folder (it just contains a cache from previous builds)
  • Restart Xcode

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

How to get files in a relative path in C#

Write it like this:

string[] files = Directory.GetFiles(@".\Archive", "*.zip");

. is for relative to the folder where you started your exe, and @ to allow \ in the name.

When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.

In order to get the folder where your .exe actually resides, use:

var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Why is there no Char.Empty like String.Empty?

Not an answer to your question, but to denote a default char you can use just

default(char)

which is same as char.MinValue which in turn is same as \0. One shouldn't use if for something like an empty string though.

How to handle anchor hash linking in AngularJS

On Route change it will scroll to the top of the page.

 $scope.$on('$routeChangeSuccess', function () {
      window.scrollTo(0, 0);
  });

put this code on your controller.

Cast a Double Variable to Decimal

use default convertation class: Convert.ToDecimal(Double)

TransactionRequiredException Executing an update/delete query

Faced the same problem, I simply forgot to activate the transaction management with the @EnableTransactionManagement annotation.

Ref:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

Nesting CSS classes

Not possible with vanilla CSS. However you can use something like:

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Or

Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.

Example:

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}

How do I check what version of Python is running my script?

Put something like:

#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
  sys.stderr.write("You need python 2.6 or later to run this script\n")
  exit(1)

at the top of your script.

Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.

Changing the Git remote 'push to' default

Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:

git config remote.origin.url url-to-my-other-remote

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

How to insert multiple rows from array using CodeIgniter framework?

You could always use mysql's LOAD DATA:

LOAD DATA LOCAL INFILE '/full/path/to/file/foo.csv' INTO TABLE `footable` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' 

to do bulk inserts rather than using a bunch of INSERT statements.

assignment operator overloading in c++

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.

findViewByID returns null

Set the activity content from a layout resource. ie.,setContentView(R.layout.basicXml);

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

How to remove "href" with Jquery?

Your title question and your example are completely different. I'll start by answering the title question:

$("a").removeAttr("href");

And as far as not requiring an href, the generally accepted way of doing this is:

<a href"#" onclick="doWork(); return false;">link</a>

The return false is necessary so that the href doesn't actually go anywhere.

How to properly seed random number generator

@[Denys Séguret] has posted correct. But In my case I need new seed everytime hence below code;

Incase you need quick functions. I use like this.


func RandInt(min, max int) int {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    return r.Intn(max-min) + min
}

func RandFloat(min, max float64) float64 {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    return min + r.Float64()*(max-min)
}

source

The FastCGI process exited unexpectedly

For user using PHP 5.6.x follow this link and install the x86 version.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How to save/restore serializable object to/from file?

You can use JsonConvert from Newtonsoft library. To serialize an object and write to a file in json format:

File.WriteAllText(filePath, JsonConvert.SerializeObject(obj));

And to deserialize it back into object:

var obj = JsonConvert.DeserializeObject<ObjType>(File.ReadAllText(filePath));

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

finding first day of the month in python

Yes, first set a datetime to the start of the current month.

Second test if current date day > 25 and get a true/false on that. If True then add add one month to the start of month datetime object. If false then use the datetime object with the value set to the beginning of the month.

import datetime 
from dateutil.relativedelta import relativedelta

todayDate = datetime.date.today()
resultDate = todayDate.replace(day=1)

if ((todayDate - resultDate).days > 25):
    resultDate = resultDate + relativedelta(months=1)

print resultDate

How to use Apple's new San Francisco font on a webpage

Last tested in 2015

Should use this solution as a last choice, when other solutions don't work.


Original answer:

Work on macOS Chrome/Safari

body { font-family: '.SFNSDisplay-Regular', sans-serif; }

How to sort a data frame by alphabetic order of a character variable in R?

#sort dataframe by col
sort.df <- with(df,  df[order(sortbythiscolumn) , ])

#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])

#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

How to get the number of days of difference between two dates on mysql?

I prefer TIMESTAMPDIFF because you can easily change the unit if need be.

How to deal with floating point number precision in JavaScript?

I like Pedro Ladaria's solution and use something similar.

function strip(number) {
    return (parseFloat(number).toPrecision(12));
}

Unlike Pedros solution this will round up 0.999...repeating and is accurate to plus/minus one on the least significant digit.

Note: When dealing with 32 or 64 bit floats, you should use toPrecision(7) and toPrecision(15) for best results. See this question for info as to why.

Is there a way to run Python on Android?

Here are some tools listed in official python website


There is an app called QPython3 in playstore which can be used for both editing and running python script.

Playstore link


Another app called Termux in which you can install python using command

pkg install python

Playstore Link


If you want develop apps , there is Python Android Scripting Layer (SL4A) .

The Scripting Layer for Android, SL4A, is an open source application that allows programs written in a range of interpreted languages to run on Android. It also provides a high level API that allows these programs to interact with the Android device, making it easy to do stuff like accessing sensor data, sending an SMS, rendering user interfaces and so on.


You can also check PySide for Android, which is actually Python bindings for the Qt 4.


There's a platform called PyMob where apps can be written purely in Python and the compiler tool-flow (PyMob) converts them in native source codes for various platforms.


Also check python-for-android

python-for-android is an open source build tool to let you package Python code into standalone android APKs. These can be passed around, installed, or uploaded to marketplaces such as the Play Store just like any other Android app. This tool was originally developed for the Kivy cross-platform graphical framework, but now supports multiple bootstraps and can be easily extended to package other types of Python apps for Android.


Try Chaquopy A Python SDK for Android


Anddd... BeeWare

BeeWare allows you to write your app in Python and release it on multiple platforms. No need to rewrite the app in multiple programming languages. It means no issues with build tools, environments, compatibility, etc.

what is the use of Eval() in asp.net

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

<asp:TemplateField>
<ItemTemplate>
        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
        </asp:Label>
</ItemTemplate>
</asp:TemplateField>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:

SQLSVCACCOUNT:                 NT AUTHORITY\SYSTEM

According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I have occurred the same error look following example-

async.waterfall([function(waterCB) {
    waterCB(null);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.

Cheak your function parameters Below are a correct example.

async.waterfall([function(waterCB) {
    waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

Thanks

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Error: JAVA_HOME is not defined correctly executing maven

It happens because of the reason mentioned below :

If you see the mvn script: The code fails here ---

Steps for debugging and fixing:

Step 1: Open the mvn script /Users/Username/apache-maven-3.0.5/bin/mvn (Open with the less command like: less /Users/Username/apache-maven-3.0.5/bin/mvn)

Step 2: Find out the below code in the script:

  if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi

Step3: It is happening because JAVACMD variable was not set. So it displays the error.

Note: To Fix it

export JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin/java

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/

Key: If you want it to be permanent open emacs .profile

post the commands and press Ctrl-x Ctrl-c ( save-buffers-kill-terminal ).

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

"For me to make it work again I just deleted the files

ib_logfile0 and

ib_logfile1 .

from :

/Applications/MAMP/db/mysql56/ib_logfile0 "

On XAMPP its Xampp/xamppfiles/var/mysql

Got this from PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

how to read xml file from url using php

Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On on php.ini)

Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:

<?php
if (($response_xml_data = file_get_contents($map_url))===false){
    echo "Error fetching XML\n";
} else {
   libxml_use_internal_errors(true);
   $data = simplexml_load_string($response_xml_data);
   if (!$data) {
       echo "Error loading XML\n";
       foreach(libxml_get_errors() as $error) {
           echo "\t", $error->message;
       }
   } else {
      print_r($data);
   }
}
?>

If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents() on example 4 at http://php.net/manual/en/function.file-get-contents.php

How to generate the whole database script in MySQL Workbench?

Try the export function of phpMyAdmin.

I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.

PHP Undefined Index

The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.

When you submit the form it will then exist, and it won't complain about it.

#so change
$_GET['query_age'];
#to:
(!empty($_GET['query_age']) ? $_GET['query_age'] : null);

How to tell if a file is git tracked (by shell exit code)?

I suggest a custom alias on you .gitconfig.

You have to way to do:

1) With git command:

git config --global alias.check-file <command>

2) Editing ~/.gitconfig and add this line on alias section:

[alias]
    check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi;  };  f"

Once launched command (1) or saved file (2), on your workspace you can test it:

$ git check-file
$ Filename missing 

$ git check-file README.md
$ File tracked 

$ git check-file foo
$ File not tracked

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I have upgraded my older version of WCF to WCF 4 with below changes, hope you can also make the similar changes.

1. Web.config:

<system.serviceModel>
      <bindings>
        <basicHttpBinding>
          <binding name="Demo_BasicHttp">
            <security mode="TransportCredentialOnly">
              <transport clientCredentialType="InheritedFromHost"/>
            </security>
          </binding>
        </basicHttpBinding>
      </bindings>
      <services>
        <service name="DemoServices.CalculatorService.ServiceImplementation.CalculatorService" behaviorConfiguration="Demo_ServiceBehavior">
          <endpoint address="" binding="basicHttpBinding"
              bindingConfiguration="Demo_BasicHttp" contract="DemoServices.CalculatorService.ServiceContracts.ICalculatorServiceContract">
            <identity>
              <dns value="localhost"/>
            </identity>
          </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="Demo_ServiceBehavior">
            <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
            <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <protocolMapping>
        <add scheme="http" binding="basicHttpBinding" bindingConfiguration="Demo_BasicHttp"/>
      </protocolMapping>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>

2. App.config:

    <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ICalculatorServiceContract" maxBufferSize="2147483647" maxBufferPoolSize="33554432" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="00:10:00">
          <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="4096" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Ntlm" proxyCredentialType="None" realm="" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:24357/CalculatorService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICalculatorServiceContract" contract="ICalculatorServiceContract" name="Demo_BasicHttp" />
    </client>
  </system.serviceModel>

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

what is trailing whitespace and how can I handle this?

Trailing whitespace:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

Strip them:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893

Using union and order by clause in mysql

When you use an ORDER BY clause inside of a sub query used in conjunction with a UNION mysql will optimise away the ORDER BY clause.

This is because by default a UNION returns an unordered list so therefore an ORDER BY would do nothing.

The optimisation is mentioned in the docs and says:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.

The last sentence of this is a bit misleading because it should have an effect. This optimisation causes a problem when you are in a situation where you need to order within the subquery.

To force MySQL to not do this optimisation you can add a LIMIT clause like so:

(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999)
UNION ALL
(SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999)
UNION ALL
(SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)

A high LIMIT means that you could add an OFFSET on the overall query if you want to do something such as pagination.

This also gives you the added benefit of being able to ORDER BY different columns for each union.

Int to byte array

Update for 2020 - BinaryPrimitives should now be preferred over BitConverter. It provides endian-specific APIs, and is less allocatey.


byte[] bytes = BitConverter.GetBytes(i);

although note also that you might want to check BitConverter.IsLittleEndian to see which way around that is going to appear!

Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>> / <<), or by using unsafe code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

MySQL Sum() multiple columns

The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?

If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.

Then your query would be

SELECT subject, SUM(mark) total 
FROM Subjects s 
  INNER JOIN Marks m ON m.subject_id = s.id
GROUP BY s.id

unix - count of columns in file

This is usually what I use for counting the number of fields:

head -n 1 file.name | awk -F'|' '{print NF; exit}'

How can I get the status code from an http error in Axios?

You can use the spread operator (...) to force it into a new object like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({...error}) 
})

Be aware: this will not be an instance of Error.

Creating and returning Observable from Angular 2 Service

UPDATE: 9/24/16 Angular 2.0 Stable

This question gets a lot of traffic still, so, I wanted to update it. With the insanity of changes from Alpha, Beta, and 7 RC candidates, I stopped updating my SO answers until they went stable.

This is the perfect case for using Subjects and ReplaySubjects

I personally prefer to use ReplaySubject(1) as it allows the last stored value to be passed when new subscribers attach even when late:

let project = new ReplaySubject(1);

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject
    project.next(result));

    //add delayed subscription AFTER loaded
    setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});

//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234

So even if I attach late or need to load later I can always get the latest call and not worry about missing the callback.

This also lets you use the same stream to push down onto:

project.next(5678);
//output
//Subscription Streaming: 5678

But what if you are 100% sure, that you only need to do the call once? Leaving open subjects and observables isn't good but there's always that "What If?"

That's where AsyncSubject comes in.

let project = new AsyncSubject();

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
                  err => console.log(err),
                  () => console.log('Completed'));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject and complete
    project.next(result));
    project.complete();

    //add a subscription even though completed
    setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});

//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234

Awesome! Even though we closed the subject it still replied with the last thing it loaded.

Another thing is how we subscribed to that http call and handled the response. Map is great to process the response.

public call = http.get(whatever).map(res => res.json())

But what if we needed to nest those calls? Yes you could use subjects with a special function:

getThing() {
    resultSubject = new ReplaySubject(1);

    http.get('path').subscribe(result1 => {
        http.get('other/path/' + result1).get.subscribe(response2 => {
            http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
        })
    })
    return resultSubject;
}
var myThing = getThing();

But that's a lot and means you need a function to do it. Enter FlatMap:

var myThing = http.get('path').flatMap(result1 => 
                    http.get('other/' + result1).flatMap(response2 => 
                        http.get('another/' + response2)));

Sweet, the var is an observable that gets the data from the final http call.

OK thats great but I want an angular2 service!

I got you:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';

@Injectable()
export class ProjectService {

  public activeProject:ReplaySubject<any> = new ReplaySubject(1);

  constructor(private http: Http) {}

  //load the project
  public load(projectId) {
    console.log('Loading Project:' + projectId, Date.now());
    this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
    return this.activeProject;
  }

 }

 //component

@Component({
    selector: 'nav',
    template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
 export class navComponent implements OnInit {
    public project:any;

    constructor(private projectService:ProjectService) {}

    ngOnInit() {
        this.projectService.activeProject.subscribe(active => this.project = active);
    }

    public load(projectId:string) {
        this.projectService.load(projectId);
    }

 }

I'm a big fan of observers and observables so I hope this update helps!

Original Answer

I think this is a use case of using a Observable Subject or in Angular2 the EventEmitter.

In your service you create a EventEmitter that allows you to push values onto it. In Alpha 45 you have to convert it with toRx(), but I know they were working to get rid of that, so in Alpha 46 you may be able to simply return the EvenEmitter.

class EventService {
  _emitter: EventEmitter = new EventEmitter();
  rxEmitter: any;
  constructor() {
    this.rxEmitter = this._emitter.toRx();
  }
  doSomething(data){
    this.rxEmitter.next(data);
  }
}

This way has the single EventEmitter that your different service functions can now push onto.

If you wanted to return an observable directly from a call you could do something like this:

myHttpCall(path) {
    return Observable.create(observer => {
        http.get(path).map(res => res.json()).subscribe((result) => {
            //do something with result. 
            var newResultArray = mySpecialArrayFunction(result);
            observer.next(newResultArray);
            //call complete if you want to close this stream (like a promise)
            observer.complete();
        });
    });
}

That would allow you do this in the component: peopleService.myHttpCall('path').subscribe(people => this.people = people);

And mess with the results from the call in your service.

I like creating the EventEmitter stream on its own in case I need to get access to it from other components, but I could see both ways working...

Here's a plunker that shows a basic service with an event emitter: Plunkr

Using setTimeout to delay timing of jQuery actions

.html() only takes a string OR a function as an argument, not both. Try this:

 $("#showDiv").click(function () {
     $('#theDiv').show(1000, function () {
         setTimeout(function () {
             $('#theDiv').html(function () {
                 setTimeout(function () {
                     $('#theDiv').html('Here is some replacement text');
                 }, 0);
                 setTimeout(function () {
                     $('#theDiv').html('More replacement text goes here');
                 }, 2500);
             });
         }, 2500);
     });
 }); //click function ends

jsFiddle example

Regex to replace multiple spaces with a single space

var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

Or if you also want to replace tabs:

var replaced = string.replace(/\s+/g, " ");

How to add Tomcat Server in eclipse

The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.

You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

There's no magical solution of displaying something outside an overflow hidden container.

A similar effect can be achieved by having an absolute positioned div that matches the size of its parent by positioning it inside your current relative container (the div you don't wish to clip should be outside this div):

#1 .mask {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 1;
  overflow: hidden;
}

Take in mind that if you only have to clip content on the x axis (which appears to be your case, as you only have set the div's width), you can use overflow-x: hidden.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

You can simply use decimal.ToString()

For two decimals

myDecimal.ToString("0.00");

For four decimals

myDecimal.ToString("0.0000");

This gives dot as decimal separator, and no thousand separator regardless of culture.

"Items collection must be empty before using ItemsSource."

In My case, it was just an extra StackPanel inside the ListView:

<ListView Name="_details" Margin="50,0,50,0">
            <StackPanel Orientation="Vertical">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                    <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                    <ItemsControl ItemsSource="{Binding Items}"/>
                </StackPanel>
            </StackPanel>
        </ListView>

Becomes:

<ListView Name="_details" Margin="50,0,50,0">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                    <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                    <ItemsControl ItemsSource="{Binding Items}"/>
                </StackPanel>
        </ListView>

and all is well.

intellij incorrectly saying no beans of type found for autowired repository

Check if the package of your bean is written correctly

//Check if this is written right 
package com.package1.package2.package3


import ...

@Service
class ServiceX {

  ...

}

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME is affected by NTP, and can move forwards and backwards. CLOCK_MONOTONIC is not, and advances at one tick per tick.

Can we cast a generic object to a custom object type in javascript?

This worked for me. It's simple for simple objects.

_x000D_
_x000D_
class Person {_x000D_
  constructor(firstName, lastName) {_x000D_
    this.firstName = firstName;_x000D_
    this.lastName = lastName;_x000D_
  }_x000D_
  getFullName() {_x000D_
    return this.lastName + " " + this.firstName;_x000D_
  }_x000D_
_x000D_
  static class(obj) {_x000D_
    return new Person(obj.firstName, obj.lastName);_x000D_
  }_x000D_
}_x000D_
_x000D_
var person1 = {_x000D_
  lastName: "Freeman",_x000D_
  firstName: "Gordon"_x000D_
};_x000D_
_x000D_
var gordon = Person.class(person1);_x000D_
console.log(gordon.getFullName());
_x000D_
_x000D_
_x000D_

I was also searching for a simple solution, and this is what I came up with, based on all other answers and my research. Basically, class Person has another constructor, called 'class' which works with a generic object of the same 'format' as Person. I hope this might help somebody as well.

What is the difference between “int” and “uint” / “long” and “ulong”?

The difference is that the uint and ulong are unsigned data types, meaning the range is different: They do not accept negative values:

int range: -2,147,483,648 to 2,147,483,647
uint range: 0 to 4,294,967,295

long range: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong range: 0 to 18,446,744,073,709,551,615

Chart.js - Formatting Y axis

Here you can find a good example of how to format Y-Axis value.

Also, you can use scaleLabel : "<%=value%>" that you mentioned, It basically means that everything between <%= and %> tags will be treated as javascript code (i.e you can use if statments...)

Textarea to resize based on content length

You may also try contenteditable attribute onto a normal p or div. Not really a textarea but it will auto-resize without script.

_x000D_
_x000D_
.divtext {
    border: ridge 2px;
    padding: 5px;
    width: 20em;
    min-height: 5em;
    overflow: auto;
}
_x000D_
<div class="divtext" contentEditable>Hello World</div>
_x000D_
_x000D_
_x000D_

How to use ng-repeat without an html element

for a solution that really works

html

<remove  ng-repeat-start="itemGroup in Groups" ></remove>
   html stuff in here including inner repeating loops if you want
<remove  ng-repeat-end></remove>

add an angular.js directive

//remove directive
(function(){
    var remove = function(){

        return {    
            restrict: "E",
            replace: true,
            link: function(scope, element, attrs, controller){
                element.replaceWith('<!--removed element-->');
            }
        };

    };
    var module = angular.module("app" );
    module.directive('remove', [remove]);
}());

for a brief explanation,

ng-repeat binds itself to the <remove> element and loops as it should, and because we have used ng-repeat-start / ng-repeat-end it loops a block of html not just an element.

then the custom remove directive places the <remove> start and finish elements with <!--removed element-->

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

In your case, the first value to insert must be NULL, because it's AUTO_INCREMENT.

Working copy locked error in tortoise svn while committing

Windows Solution:

https://sourceforge.net/projects/win32svn/

1.Download it, then add it to system path.

2.Go to work directory execute "svn clean" and "svn update" in cmd.

ImportError: cannot import name NUMPY_MKL

Reinstall numpy-1.11.0_XXX.whl (for your Python) from www.lfd.uci.edu/~gohlke/pythonlibs. This file has the same name and version if compare with the variant downloaded by me earlier 29.03.2016, but its size and content differ from old variant. After re-installation error disappeared.

Second option - return back to scipy 0.17.0 from 0.17.1

P.S. I use Windows 64-bit version of Python 3.5.1, so can't guarantee that numpy for Python 2.7 is already corrected.

How to randomize two ArrayLists in the same fashion?

Wrap them in another class so that you can end up with a single array or List of those objects.

public class Data {
    private String txtFileName;
    private String imgFileName;

    // Add/generate c'tor, getter/setter, equals, hashCode and other boilerplate.
}

Usage example:

List<Data> list = new ArrayList<Data>();
list.add(new Data("H1.txt", "e1.jpg"));
list.add(new Data("H2.txt", "e2.jpg"));
// ...

Collections.shuffle(list);

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

In android studio: reduce minSDKversion. It will work...

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "healthcare.acceliant.trianz.com.myapplication"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
}

How to open a website when a Button is clicked in Android application?

You can wrap the buttons in anchors that href to the appropriate website.

<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>

When the user clicks the button (input) they are directed to the destination specified in the href property of the anchor.

Edit: Oops, I didn't read "Eclipse" in the question title. My mistake.

You can't specify target table for update in FROM clause

The problem is that MySQL, for whatever inane reason, doesn't allow you to write queries like this:

UPDATE myTable
SET myTable.A =
(
    SELECT B
    FROM myTable
    INNER JOIN ...
)

That is, if you're doing an UPDATE/INSERT/DELETE on a table, you can't reference that table in an inner query (you can however reference a field from that outer table...)


The solution is to replace the instance of myTable in the sub-query with (SELECT * FROM myTable), like this

UPDATE myTable
SET myTable.A =
(
    SELECT B
    FROM (SELECT * FROM myTable) AS something
    INNER JOIN ...
)

This apparently causes the necessary fields to be implicitly copied into a temporary table, so it's allowed.

I found this solution here. A note from that article:

You don’t want to just SELECT * FROM table in the subquery in real life; I just wanted to keep the examples simple. In reality, you should only be selecting the columns you need in that innermost query, and adding a good WHERE clause to limit the results, too.

iFrame onload JavaScript event

Your code is correct. Just test to ensure it is being called like:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>

What is the Gradle artifact dependency graph command?

The command is gradle dependencies, and its output is much improved in Gradle 1.2. (You can already try 1.2-rc-1 today.)

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

Gradients in Internet Explorer 9

The code I use for all browser gradients:

background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;

You will need to specify a height or zoom: 1 to apply hasLayout to the element for this to work in IE.


Update:

Here is a LESS Mixin (CSS) version for all you LESS users out there:

.gradient(@start, @end) {
    background: mix(@start, @end, 50%);
    filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
    background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
    background: -webkit-linear-gradient(@start, @end);
    background: -moz-linear-gradient(top, @start, @end);
    background: -ms-linear-gradient(@start, @end);
    background: -o-linear-gradient(@start, @end);
    background: linear-gradient(@start, @end);
    zoom: 1;
}

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

RegEx to exclude a specific string constant

Try this regular expression:

^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$

It describes three cases:

  1. less than three arbitrary character
  2. exactly three characters, while either
    • the first is not A, or
    • the first is A but the second is not B, or
    • the first is A, the second B but the third is not C
  3. more than three arbitrary characters

Press any key to continue

Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Example:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

Javascript regular expression password validation having special characters

Don't try and do too much in one step. Keep each rule separate.

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters");
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter."); 
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit.");
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

Beautiful Soup and extracting a div and its contents by ID

To find an element by its id:

div = soup.find(id="articlebody")

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

npm config set strict-ssl false -g

To save it globally

How can I know when an EditText loses focus?

Using Java 8 lambda expression:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );
    }        
});

What is "stdafx.h" used for in Visual Studio?

It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.

If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

How can I stop Chrome from going into debug mode?

If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.

I suggest you "Disable all break points":

Enter image description here

Source:

https://javascript.info/debugging-chrome

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

jQuery / Javascript code check, if not undefined

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

jQuery $("#radioButton").change(...) not firing during de-selection

<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>                  

jquery part

$(".rg").change(function () {

if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', 'disabled');
        }
                    });

here is the DEMO

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

What is the difference between MVC and MVVM?

MVVM Model-View ViewModel is similar to MVC, Model-View Controller

The controller is replaced with a ViewModel. The ViewModel sits below the UI layer. The ViewModel exposes the data and command objects that the view needs. You could think of this as a container object that view goes to get its data and actions from. The ViewModel pulls its data from the model.

Russel East does a blog discussing more in detail Why is MVVM is different from MVC

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}

Credit card payment gateway in PHP?

There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.

The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.

All that being said companies like PayPal have a PHP SDK:

https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks

Authorize.Net:

http://developer.authorize.net/samplecode/

Those are two of the more popular ones for the United States.

For PCI Info see:

https://www.pcisecuritystandards.org/

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

Eclipse CDT: Symbol 'cout' could not be resolved

Thanks loads for the answers above. I'm adding an answer for a specific use-case...

On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration as well as to add /usr/include/c++/4.7, /usr/include and /usr/include/c++/4.7/x86_64-linux-gnu to Project Properties -> C/C++ General -> Paths and Symbols and then to rebuild the index.

How can I get last characters of a string

Last 5

_x000D_
_x000D_
var id="ctl03_Tabs1";_x000D_
var res = id.charAt(id.length-5)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Last

_x000D_
_x000D_
   _x000D_
 var id="ctl03_Tabs1";_x000D_
 var res = id.charAt(id.length-1)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Simplest way to set image as JPanel background

As I know the way you can do it is to override paintComponent method that demands to inherit JPanel

 @Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); // paint the background image and scale it to fill the entire space
    g.drawImage(/*....*/);
}

The other way (a bit complicated) to create second custom JPanel and put is as background for your main

ImagePanel

public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;

public ImagePanel(Image image)
{
    this.image = image;
    this.iWidth2 = image.getWidth(this)/2;
    this.iHeight2 = image.getHeight(this)/2;
}


public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    if (image != null)
    {
        int x = this.getParent().getWidth()/2 - iWidth2;
        int y = this.getParent().getHeight()/2 - iHeight2;
        g.drawImage(image,x,y,this);
    }
}
}

EmptyPanel

public class EmptyPanel extends JPanel{

private static final long serialVersionUID = 1L;

public EmptyPanel() {
    super();
    init();
}

@Override
public boolean isOptimizedDrawingEnabled() {
    return false;
}


public void init(){

    LayoutManager overlay = new OverlayLayout(this);
    this.setLayout(overlay);

    ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
    iPanel.setLayout(new BorderLayout());   
    this.add(iPanel);
    iPanel.setOpaque(false);                
}
}

IconToImage

public class IconToImage {

Icon icon;
Image image;


public IconToImage(Icon icon) {
    this.icon = icon;
    image = iconToImage();
}

public Image iconToImage() { 
    if (icon instanceof ImageIcon) { 
        return ((ImageIcon)icon).getImage(); 
    } else { 
        int w = icon.getIconWidth(); 
        int h = icon.getIconHeight(); 
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
        GraphicsDevice gd = ge.getDefaultScreenDevice(); 
        GraphicsConfiguration gc = gd.getDefaultConfiguration(); 
        BufferedImage image = gc.createCompatibleImage(w, h); 
        Graphics2D g = image.createGraphics(); 
        icon.paintIcon(null, g, 0, 0); 
        g.dispose(); 
        return image; 
    } 
}


/**
 * @return the image
 */
public Image getImage() {
    return image;
}
}

Difference between Divide and Conquer Algo and Dynamic Programming

I think of Divide & Conquer as an recursive approach and Dynamic Programming as table filling.

For example, Merge Sort is a Divide & Conquer algorithm, as in each step, you split the array into two halves, recursively call Merge Sort upon the two halves and then merge them.

Knapsack is a Dynamic Programming algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.

Javascript to stop HTML5 video playback on modal window close

Have a try:

_x000D_
_x000D_
function stop(){_x000D_
    var video = document.getElementById("video");_x000D_
    video.load();_x000D_
}
_x000D_
_x000D_
_x000D_

What is a daemon thread in Java?

Daemon threads are like assistants. Non-Daemon threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.

How to escape single quotes in MySQL

You can use this code,

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

if mysqli_real_escape_string() does not work.

How to disable XDebug

If you are using MAMP Pro on Mac OS X it's done via the MAMP client by unchecking Activate Xdebug under the PHP tab:

Disabling Xdebug in MAMP Pro

How to read an external local JSON file in JavaScript?

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

Write values in app.config file

private static string GetSetting(string key)
{
    return ConfigurationManager.AppSettings[key];
}

private static void SetSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);
    ConfigurationManager.RefreshSection("appSettings");
}

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

After taking a look at the API, you can pass the dialog your activity or getActivity if you're in a fragment, then forcefully clean it up with dialog.dismiss() in the return methods to prevent leaks.

Though it is not explicitly stated anywhere I know, it seems you are passed back the dialog in the OnClickHandlers just to do this.

How to cin to a vector

In this case your while loop will look like

int i = 0;
int a = 0;
while (i < n){
  cin >> a;
  V.push_back(a);
  ++i;
}

Convert string to Python class object?

Yes, you can do this. Assuming your classes exist in the global namespace, something like this will do it:

import types

class Foo:
    pass

def str_to_class(s):
    if s in globals() and isinstance(globals()[s], types.ClassType):
            return globals()[s]
    return None

str_to_class('Foo')

==> <class __main__.Foo at 0x340808cc>

The remote end hung up unexpectedly while git cloning

Check your internet speed. Also check the following commands:

$ git config --global http.postBuffer 2M
$ git pull origin master

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

How to use QTimer

  1. It's good practice to give a parent to your QTimer to use Qt's memory management system.

  2. update() is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.

  3. If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.

  4. Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.

How to get back to the latest commit after checking out a previous commit?

show all branches and commit
git log --branches --oneline

show last commit
git log --branches -1 --oneline

show before last commit
git log --branches -2 --oneline

Get checkbox values using checkbox name using jquery

You should include the brackets as well . . .

<input type="checkbox" name="bla[]" value="1" />

therefore referencing it should be as be name='bla[]'

$(document).ready( function () { 

   $("input[name='bla[]']").each( function () {
       alert( $(this).val() );
   });

});

push() a two-dimensional array

The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).

In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

JS. How to replace html element with another element/text, represented in string?

As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)

The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.

Here is the code

var str = '<a href="http://www.com">item to replace</a>'; //it can be anything
var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
if(Obj.outerHTML) { //if outerHTML is supported
    Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
}
else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
    var tmpObj=document.createElement("div");
    tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
    ObjParent=Obj.parentNode; //Okey, element should be parented
    ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
    ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
}

That's all

Use Toast inside Fragment

If you are using kotlin then the context will be already defined in the fragment. So just use that context. Try the following code to show a toast message.

Toast.makeText(context , "your_text", Toast.LENGTH_SHORT).show()