Programs & Examples On #Livechat

Live chat is software or web widget which allows users to communicate with each other, or with an administrator in real time.

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

Make a float only show two decimal places

Another method for Swift (without using NSString):

let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %@", percentage, "%")

P.S. this solution is not working with CGFloat type only tested with Float & Double

The simplest way to resize an UIImage?

Here's a modification of the category written by iWasRobbed above. It keeps the aspect ratio of the original image instead of distorting it.

- (UIImage*)scaleToSizeKeepAspect:(CGSize)size {
    UIGraphicsBeginImageContext(size);

    CGFloat ws = size.width/self.size.width;
    CGFloat hs = size.height/self.size.height;

    if (ws > hs) {
        ws = hs/ws;
        hs = 1.0;
    } else {
        hs = ws/hs;
        ws = 1.0;
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(size.width/2-(size.width*ws)/2,
        size.height/2-(size.height*hs)/2, size.width*ws,
        size.height*hs), self.CGImage);

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;
}

How can I zoom an HTML element in Firefox and Opera?

zoom: 145%;
-moz-transform: scale(1.45);

use this to be on the safer side

Convert Set to List without creating new List

We can use following one liner in Java 8:

List<String> list = set.stream().collect(Collectors.toList());

Here is one small example:

public static void main(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        List<String> list = set.stream().collect(Collectors.toList());
}

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

What is the difference between git clone and checkout?

The man page for checkout: http://git-scm.com/docs/git-checkout

The man page for clone: http://git-scm.com/docs/git-clone

To sum it up, clone is for fetching repositories you don't have, checkout is for switching between branches in a repository you already have.

Note: for those who have a SVN/CVS background and new to Git, the equivalent of git clone in SVN/CVS is checkout. The same wording of different terms is often confusing.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

Read user input inside a loop

echo "Enter the Programs you want to run:"
> ${PROGRAM_LIST}
while read PROGRAM_ENTRY
do
   if [ ! -s ${PROGRAM_ENTRY} ]
   then
      echo ${PROGRAM_ENTRY} >> ${PROGRAM_LIST}
   else
      break
   fi
done

Collection that allows only unique items in .NET?

If all you need is to ensure uniqueness of elements, then HashSet is what you need.

What do you mean when you say "just a set implementation"? A set is (by definition) a collection of unique elements that doesn't save element order.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

gradle build fails on lint task

With 0.7.0 there comes extended support for Lint, however, it does not work always properly. (Eg. the butterknife library)

Solution is to disable aborting build on found lint errors

I took the inspiration from https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7

(implementation: https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7/build-system/gradle/src/main/groovy/com/android/build/gradle/internal/model/DefaultAndroidProject.java )

(discussion: https://plus.google.com/+AndroidDevelopers/posts/ersS6fMLxw1 )

android {
  // your build config
  defaultConfig { ... }
  signingConfigs { ... }
  compileOptions { ... }
  buildTypes { ... }
  // This is important, it will run lint checks but won't abort build
  lintOptions {
      abortOnError false
  }
}

And if you need to disable just particular Lint rule and keep the build failing on others, use this:

/*
 * Use only 'disable' or only 'enable', those configurations exclude each other
 */
android {
  lintOptions {
    // use this line to check all rules except those listed
    disable 'RuleToDisable', 'SecondRuleToDisable'
    // use this line to check just listed rules
    enable 'FirstRuleToCheck', 'LastRuleToCheck'
  }
}

Programmatically go back to the previous fragment in the backstack

This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.

On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !

Inside activities on back pressed put this:

Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");

if (home instanceof FragmentDetailedPizza && home.isVisible()) {
    if (getFragmentManager().getBackStackEntryCount() != 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
} else {
    //Primary fragment
    moveTaskToBack(true);
}

And launch the other fragment like this:

Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();

Joining two lists together

List<string> list1 = new List<string>();
list1.Add("dot");
list1.Add("net");

List<string> list2 = new List<string>();
list2.Add("pearls");
list2.Add("!");

var result = list1.Concat(list2);

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

Enabling CORS in Cloud Functions for Firebase

For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.

Error in Swift class: Property not initialized at super.init call

Quote from The Swift Programming Language, which answers your question:

“Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:”

Safety check 1 “A designated initializer must ensure that all of the “properties introduced by its class are initialized before it delegates up to a superclass initializer.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

Check if a input box is empty

Another approach is using regex , as show below , you can use the empty regex pattern and achieve the same using ng-pattern

HTML :

 <body ng-app="app" ng-controller="formController">
 <form name="myform">
 <input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
 <span ng-show="myform.myfield.$error.pattern">Please enter!</span>
 <span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>

Controller:@formController :

var App = angular.module('app', []);
App.controller('formController', function ($scope) {              
  $scope.mypattern = /^\s*$/g;
});

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

When to use If-else if-else over switch statements and vice versa

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

Ways to save enums in database

All my experience tells me that safest way of persisting enums anywhere is to use additional code value or id (some kind of evolution of @jeebee answer). This could be a nice example of an idea:

enum Race {
    HUMAN ("human"),
    ELF ("elf"),
    DWARF ("dwarf");

    private final String code;

    private Race(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

Now you can go with any persistence referencing your enum constants by it's code. Even if you'll decide to change some of constant names, you always can save code value (e.g. DWARF("dwarf") to GNOME("dwarf"))

Ok, dive some more deeper with this conception. Here is some utility method, that helps you find any enum value, but first lets extend our approach.

interface CodeValue {
    String getCode();
}

And let our enum implement it:

enum Race implement CodeValue {...}

This is the time for magic search method:

static <T extends Enum & CodeValue> T resolveByCode(Class<T> enumClass, String code) {
    T[] enumConstants = enumClass.getEnumConstants();
    for (T entry : enumConstants) {
        if (entry.getCode().equals(code)) return entry;
    }
    // In case we failed to find it, return null.
    // I'd recommend you make some log record here to get notified about wrong logic, perhaps.
    return null;
}

And use it like a charm: Race race = resolveByCode(Race.class, "elf")

How can I check if the array of objects have duplicate property values?

ECMA Script 6 Version

If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.


ECMA Script 5 Version

If you don't have Set support, then you can use a normal JavaScript object itself, like this

var seen = {};
var hasDuplicates = values.some(function(currentObject) {

    if (seen.hasOwnProperty(currentObject.name)) {
        // Current name is already seen
        return true;
    }

    // Current name is being seen for the first time
    return (seen[currentObject.name] = false);
});

The same can be written succinctly, like this

var seen = {};
var hasDuplicates = values.some(function (currentObject) {
    return seen.hasOwnProperty(currentObject.name)
        || (seen[currentObject.name] = false);
});

Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.

How to easily get network path to the file you are working on?

Answer to my own question. The only way I have found that works consistently and instantaneously is to:

1) Create a link in my "Favorites" to the directory I use

2) Update the properties on that favorite to be an absolute path (\\ads\IT-DEPT-DFS\Data\MAILROOM)

3) When saving a new file, I navigate to that directory only via the Favorites directory created above (or you can use any Shortcut with an absolute path)

4) After saving, go to the File tab and the full path can be copied from the top of the Info (default) section

What is a typedef enum in Objective-C?

typedef enum {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;

then you can use it like :-

 ShapeType shape;

and

 enum {
    kCircle,
    kRectangle,
    kOblateSpheroid
} 
ShapeType;

now you can use it like:-

enum ShapeType shape;

What is Python Whitespace and how does it work?

something
{
 something1
 something2
}
something3

In Python

Something
    something1
    something2
something3

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

<button> background image

try this way

<button> 
    <img height="100%" src="images/s.png"/>
</button>

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The docker run command has a --ulimit flag you can use this flag to set the open file limit in your docker container.

Run the following command when spinning up your container to set the open file limit.

docker run --ulimit nofile=<softlimit>:<hardlimit> the first value before the colon indicates the soft file limit and the value after the colon indicates the hard file limit. you can verify this by running your container in interactive mode and executing the following command in your containers shell ulimit -n

PS: check out this blog post for more clarity

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Undoing a git rebase

It annoys me to no end that none of these answers is fully automatic, despite the fact that it should be automatable (at least mostly). I created a set of aliases to try to remedy this:

# Useful commands
#################

# Undo the last rebase
undo-rebase = "! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \"$PREV_COMMIT\" \"$@\";}; f"

# See what changed since the last rebase
rdiff = "!f() { : git diff ; git diff `git x-rev-before-rebase` "$@";}; f"

# Helpers
########
# Get the revision before the last rebase started
x-rev-before-rebase = !git reflog --skip=1 -1 \"`git x-start-of-rebase`\" --format=\"%gD\"

# Get the revision that started the rebase
x-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format="%gD"

You should be able to tweak this to allow going back an arbitrary number of rebases pretty easily (juggling the args is the trickiest part), which can be useful if you do a number of rebases in quick succession and mess something up along the way.

Caveats

It will get confused if any commit messages begin with "rebase (start)" (please don't do this). You could make the regex more resilient to improve the situation by matching something like this for your regex:

--grep-reflog "^rebase (start): checkout " 

WARNING: not tested (regex may need adjustments)

The reason I haven't done this is because I'm not 100% that a rebase always begins with a checkout. Can anyone confirm this?

[If you're curious about the null (:) commands at the beginning of the function, that's a way of setting up bash completions for the aliases]

nuget 'packages' element is not declared warning

This works and remains even after adding a new package:

Add the following !DOCTYPE above the <packages> element:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE packages [
  <!ELEMENT packages (package*)>
  <!ELEMENT package EMPTY>
  <!ATTLIST package
  id CDATA #REQUIRED
  version CDATA #REQUIRED
  targetFramework CDATA #REQUIRED
  developmentDependency CDATA #IMPLIED>
]>

Creating executable files in Linux

What you describe is the correct way to handle this.

You said that you want to stay in the GUI. You can usually set the execute bit through the file properties menu. You could also learn how to create a custom action for the context menu to do this for you if you're so inclined. This depends on your desktop environment of course.

If you use a more advanced editor, you can script the action to happen when the file is saved. For example (I'm only really familiar with vim), you could add this to your .vimrc to make any new file that starts with "#!/*/bin/*" executable.

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif

How to cherry-pick from a remote branch?

Since "zebra" is a remote branch, I was thinking I don't have its data locally.

You are correct that you don't have the right data, but tried to resolve it in the wrong way. To collect data locally from a remote source, you need to use git fetch. When you did git checkout zebra you switched to whatever the state of that branch was the last time you fetched. So fetch from the remote first:

# fetch just the one remote
git fetch <remote>
# or fetch from all remotes
git fetch --all
# make sure you're back on the branch you want to cherry-pick to
git cherry-pick xyz

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

How can I change the Java Runtime Version on Windows (7)?

If you are using windows 10 or windows server 2012, the steps to change the java runtime version is this:

  1. Open regedit using 'Run'
  2. Navigate to HKEY_LOCAL_MACHINE -> SOFTWARE -> JavaSoft -> Java Runtime Environment
  3. Here you will see all the versions of java you installed on your PC. For me I have several versions of java 1.8 installed, so the folder displayed here are 1.8, 1.8.0_162 and 1.8.0_171
  4. Click the '1.8' folder, then double click the JavaHome and RuntimeLib keys, Change the version number inside to whichever Java version you want your PC to run on. For example, if the Value data of the key is 'C:\Program Files\Java\jre1.8.0_171', you can change this to 'C:\Program Files\Java\jre1.8.0_162'.
  5. You can then verify the version change by typing 'java -version' on the command line.

Padding characters in printf

This one is even simpler and execs no external commands.

$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"

JBoss............... [UP]

Inserting a value into all possible locations in a list

If you want to insert a list into a list, you can do this:

>>> a = [1,2,3,4,5]
>>> for x in reversed(['a','b','c']): a.insert(2,x)
>>> a
[1, 2, 'a', 'b', 'c', 3, 4, 5]

Fatal error: Call to undefined function mb_strlen()

For me, this worked in Ubuntu 14.04 and for php5.6:

$ sudo apt-get install php5.6-mbstring

WCF Service Returning "Method Not Allowed"

Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:

[ServiceContract]
public interface IUploadService
{
    [WebGet()]
    [OperationContract]
    string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.

    [OperationContract]
    void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
 }

Is there a simple JavaScript slider?

There's a nice javascript slider, it's very easy to implement. You can download the zip package here: http://ruwix.com/javascript-volume-slider-control/


p.s. here the simplified version of the above script:

enter image description here

DEMO link

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

CSS table layout: why does table-row not accept a margin?

Fiddle

 .row-seperator{
   border-top: solid transparent 50px;
 }

<table>
   <tr><td>Section 1</td></tr>
   <tr><td>row1 1</td></tr>
   <tr><td>row1 2</td></tr>
   <tr>
      <td class="row-seperator">Section 2</td>
   </tr>
   <tr><td>row2 1</td></tr>
   <tr><td>row2 2</td></tr>
</table>


#Outline
Section 1
row1 1
row1 2


Section 2
row2 1
row2 2

this can be another solution

How to remove all .svn directories from my application directories

In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

How do you do a deep copy of an object in .NET?

I have a simpler idea. Use LINQ with a new selection.

public class Fruit
{
  public string Name {get; set;}
  public int SeedCount {get; set;}
}

void SomeMethod()
{
  List<Fruit> originalFruits = new List<Fruit>();
  originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
  originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});

  //Deep Copy
  List<Fruit> deepCopiedFruits = from f in originalFruits
              select new Fruit {Name=f.Name, SeedCount=f.SeedCount};
}

How to determine if string contains specific substring within the first X characters

Use IndexOf is easier and high performance.

int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;

Get 2 Digit Number For The Month

Function

FORMAT(date,'MM') 

will do the job with two digit.

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

How to check for empty array in vba macro

Public Function IsEmptyArray(InputArray As Variant) As Boolean

   On Error GoTo ErrHandler:
   IsEmptyArray = Not (UBound(InputArray) >= 0)
   Exit Function

   ErrHandler:
   IsEmptyArray = True

End Function

Insert json file into mongodb

mongoimport --jsonArray  -d DatabaseN -c collectionName /filePath/filename.json

What is the meaning of prepended double colon "::"?

its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;

int x;
void f2()
{
   int x = 1; // hide global x
   ::x = 2; // assign to global x
   x = 2; // assign to local x
   // ...
}

Entityframework Join using join method and lambdas

You can find a few examples here:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });


foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}

Or just google for 'linq join method syntax'.

Completely Remove MySQL Ubuntu 14.04 LTS

This is what saved me. Apparently the depackager tries to put things in the wrong tmp folder.

https://askubuntu.com/a/248860

How to get the employees with their managers

(SELECT ename FROM EMP WHERE empno = mgr)

There are no records in EMP that meet this criteria.

You need to self-join to get this relation.

SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;

EDIT:

The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:

> select * from emp;

 empno | ename |    job    | deptno | mgr  
-------+-------+-----------+--------+------
  7839 | king  | president |     10 |     
  7698 | blake | manager   |     30 | 7839
(2 rows)

> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;

 employee | empno | manager | empno 
----------+-------+---------+-------
 king     |  7839 |         |      
 blake    |  7698 | king    |  7839
(2 rows)

The difference is that an outer join returns all the rows. An inner join will produce the following:

> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;

 ename | empno | manager | mgr  
-------+-------+---------+------
 blake |  7698 | king    | 7839
(1 row)

jquery how to empty input field

To reset text, number, search, textarea inputs:

$('#shares').val('');

To reset select:

$('#select-box').prop('selectedIndex',0);

To reset radio input:

$('#radio-input').attr('checked',false);

To reset file input:

$("#file-input").val(null);

Fastest way to determine if record exists

Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's

SELECT distinct 1 products.id FROM products WHERE products.id = ?;

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

Arithmetic operation resulted in an overflow. (Adding integers)

2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.

How Do I Take a Screen Shot of a UIView?

CGImageRef UIGetScreenImage();

Apple now allows us to use it in a public application, even though it's a private API

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array

The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.

Good luck!

Change all files and folders permissions of a directory to 644/755

Easiest for me to remember is two operations:

chmod -R 644 dirName
chmod -R +X dirName

The +X only affects directories.

How to execute the start script with Nodemon

I have a TypeScript file called "server.ts", The following npm scripts configures Nodemon and npm to start my app and monitor for any changes on TypeScript files:

"start": "nodemon -e ts  --exec \"npm run myapp\"",
"myapp": "tsc -p . && node server.js",

I already have Nodemon on dependencies. When I run npm start, it will ask Nodemon to monitor its files using the -e switch and then it calls the myapp npm script which is a simple combination of transpiling the typescript files and then starting the resulting server.js. When I change the TypeScript file, because of -e switch the same cycle happens and new .js files will be generated and executed.

How to check radio button is checked using JQuery?

Radio buttons are,

<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">

to check on click,

$('.radioButtons').click(function(){
    if($("#radio_1")[0].checked){
       //logic here
    }
});

SFTP in Python? (platform independent)

fsspec is a great option for this, it offers a filesystem like implementation of sftp.

from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)

# list a directory
fs.ls("/")

# open a file
with fs.open(file_name) as file:
    content = file.read()

Also worth noting that fsspec uses paramiko in the implementation.

Aligning textviews on the left and right edges in Android layout

It can be done with LinearLayout (less overhead and more control than the Relative Layout option). Give the second view the remaining space so gravity can work. Tested back to API 16.

Proof

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Aligned left" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout> 

If you want to limit the size of the first text view, do this:

Adjust weights as required. Relative layout won't allow you to set a percentage weight like this, only a fixed dp of one of the views

Proof 2

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Aligned left but too long and would squash the other view" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout>

Run on server option not appearing in Eclipse

Right click on the project, go to "Run as", select "Run configurations" and create a run configuration.

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

How do I resize a Google Map with JavaScript after it has loaded?

The popular answer google.maps.event.trigger(map, "resize"); didn't work for me alone.

Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.

$(document).ready(function() {
    google.maps.event.addListener(map, "idle", function(){
        google.maps.event.trigger(map, 'resize'); 
    });
}); 

This was my answer that worked for me.

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

How can I enable CORS on Django REST Framework

Below are the working steps without the need for any external modules:

Step 1: Create a module in your app.

E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.

Lets call this as custom_cors_middleware.py

Paste the below Class definition:

class CustomCorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"

        # Code to be executed for each request/response after
        # the view is called.

        return response

Step 2: Register a middleware

In your projects settings.py file, add this line

'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

E.g:

  MIDDLEWARE = [
        'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
         ...
        'django.middleware.common.CommonMiddleware',

    ]

Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.

You can now verify it will add the required response headers to all the views in the project!

Transaction isolation levels relation with locks on table

The locks are always taken at DB level:-

Oracle official Document:- To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)

How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.

One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values that represent the transaction isolation levels you can use in JDBC.

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

x86 Assembly on a Mac

Forget about finding a IDE to write/run/compile assembler on Mac. But, remember mac is UNIX. See http://asm.sourceforge.net/articles/linasm.html. A decent guide (though short) to running assembler via GCC on Linux. You can mimic this. Macs use Intel chips so you want to look at Intel syntax.

How to restart ADB manually from Android Studio

  1. Open a Task Manager by pressing CTRL+ALT+DELETE, or right click at the bottom of the start menu and select Start Task Manager. see how to launch the task manager here

  2. Click on Processes or depending on OS, Details. Judging by your screenshot it's Processes.

  3. Look for adb.exe from that list, click on END PROCESS

  4. Click on the restart button in that window above. That should do it.

Basically by suddenly removing your device ADB got confused and won't respond while waiting for a device, and Android Studio doesn't want multiple instances of an ADB server running, so you'll have to kill the previous server manually and restart the whole process.

Defining static const integer members in class definition

As of C++11 you can use:

static constexpr int N = 10;

This theoretically still requires you to define the constant in a .cpp file, but as long as you don't take the address of N it is very unlikely that any compiler implementation will produce an error ;).

What is a non-capturing group in regular expressions?

?: is used when you want to group an expression, but you do not want to save it as a matched/captured portion of the string.

An example would be something to match an IP address:

/(?:\d{1,3}\.){3}\d{1,3}/

Note that I don't care about saving the first 3 octets, but the (?:...) grouping allows me to shorten the regex without incurring the overhead of capturing and storing a match.

How does one set up the Visual Studio Code compiler/debugger to GCC?

Caution

A friendly reminder: The following tutorial is for Linux user instead of Windows

Tutorial

If you want to debug your c++ code with GDB

You can read this ( Debugging your code ) article from Visual Studio Code official website.

Step 1: Compilation

You need to set up task.json for compilation of your cpp file

or simply type in the following command in the command window

g++ -g file.cpp -o file.exe

to generate a debuggable .exe file

Step 2: Set up the launch.json file

To enable debugging, you will need to generate a launch.json file

follow the launch.json example or google others

Step 3: Press (Ctrl+F5) to start compiling

this launch.json file will launch the configuration when you press the shortcut (Ctrl+F5)

Enjoy it!

ps. For those who want to set up tasks.json, you can read this from vscode official (-> TypeScript Hello World)

How to determine the first and last iteration in a foreach loop?

foreach ($arquivos as $key => $item) {
   reset($arquivos);
   // FIRST AHEAD
   if ($key === key($arquivos) || $key !== end(array_keys($arquivos)))
       $pdf->cat(null, null, $key);

   // LAST
   if ($key === end(array_keys($arquivos))) {
       $pdf->cat(null, null, $key)
           ->execute();
   }
}

Java Hashmap: How to get key from value?

You could insert both the key,value pair and its inverse into your map structure

map.put("theKey", "theValue");
map.put("theValue", "theKey");

Using map.get("theValue") will then return "theKey".

It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:

  • Contains only 1 to 1 pairs
  • Set of values is disjoint from the set of keys (1->2, 2->3 breaks it)

Autoplay an audio with HTML5 embed tag while the player is invisible

<div id="music">
<audio autoplay>
  <source src="kooche.mp3" type="audio/mpeg">
  <p>If you can read this, your browser does not support the audio element.</p>
</audio>
</div>

And the css:

#music {
  display:none;
}

Like suggested above, you probably should have the controls available in some form. Maybe use a toggle link/checkbox that slides the controls in via jquery.

Source: HTML5 Audio Autoplay

Bootstrap carousel multiple frames at once

_x000D_
_x000D_
    $('#carousel-example-generic').on('slid.bs.carousel', function () {_x000D_
        $(".item.active:nth-child(" + ($(".carousel-inner .item").length -1) + ") + .item").insertBefore($(".item:first-child"));_x000D_
        $(".item.active:last-child").insertBefore($(".item:first-child"));_x000D_
    });    
_x000D_
        .item.active,_x000D_
        .item.active + .item,_x000D_
        .item.active + .item  + .item {_x000D_
           width: 33.3%;_x000D_
           display: block;_x000D_
           float:left;_x000D_
        }          
_x000D_
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="max-width:800px;">_x000D_
  <!-- Indicators -->_x000D_
  <ol class="carousel-indicators">_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>_x000D_
  </ol>_x000D_
_x000D_
  <!-- Wrapper for slides -->_x000D_
  <div class="carousel-inner" role="listbox">_x000D_
    <div class="item active">_x000D_
        <img data-src="holder.js/300x200?text=1">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=2">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=3">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=4">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=5">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=6">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=7">_x000D_
    </div>    _x000D_
  </div>_x000D_
_x000D_
  <!-- Controls -->_x000D_
  <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">_x000D_
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>_x000D_
    <span class="sr-only">Previous</span>_x000D_
  </a>_x000D_
  <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">_x000D_
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>_x000D_
    <span class="sr-only">Next</span>_x000D_
  </a>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.1/holder.min.js"></script>_x000D_
    
_x000D_
_x000D_
_x000D_

Auto increment in phpmyadmin

In phpMyAdmin, navigate to the table in question and click the "Operations" tab. On the left under Table Options you will be allowed to set the current AUTO_INCREMENT value.

Regular expression for extracting tag attributes

Token Mantra response: you should not tweak/modify/harvest/or otherwise produce html/xml using regular expression.

there are too may corner case conditionals such as \' and \" which must be accounted for. You are much better off using a proper DOM Parser, XML Parser, or one of the many other dozens of tried and tested tools for this job instead of inventing your own.

I don't really care which one you use, as long as its recognized, tested, and you use one.

my $foo  = Someclass->parse( $xmlstring ); 
my @links = $foo->getChildrenByTagName("a"); 
my @srcs = map { $_->getAttribute("src") } @links; 
# @srcs now contains an array of src attributes extracted from the page. 

Stop setInterval

You need to set the return value of setInterval to a variable within the scope of the click handler, then use clearInterval() like this:

var interval = null;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            clearInterval(interval); // stop the interval
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
        }
    });
}

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

What causes java.lang.IncompatibleClassChangeError?

This means that you have made some incompatible binary changes to the library without recompiling the client code. Java Language Specification §13 details all such changes, most prominently, changing non-static non-private fields/methods to be static or vice versa.

Recompile the client code against the new library, and you should be good to go.

UPDATE: If you publish a public library, you should avoid making incompatible binary changes as much as possible to preserve what's known as "binary backward compatibility". Updating dependency jars alone ideally shouldn't break the application or the build. If you do have to break binary backward compatibility, it's recommended to increase the major version number (e.g. from 1.x.y to 2.0.0) before releasing the change.

Git push rejected "non-fast-forward"

  1. Undo the local commit. This will just undo the commit and preserves the changes in working copy
git reset --soft HEAD~1
  1. Pull the latest changes
git pull
  1. Now you can commit your changes on top of latest code

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

For resovle this issue:

  1. Go to Xcode/Preferences/Accounts
  2. Click on your apple id account;
  3. Click - "View Details" (is open a new window with "signing identities" and "provisioning profiles";
  4. Delete all certificates from "Provisioning profiles", empty trash;
  5. Delete your Apple-ID account;
  6. Log in again with your apple id and build app!

Good luck!

Error in launching AVD with AMD processor

As many other pointed out, Intel HAXM only supports Intel CPUs. Since Windows 1804 you can use Microsoft's Hyper-V instead of HAXM for the emulator. This also helps people who want to use Hyper-V for virtual machines as you need to disable hyper-v to run haxm.

Short version:

  • install Windows Hypervisor Platform feature
  • Update to Android Emulator 27.2.7 or above
  • put WindowsHypervisorPlatform = on into C:\Users\your-username\.android\advancedFeatures.ini or start emulator or command line with -feature WindowsHypervisorPlatform
  • enable IOMMU in your BIOS settings

Long version with more details:

https://blogs.msdn.microsoft.com/visualstudio/2018/05/08/hyper-v-android-emulator-support/

Requirements docs:

https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/system-requirements-for-hyper-v-on-windows

Standard Android menu icons, for example refresh

After seeing this post I found a useful link:

http://developer.android.com/design/downloads/index.html

You can download a lot of sources editable with Fireworks, Illustrator, Photoshop, etc...
And there's also fonts and icon packs.

Here is a stencil example.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Using Django time/date widgets in custom form

As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible.

EXEC sp_executesql with multiple parameters

If one need to use the sp_executesql with OUTPUT variables:

EXEC sp_executesql @sql
                  ,N'@p0 INT'
                  ,N'@p1 INT OUTPUT'
                  ,N'@p2 VARCHAR(12) OUTPUT' 
                  ,@p0
                  ,@p1 OUTPUT
                  ,@p2 OUTPUT;

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

How to style the UL list to a single line

Try experimenting with something like this also:

HTML

 <ul class="inlineList">
   <li>She</li>
   <li>Needs</li>
   <li>More Padding, Captain!</li>
 </ul>

CSS

 .inlineList {
   display: flex;
   flex-direction: row;
   /* Below sets up your display method: flex-start|flex-end|space-between|space-around */
   justify-content: flex-start; 
   /* Below removes bullets and cleans white-space */
   list-style: none;
   padding: 0;
   /* Bonus: forces no word-wrap */
   white-space: nowrap;
 }
 /* Here, I got you started.
 li {
   padding-top: 50px;
   padding-bottom: 50px;
   padding-left: 50px;
   padding-right: 50px;
 }
 */

I made a codepen to illustrate: http://codepen.io/agm1984/pen/mOxaEM

CodeIgniter: Load controller within controller

In this cases you can try some old school php.

// insert at the beggining of home.php controller require_once(dirname(__FILE__)."/product.php"); // the controller route.

Then, you'll have something like:

Class Home extends CI_Controller
{
 public function __construct()
 {
  parent::__construct();
  $this->product = new Product();
  ...
 }

 ...
 // usage example
 public function addProduct($data)
 {
  $this->product->add($data);
 }
}

And then just use the controller's methods as you like.

React component initialize state from props

set the state data inside constructor like this

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

it will not going to work if u set in side componentDidMount() method through props.

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

Send text to specific contact programmatically (whatsapp)

Check out my answer : https://stackoverflow.com/a/40285262/5879376

 Intent sendIntent = new Intent("android.intent.action.MAIN");
 sendIntent.setComponent(new  ComponentName("com.whatsapp","com.whatsapp.Conversation"));
 sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix

 startActivity(sendIntent);

Searching for Text within Oracle Stored Procedures

I allways use UPPER(text) like UPPER('%blah%')

Using intents to pass data between activities

Pass the data from Activity-1 to AndroidTabRes.. as below:

At sending activity...

Intent intent = new Intent(current.this, AndroidTabRestaurantDescSearchListView.class);
intent.putExtra("keyName","value");
startActivity(intent);

At AndroidTabRes.. activity...

  String data = getIntent().getExtras().getString("keyName");

Thus you can have data at receiving activity from sending activity...

And in your AndroidTabRestaurantDescSearchListView class, do this:

String value= getIntent().getStringExtra("keyName");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);

Then in your RatingDescriptionSearchActivity class, do this:

 String data= getIntent().getStringExtra("keyName");

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

No, you should run mysql -u root -p in bash, not at the MySQL command-line. If you are in mysql, you can exit by typing exit.

CSS/Javascript to force html table row on a single line

Use the CSS property white-space: nowrap and overflow: hidden on your td.

Update

Just saw your comment, not sure what I was thinking, I've done this so many times I forgot how I do it. This is approach that works well in most browsers for me... rather than trying to constrain the td, I use a div inside the td that will handle the overflow instance. This has a nice side effect of being able to add your padding, margins, background colors, etc. to your div rather than trying to style the td.

<html>
<head>
<style>
.hideextra { white-space: nowrap; overflow: hidden; text-overflow:ellipsis; }
</style>
</head>
<body>
<table style="width: 300px">
<tr>
    <td>Column 1</td><td>Column 2</td>
</tr>
<tr>
   <td>
    <div class="hideextra" style="width:200px">
        this is the text in column one which wraps</div></td>
   <td>
    <div class="hideextra" style="width:100px">
        this is the column two test</div></td>
</tr>
</table>
</body>
</html>

As a bonus, IE will place an ellipsis in the case of an overflow using the browser-specific text-overflow:ellipsis style. There is a way to do the same in FireFox automatically too, but I have not tested it myself.

Update 2

I started using this truncation code by Justin Maxwell for several months now which works properly in FireFox too.

How can I use pointers in Java?

All objects in Java are references and you can use them like pointers.

abstract class Animal
{...
}

class Lion extends Animal
{...
}

class Tiger extends Animal
{   
public Tiger() {...}
public void growl(){...}
}

Tiger first = null;
Tiger second = new Tiger();
Tiger third;

Dereferencing a null:

first.growl();  // ERROR, first is null.    
third.growl(); // ERROR, third has not been initialized.

Aliasing Problem:

third = new Tiger();
first = third;

Losing Cells:

second = third; // Possible ERROR. The old value of second is lost.    

You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.

first = second;
second = third; //OK

Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.

The Java system will throw an exception (OutOfMemoryError) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.

Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.

Novices often make the following error.

Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed. 

What you probably meant to say was:

Tiger tony = null;
tony = third; // OK.

Improper Casting:

Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler. 

Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.

Pointers in C:

void main() {   
    int*    x;  // Allocate the pointers x and y
    int*    y;  // (but not the pointees)

    x = malloc(sizeof(int));    // Allocate an int pointee,
                                // and set x to point to it

    *x = 42;    // Dereference x to store 42 in its pointee

    *y = 13;    // CRASH -- y does not have a pointee yet

    y = x;      // Pointer assignment sets y to point to x's pointee

    *y = 13;    // Dereference y to store 13 in its (shared) pointee
}

Pointers in Java:

class IntObj {
    public int value;
}

public class Binky() {
    public static void main(String[] args) {
        IntObj  x;  // Allocate the pointers x and y
        IntObj  y;  // (but not the IntObj pointees)

        x = new IntObj();   // Allocate an IntObj pointee
                            // and set x to point to it

        x.value = 42;   // Dereference x to store 42 in its pointee

        y.value = 13;   // CRASH -- y does not have a pointee yet

        y = x;  // Pointer assignment sets y to point to x's pointee

        y.value = 13;   // Deference y to store 13 in its (shared) pointee
    }
} 

UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.

Node Version Manager install - nvm command not found

In macOS, i had to source it using source ~/.nvm/nvm.sh command to fix this problem.

After that, add these lines

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

onto ~/.bash_profile so that nvm will be sourced automatically upon login.

How to send and retrieve parameters using $state.go toParams and $stateParams?

I was trying to Navigate from Page 1 to 2, and I had to pass some data as well.

In my router.js, I added params name and age :

.state('page2', {
          url: '/vehicle/:source',
          params: {name: null, age: null},
.................

In Page1, onClick of next button :

$state.go("page2", {name: 'Ron', age: '20'});

In Page2, I could access those params :

$stateParams.name
$stateParams.age

Emulator in Android Studio doesn't start

I'm using Ubuntu 19.10, I too had the same issue what I just did is deleting all virtual devices and create a new one.

Scroll to bottom of div with Vue.js

2021 easy solution that won't hurt your brain... use el.scrollIntoView()

Here is a fiddle.

This solution will not hurt your brain having to think about scrollTop or scrollHeight, has smooth scrolling built in, and even works in IE.

scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'}) to get smooth scrolling.

methods: {
  scrollToElement() {
    const el = this.$el.getElementsByClassName('scroll-to-me')[0];

    if (el) {
      // Use el.scrollIntoView() to instantly scroll to the element
      el.scrollIntoView({behavior: 'smooth'});
    }
  }
}

Then if you wanted to scroll to this element on page load you could call this method like this:

mounted() {
  this.scrollToElement();
}

Else if you wanted to scroll to it on a button click or some other action you could call it the same way:

<button @click="scrollToElement">scroll to me</button>

The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.

Pip - Fatal error in launcher: Unable to create process using '"'

Checked the evironment path, I have two paths navigated to two pip.exe and this caused this error. After deleting the redundant one and restart the PC, this issue has been fixed. The same issue for the jupyter command fixed as well.

How to add 10 minutes to my (String) time?

Use Calendar.add(int field,int amount) method.

AngularJS UI Router - change url without reloading state

i did this but long ago in version: v0.2.10 of UI-router like something like this::

$stateProvider
  .state(
    'home', {
      url: '/home',
      views: {
        '': {
          templateUrl: Url.resolveTemplateUrl('shared/partial/main.html'),
          controller: 'mainCtrl'
        },
      }
    })
  .state('home.login', {
    url: '/login',
    templateUrl: Url.resolveTemplateUrl('authentication/partial/login.html'),
    controller: 'authenticationCtrl'
  })
  .state('home.logout', {
    url: '/logout/:state',
    controller: 'authenticationCtrl'
  })
  .state('home.reservationChart', {
    url: '/reservations/?vw',
    views: {
      '': {
        templateUrl: Url.resolveTemplateUrl('reservationChart/partial/reservationChartContainer.html'),
        controller: 'reservationChartCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/viewVoucherContainer.html'),
        controller: 'viewVoucherCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/voucherContainer.html'),
        controller: 'voucherCtrl',
        reloadOnSearch: false
      }
    },
    reloadOnSearch: false
  })

How do I make a Docker container start automatically on system boot?

To start a container and set it to restart automatically on system reboot use

docker run -d --restart unless-stopped ecstatic_ritchie

Where ecstatic_ritchie is an example name specifying the container in interest. Use docker ps -a to list all container names.

To make particular running containers start automatically on system reboot

docker update --restart unless-stopped ecstatic_ritchie

To make all running containers start automatically on system reboot

docker update --restart unless-stopped $(docker ps -q)

See more on Docker homepage

How to Merge Two Eloquent Collections?

Merge two different eloquent collections into one and some objects happen to have the same id, one will overwrite the other. Use push() method instead or rethink your approach to the problem to avoid that. Refer to web

Delete a row from a table by id

How about:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    row.parentNode.removeChild(row);
}

And, if that fails, this should really work:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    var table = row.parentNode;
    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if ( !table )
        return;
    table.deleteRow(row.rowIndex);
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components html.

I followed some of the solutions proposed on this page but any of them worked for me, at least not completely.

What did actually solve my error was to write the below code snippet inside the father html tag of the elements .

I was binding to the variable.

Code:

    *ngIf="variable-name"

The error was caused, apparently by the project trying to render the page, apparently at the moment of evaluating the variable, the project just could no find its value. With the above code snippet you make sure that before rendering the page you ask if the variable has being initialized.

This is my component.ts code:

import { Component, OnInit } from '@angular/core';
import { InvitationService } from 'src/app/service/invitation.service';
import { BusinessService } from 'src/app/service/business.service';
import { Invitation } from 'src/app/_models/invitation';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
  selector: 'app-invitation-details',
  templateUrl: './invitation-details.component.html',
  styleUrls: ['./invitation-details.component.scss']
})
export class InvitationDetailsComponent implements OnInit {
  invitationsList: any;
  currentInvitation: any;
  business: any;
  invitationId: number;
  invitation: Invitation;

  constructor(private InvitationService: InvitationService, private BusinessService: 
BusinessService) { 
this.invitationId = 1; //prueba temporal con invitacion 1
this.getInvitations();
this.getInvitationById(this.invitationId);
  }

   ngOnInit() {

  }

  getInvitations() {
    this.InvitationService.getAllInvitation().subscribe(result => {
      this.invitationsList = result;
      console.log(result);
    }, error => {
      console.log(JSON.stringify(error));
    });
  }

  getInvitationById(invitationId:number){
    this.InvitationService.getInvitationById(invitationId).subscribe(result => {
      this.currentInvitation = result;
      console.log(result);
      //this.business=this.currentInvitation['business'];
       //console.log(this.currentInvitation['business']); 
     }, error => {
     console.log(JSON.stringify(error));
    });
  }
      ...

Here is my html markup:

<div class="container-fluid mt--7">
  <div class="row">
    <div class="container col-xl-10 col-lg-8">
      <div class="card card-stats ">
        <div class="card-body container-fluid form-check-inline" 
         *ngIf="currentInvitation">
          <div class="col-4">
             ...

I hope this can be helpful.

How to get an array of unique values from an array containing duplicates in JavaScript?

You can find all kinds of array unique implementations here:

http://jsperf.com/distinct-hash-vs-comparison/12

http://jsperf.com/array-unique-functional

I prefer functional styles such as:

var arr = ['lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg'];

var newarr = arr.reduce(function (prev, cur) {
    //console.log(prev, cur);
    if (prev.indexOf(cur) < 0) prev.push(cur);
    return prev;
}, []);

var secarr = arr.filter(function(element, index, array){
    //console.log(element, array.indexOf(element), index);
    return array.indexOf(element) >= index;
});

//reverses the order
var thirdarr = arr.filter(function (e, i, arr) {
    //console.log(e, arr.lastIndexOf(e), i);
    return arr.lastIndexOf(e) === i;
});

console.log(newarr);
console.log(secarr);
console.log(thirdarr);

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

Credit card expiration dates - Inclusive or exclusive?

According to Visa's "Card Acceptance and Chargeback Management Guidelines for Visa Merchants"; "Good Thru" (or "Valid Thru") Date is the expiration date of the card:

A card is valid through the last day of the month shown, (e .g ., if the Good Thru date is 03/12,the card is valid through March 31, 2012 and expires on April 1, 2012 .)

It is located below the embossed account number. If the current transaction date is after the "Good Thru" date, the card has expired.

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

Works after removing the scope reference and the function arguments:

"use strict";

describe("Request Notification Channel", function() {
    var requestNotificationChannel, rootScope;

    beforeEach(function() {
        module("messageAppModule");

        inject(function($injector, _requestNotificationChannel_) {
            rootScope = $injector.get("$rootScope");
            requestNotificationChannel = _requestNotificationChannel_;
        })
        spyOn(rootScope, "$broadcast");
    });


    it("should broadcast delete message notification with provided params", function() {
        requestNotificationChannel.deleteMessage(1, 4);
        expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4} );
    });
});

How to throw an exception in C?

On Win with MSVC there's __try ... __except ... but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Go to Xcode's breakpoints tab. Use the button at the bottom to add an exception breakpoint. Now you'll see what code is invoking setValue:forKey: and the associated stack. With luck that'll point you straight at the problem's source.

Odd that your class is LoginScreen, yet the error is saying someone is using "LoginScreen" as a key. Check that LoginScreen.m is part of your target.

enter image description here


Footnote: with Swift a common problem arises if you change the name of a class (so, you rename it everywhere in your code). Storyboard struggles with this, and you usually have to re-drag any connections involving that class. And in particular, re-enter the name of the class anywhere used in IdentityInspector tab on the right. (In the picture example I deliberately misspelled the class name. But the same thing often happens when you rename a class; even though it's seemingly correct in IdentityInspector, you need to enter the name again; it will correctly autocomplete and you're good to go.)

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

how to remove the first two columns in a file using shell (awk, sed, whatever)

Here's one way to do it with Awk that's relatively easy to understand:

awk '{print substr($0, index($0, $3))}'

This is a simple awk command with no pattern, so action inside {} is run for every input line.

The action is to simply prints the substring starting with the position of the 3rd field.

  • $0: the whole input line
  • $3: 3rd field
  • index(in, find): returns the position of find in string in
  • substr(string, start): return a substring starting at index start

If you want to use a different delimiter, such as comma, you can specify it with the -F option:

awk -F"," '{print substr($0, index($0, $3))}'

You can also operate this on a subset of the input lines by specifying a pattern before the action in {}. Only lines matching the pattern will have the action run.

awk 'pattern{print substr($0, index($0, $3))}'

Where pattern can be something such as:

  • /abcdef/: use regular expression, operates on $0 by default.
  • $1 ~ /abcdef/: operate on a specific field.
  • $1 == blabla: use string comparison
  • NR > 1: use record/line number
  • NF > 0: use field/column number

How to center the elements in ConstraintLayout

Update:

Chain

You can now use the chain feature in packed mode as describe in Eugene's answer.


Guideline

You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/login_auth"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

</android.support.constraint.ConstraintLayout>

Layout Editor

Run batch file as a Windows service

NSSM is totally free and hyper-easy, running command prompt / terminal as administrator:

nssm install "YourCoolServiceNameLabel"

then a dialog will appear so you can choose where is the file you want to run.

to uninstall

nssm remove "YourCoolServiceNameLabel"

Download old version of package with NuGet

Another option is to change the version number in the packages.config file. This will cause NuGet to download the dlls for that version the next time you build.

RecyclerView: Inconsistency detected. Invalid item position

Sorry For late but perfect solution: when you try to remove a specific item just call notifydatasetchange() and get these item in bindviewholder and remove that item and add again to the last of list and then chek list position if this is last index then remove item. basically the problem is come when you try to remove item from the center. if you remove item from last index then there have no more recycling and also your adpter count are mantine (this is critical point crash come here) and the crash is solved the code snippet below .

 holder.itemLayout.setVisibility( View.GONE );//to hide temprory it show like you have removed item

        Model current = list.get( position );
        list.remove( current );
        list.add( list.size(), current );//add agine to last index
        if(position==list.size()-1){// remove from last index
             list.remove( position );
        }

Is there a way to provide named parameters in a function call in JavaScript?

Calling function f with named parameters passed as the object

o = {height: 1, width: 5, ...}

is basically calling its composition f(...g(o)) where I am using the spread syntax and g is a "binding" map connecting the object values with their parameter positions.

The binding map is precisely the missing ingredient, that can be represented by the array of its keys:

// map 'height' to the first and 'width' to the second param
binding = ['height', 'width']

// take binding and arg object and return aray of args
withNamed = (bnd, o) => bnd.map(param => o[param])

// call f with named args via binding
f(...withNamed(binding, {hight: 1, width: 5}))

Note the three decoupled ingredients: the function, the object with named arguments and the binding. This decoupling allows for a lot of flexibility to use this construct, where the binding can be arbitrarily customized in function's definition and arbitrarily extended at the function call time.

For instance, you may want to abbreviate height and width as h and w inside your function's definition, to make it shorter and cleaner, while you still want to call it with full names for clarity:

// use short params
f = (h, w) => ...

// modify f to be called with named args
ff = o => f(...withNamed(['height', 'width'], o))

// now call with real more descriptive names
ff({height: 1, width: 5})

This flexibility is also more useful for functional programming, where functions can be arbitrarily transformed with their original param names getting lost.

Servlet for serving static content

I found great tutorial on the web about some workaround. It is simple and efficient, I used it in several projects with REST urls styles approach:

http://www.kuligowski.pl/java/rest-style-urls-and-url-mapping-for-static-content-apache-tomcat,5

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

Spark - load CSV file as DataFrame?

To read from relative path on the system use System.getProperty method to get current directory and further uses to load the file using relative path.

scala> val path = System.getProperty("user.dir").concat("/../2015-summary.csv")
scala> val csvDf = spark.read.option("inferSchema","true").option("header", "true").csv(path)
scala> csvDf.take(3)

spark:2.4.4 scala:2.11.12

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

Center-align a HTML table

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work. Cheers

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

How do I convert uint to int in C#?

Assuming that the value contained in the uint can be represented in an int, then it is as simple as:

int val = (int) uval;

What's the most efficient way to test two integer ranges for overlap?

If you were dealing with, given two ranges [x1:x2] and [y1:y2], natural / anti-natural order ranges at the same time where:

  • natural order: x1 <= x2 && y1 <= y2 or
  • anti-natural order: x1 >= x2 && y1 >= y2

then you may want to use this to check:

they are overlapped <=> (y2 - x1) * (x2 - y1) >= 0

where only four operations are involved:

  • two subtractions
  • one multiplication
  • one comparison

How to use Redirect in the new react-router-dom of Reactjs

You have to use setState to set a property that will render the <Redirect> inside your render() method.

E.g.

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow


That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.

But I guess you have your reasons to do it this way.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

Change width of select tag in Twitter Bootstrap

Tested alone, <select class=input-xxlarge> sets the content width of the element to 530px. (The total width of the element is slightly smaller than that of <input class=input-xxlarge> due to different padding. If this a a problem, set the paddings in your own style sheet as desired.)

So if it does not work, the effect is prevented by some setting in your own style sheet or maybe in the use other settings for the element.

REST API - Bulk Create or Update in single request

You probably will need to use POST or PATCH, because it is unlikely that a single request that updates and creates multiple resources will be idempotent.

Doing PATCH /docs is definitely a valid option. You might find using the standard patch formats tricky for your particular scenario. Not sure about this.

You could use 200. You could also use 207 - Multi Status

This can be done in a RESTful way. The key, in my opinion, is to have some resource that is designed to accept a set of documents to update/create.

If you use the PATCH method I would think your operation should be atomic. i.e. I wouldn't use the 207 status code and then report successes and failures in the response body. If you use the POST operation then the 207 approach is viable. You will have to design your own response body for communicating which operations succeeded and which failed. I'm not aware of a standardized one.

Facebook API: Get fans of / people who like a page

According to the Facebook documentation it's not possible to get all the fans of a page:

Although you can't get a list of all the fans of a Facebook Page, you can find out whether a specific person has liked a Page.

Get current batchfile directory

System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.

You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd).

You can refer to other files in the same folder as the batch script by using this syntax:

CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

More on batch parameters.

Multiple IF AND statements excel

With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs

=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))

although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))

To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula

=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

Input type number "only numeric value" validation

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

MySQL error - #1062 - Duplicate entry ' ' for key 2

As it was said you have a unique index.

However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

That means that all these entries contain value NULL, not empty string ''. Mysql lets you have multiple NULL values in unique fields.

How do you add a scroll bar to a div?

<div class="scrollingDiv">foo</div> 

div.scrollingDiv
{
   overflow:scroll;
}

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

How to set width and height dynamically using jQuery

As @Misha Moroshko has already posted himself, this works:

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

There's some advantage to this technique over @Nick Craver's accepted answer - you can also specifiy different units:

$("#mainTable").css("width", "100%");

So @Nick Craver's method might actually be the wrong choice for some users. From the jquery API (http://api.jquery.com/width/):

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

How can I find out a file's MIME type (Content-Type)?

one of the other tool (besides file) you can use is xdg-mime

eg xdg-mime query filetype <file>

if you have yum,

yum install xdg-utils.noarch

An example comparison of xdg-mime and file on a Subrip(subtitles) file

$ xdg-mime query filetype subtitles.srt
application/x-subrip

$ file --mime-type subtitles.srt
subtitles.srt: text/plain

in the above file only show it as plain text.

How to implement a Boolean search with multiple columns in pandas

the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :

df = df.query("columnNameA <= @x or columnNameB == @y")

with x and y are declared variables which you can refer to with @

Remove last characters from a string in C#. An elegant way?

You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.

string var = var.Substring(0, var.LastIndexOf(','));

How to get the value from the GET parameters?

See this

function getURLParameters(paramName)
{
    var sURL = window.document.URL.toString();
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        var arrParamNames = new Array(arrURLParams.length);
        var arrParamValues = new Array(arrURLParams.length);

        var i = 0;
        for (i = 0; i<arrURLParams.length; i++)
        {
            var sParam =  arrURLParams[i].split("=");
            arrParamNames[i] = sParam[0];
            if (sParam[1] != "")
                arrParamValues[i] = unescape(sParam[1]);
            else
                arrParamValues[i] = "No Value";
        }

        for (i=0; i<arrURLParams.length; i++)
        {
            if (arrParamNames[i] == paramName)
            {
                //alert("Parameter:" + arrParamValues[i]);
                return arrParamValues[i];
            }
        }
        return "No Parameters Found";
    }
}

Simplest/cleanest way to implement a singleton in JavaScript

Here is a simple example to explain the singleton pattern in JavaScript.

var Singleton = (function() {
    var instance;
    var init = function() {
        return {
            display:function() {
                alert("This is a singleton pattern demo");
            }
        };
    };
    return {
        getInstance:function(){
            if(!instance){
                alert("Singleton check");
                instance = init();
            }
            return instance;
        }
    };
})();

// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created

var inst = Singleton.getInstance();
inst.display();

// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object

var inst1 = Singleton.getInstance();
inst1.display();

Change color of Back button in navigation bar

In Swift3, To set the Back button to red.

self.navigationController?.navigationBar.tintColor = UIColor.red

Extract and delete all .gz in a directory- Linux

Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz

Then Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm

This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.

XMLHttpRequest cannot load an URL with jQuery

Found a possible workaround that I don't believe was mentioned.

Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Basically as long as you use forms/url-encoded/plain text content types you are fine.

$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: "http://localhost/endpoint",
    data: JSON.stringify({'DataToPost': 123}),
    success: function (data) {
        alert(JSON.stringify(data));
    }
});     

I use it with ASP.NET WebAPI2. So on the other end:

public static void RegisterWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}

This way Json formatter gets used when parsing plain text content type.

And don't forget in Web.config:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>    

Hope this helps.

Replace characters from a column of a data frame R

chartr is also convenient for these types of substitutions:

chartr("_", "-", data1$c)
#  [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"

Thus, you can just do:

data1$c <- chartr("_", "-", data1$c)

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

Custom HTTP headers : naming conventions

The format for HTTP headers is defined in the HTTP specification. I'm going to talk about HTTP 1.1, for which the specification is RFC 2616. In section 4.2, 'Message Headers', the general structure of a header is defined:

   message-header = field-name ":" [ field-value ]
   field-name     = token
   field-value    = *( field-content | LWS )
   field-content  = <the OCTETs making up the field-value
                    and consisting of either *TEXT or combinations
                    of token, separators, and quoted-string>

This definition rests on two main pillars, token and TEXT. Both are defined in section 2.2, 'Basic Rules'. Token is:

   token          = 1*<any CHAR except CTLs or separators>

In turn resting on CHAR, CTL and separators:

   CHAR           = <any US-ASCII character (octets 0 - 127)>

   CTL            = <any US-ASCII control character
                    (octets 0 - 31) and DEL (127)>

   separators     = "(" | ")" | "<" | ">" | "@"
                  | "," | ";" | ":" | "\" | <">
                  | "/" | "[" | "]" | "?" | "="
                  | "{" | "}" | SP | HT

TEXT is:

   TEXT           = <any OCTET except CTLs,
                    but including LWS>

Where LWS is linear white space, whose definition i won't reproduce, and OCTET is:

   OCTET          = <any 8-bit sequence of data>

There is a note accompanying the definition:

The TEXT rule is only used for descriptive field contents and values
that are not intended to be interpreted by the message parser. Words
of *TEXT MAY contain characters from character sets other than ISO-
8859-1 [22] only when encoded according to the rules of RFC 2047
[14].

So, two conclusions. Firstly, it's clear that the header name must be composed from a subset of ASCII characters - alphanumerics, some punctuation, not a lot else. Secondly, there is nothing in the definition of a header value that restricts it to ASCII or excludes 8-bit characters: it's explicitly composed of octets, with only control characters barred (note that CR and LF are considered controls). Furthermore, the comment on the TEXT production implies that the octets are to be interpreted as being in ISO-8859-1, and that there is an encoding mechanism (which is horrible, incidentally) for representing characters outside that encoding.

So, to respond to @BalusC in particular, it's quite clear that according to the specification, header values are in ISO-8859-1. I've sent high-8859-1 characters (specifically, some accented vowels as used in French) in a header out of Tomcat, and had them interpreted correctly by Firefox, so to some extent, this works in practice as well as in theory (although this was a Location header, which contains a URL, and these characters are not legal in URLs, so this was actually illegal, but under a different rule!).

That said, i wouldn't rely on ISO-8859-1 working across all servers, proxies, and clients, so i would stick to ASCII as a matter of defensive programming.

How to add button tint programmatically

The way I managed to get mine to work was by using CompoundButtonCompat.setButtonTintList(button, colour).

To my understanding this works regardless of android version.

NPM: npm-cli.js not found when running npm

Copy the directory named npm from your installed node path (In my case the npm directory was available in C:\Program Files\nodejs\node_modules).

Navigate to C:\Users\%USERNAME%\AppData\Roaming\npm\node_modules and paste the copied npm directory there.

This method worked for me when I had the same error. . .

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Adding attribute in jQuery

Add attribute as:

$('#Selector_id').attr('disabled',true);

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

Example use of "continue" statement in Python?

Here's a simple example:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

Output will be:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

It continues to the next iteration of the loop.

How to show Page Loading div until the page has finished loading?

I have another below simple solution for this which perfectly worked for me.

First of all, create a CSS with name Lockon class which is transparent overlay along with loading GIF as shown below

.LockOn {
    display: block;
    visibility: visible;
    position: absolute;
    z-index: 999;
    top: 0px;
    left: 0px;
    width: 105%;
    height: 105%;
    background-color:white;
    vertical-align:bottom;
    padding-top: 20%; 
    filter: alpha(opacity=75); 
    opacity: 0.75; 
    font-size:large;
    color:blue;
    font-style:italic;
    font-weight:400;
    background-image: url("../Common/loadingGIF.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}

Now we need to create our div with this class which cover entire page as an overlay whenever the page is getting loaded

<div id="coverScreen"  class="LockOn">
</div>

Now we need to hide this cover screen whenever the page is ready and so that we can restrict the user from clicking/firing any event until the page is ready

$(window).on('load', function () {
$("#coverScreen").hide();
});

Above solution will be fine whenever the page is loading.

Now the question is after the page is loaded, whenever we click a button or an event which will take a long time, we need to show this in the client click event as shown below

$("#ucNoteGrid_grdViewNotes_ctl01_btnPrint").click(function () {
$("#coverScreen").show();
});

That means when we click this print button (which will take a long time to give the report) it will show our cover screen with GIF which gives this result and once the page is ready above windows on load function will fire and which hide the cover screen once the screen is fully loaded.

How to make a floated div 100% height of its parent?

For #outer height to be based on its content, and have #inner base its height on that, make both elements absolutely positioned.

More details can be found in the spec for the css height property, but essentially, #inner must ignore #outer height if #outer's height is auto, unless #outer is positioned absolutely. Then #inner height will be 0, unless #inner itself is positioned absolutely.

<style>
    #outer {
        position:absolute; 
        height:auto; width:200px; 
        border: 1px solid red; 
    }
    #inner {
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
    }
</style>

<div id='outer'>
    <div id='inner'>
    </div>
    text
</div>

However... By positioning #inner absolutely, a float setting will be ignored, so you will need to choose a width for #inner explicitly, and add padding in #outer to fake the text wrapping I suspect you want. For example, below, the padding of #outer is the width of #inner +3. Conveniently (as the whole point was to get #inner height to 100%) there's no need to wrap text beneath #inner, so this will look just like #inner is floated.

<style>
    #outer2{
        padding-left: 23px;
        position:absolute; 
        height:auto; 
        width:200px; 
        border: 1px solid red; 
    }
    #inner2{
        left:0;
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
   }
</style>

<div id='outer2'>
    <div id='inner2'>
    </div>
    text
</div>

I deleted my previous answer, as it was based on too many wrong assumptions about your goal.

How to cut a string after a specific character in unix

This should do the trick:

$ echo "$var" | awk -F':' '{print $NF}'
/home/some/directory/file

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

How to place Text and an Image next to each other in HTML?

You can use vertical-align and floating.

In most cases you want to vertical-align: middle, the image.

Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align

vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;

For middle, the definition is: The element is placed in the middle of the parent element.

So you might want to apply that to all elements within the element.

"A referral was returned from the server" exception when accessing AD from C#

Probably the path you supplied was not correct. Check that.

I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.

How to check if command line tools is installed

Open your terminal and check to see if you have Xcode installed already with this:

xcode-select -p

in return, if you get this:

/Library/Developer/CommandLineTools

That means you have that Xcode is installed.

Another way you can check would you if you have "HomeBrew" installed you can use the following command to see if you have Xcode and the version:

brew config

And finally, if you don't have the Xcode follow this link to download the Xcode from the Appstore. Xcode from the App Store.

Good Luck.

Why does npm install say I have unmet dependencies?

npm install will install all the packages from npm-shrinkwrap.json, but might ignore packages in package.json, if they're not preset in the former.

If you're project has a npm-shrinkwrap.json, make sure you run npm shrinkwrap to regenerate it, each time you add add/remove/change package.json.

How to Convert Boolean to String

You use strval() or (string) to convert to string in PHP. However, that does not convert boolean into the actual spelling of "true" or "false" so you must do that by yourself. Here's an example function:

function strbool($value)
{
    return $value ? 'true' : 'false';
}
echo strbool(false); // "false"
echo strbool(true); // "true"

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

For me, the problem was passing in a larger than normally expected HTTP header. I resolved it by setting maxHttpHeaderSize="1048576" attribute on the Connector node in server.xml.

ImportError: No module named site on Windows

First uninstall python and again install the latest version during installation use custom install and mark all user checkbox and set the installation path C:\Python 3.9 and make PYTHON_HOME value C:\Python 3.9 in the Environmental variable it works for me

Pass path with spaces as parameter to bat file

If you have a path with spaces you must surround it with quotation marks (").

Not sure if that's exactly what you're asking though?

What is the correct way of reading from a TCP socket in C/C++?

For any non-trivial application (I.E. the application must receive and handle different kinds of messages with different lengths), the solution to your particular problem isn't necessarily just a programming solution - it's a convention, I.E. a protocol.

In order to determine how many bytes you should pass to your read call, you should establish a common prefix, or header, that your application receives. That way, when a socket first has reads available, you can make decisions about what to expect.

A binary example might look like this:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

enum MessageType {
    MESSAGE_FOO,
    MESSAGE_BAR,
};

struct MessageHeader {
    uint32_t type;
    uint32_t length;
};

/**
 * Attempts to continue reading a `socket` until `bytes` number
 * of bytes are read. Returns truthy on success, falsy on failure.
 *
 * Similar to @grieve's ReadXBytes.
 */
int readExpected(int socket, void *destination, size_t bytes)
{
    /*
    * Can't increment a void pointer, as incrementing
    * is done by the width of the pointed-to type -
    * and void doesn't have a width
    *
    * You can in GCC but it's not very portable
    */
    char *destinationBytes = destination;
    while (bytes) {
        ssize_t readBytes = read(socket, destinationBytes, bytes);
        if (readBytes < 1)
            return 0;
        destinationBytes += readBytes;
        bytes -= readBytes;
    }
    return 1;
}

int main(int argc, char **argv)
{
    int selectedFd;

    // use `select` or `poll` to wait on sockets
    // received a message on `selectedFd`, start reading

    char *fooMessage;
    struct {
        uint32_t a;
        uint32_t b;
    } barMessage;

    struct MessageHeader received;
    if (!readExpected (selectedFd, &received, sizeof(received))) {
        // handle error
    }
    // handle network/host byte order differences maybe
    received.type = ntohl(received.type);
    received.length = ntohl(received.length);

    switch (received.type) {
        case MESSAGE_FOO:
            // "foo" sends an ASCII string or something
            fooMessage = calloc(received.length + 1, 1);
            if (readExpected (selectedFd, fooMessage, received.length))
                puts(fooMessage);
            free(fooMessage);
            break;
        case MESSAGE_BAR:
            // "bar" sends a message of a fixed size
            if (readExpected (selectedFd, &barMessage, sizeof(barMessage))) {
                barMessage.a = ntohl(barMessage.a);
                barMessage.b = ntohl(barMessage.b);
                printf("a + b = %d\n", barMessage.a + barMessage.b);
            }
            break;
        default:
            puts("Malformed type received");
            // kick the client out probably
    }
}

You can likely already see one disadvantage of using a binary format - for each attribute greater than a char you read, you will have to ensure its byte order is correct using the ntohl or ntohs functions.

An alternative is to use byte-encoded messages, such as simple ASCII or UTF-8 strings, which avoid byte-order issues entirely but require extra effort to parse and validate.

There are two final considerations for network data in C.

The first is that some C types do not have fixed widths. For example, the humble int is defined as the word size of the processor, so 32 bit processors will produce 32 bit ints, while 64 bit processors will produces 64 bit ints. Good, portable code should have network data use fixed-width types, like those defined in stdint.h.

The second is struct padding. A struct with different-widthed members will add data in between some members to maintain memory alignment, making the struct faster to use in the program but sometimes producing confusing results.

#include <stdio.h>
#include <stdint.h>

int main()
{
    struct A {
        char a;
        uint32_t b;
    } A;

    printf("sizeof(A): %ld\n", sizeof(A));
}

In this example, its actual width won't be 1 char + 4 uint32_t = 5 bytes, it'll be 8:

mharrison@mharrison-KATANA:~$ gcc -o padding padding.c
mharrison@mharrison-KATANA:~$ ./padding 
sizeof(A): 8

This is because 3 bytes are added after char a to make sure uint32_t b is memory-aligned.

So if you write a struct A, then attempt to read a char and a uint32_t on the other side, you'll get char a, and a uint32_t where the first three bytes are garbage and the last byte is the first byte of the actual integer you wrote.

Either document your data format explicitly as C struct types or, better yet, document any padding bytes they might contain.

How to run a class from Jar which is not the Main-Class in its Manifest file

You can execute any class which has a public final static main method from a JAR file, even if the jar file has a Main-Class defined.

Execute Main-Class:

java -jar MyJar.jar  // will execute the Main-Class

Execute another class with a public static void main method:

java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod

Note: the first uses -jar, the second uses -cp.