Programs & Examples On #Premultiplied alpha

Colorspace where each color component is multiplied by alpha value. This makes alpha blending faster and prevents color distortion when blending semitransparent colors together.

Adding 'serial' to existing column in Postgres

You can also use START WITH to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,

SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How to add Button over image using CSS?

You need to give relative or absolute or fixed positioning to your container (#shop) and set its zIndex to say 100.

You also need to give say relative positioning to your elements with the class content and lower zIndex say 97.

Do the above-mentioned with your images too and set their zIndex to 91.

And then position your button higher by setting its position to absolute and zIndex to 95

See the DEMO

HTML

<div id="shop">

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

  </div>

CSS

#shop{
    background-image: url("images/shop_bg.png");
    background-repeat: repeat-x;    
    height:121px;
    width: 984px;
    margin-left: 20px;
    margin-top: 13px;
    position:relative;
    z-index:100
}

#shop .content{    
    width: 182px; /*328 co je 1/3 - 20margin left*/
    height: 121px;
    line-height: 20px;
    margin-top: 0px;
    margin-left: 9px;
    margin-right:0px;
    display:inline-block;
    position:relative;
    z-index:97

}

img{

    position:relative;
    z-index:91

}

.span{

    width:70px;
    height:40px;
    border:1px solid red;
    position:absolute;
    z-index:95;
    right:60px;
    bottom:-20px;

}

Please initialize the log4j system properly. While running web service

Those messages are something tricky, enough so that people created this to make it clearer: https://issues.apache.org/bugzilla/show_bug.cgi?id=25747

What's tricky about them is that the warnings are written if Log4j can't find its log4j.properties (or log4j.xml) file, but also if the file is fine and dandy but its content is not complete from a configuration point of view.

The following paragraph is taken from here: http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_9/docs/TROUBLESHOOT.html

Logging output is written to a target by using an appender. If no appenders are attached to a category nor to any of its ancestors, you will get the following message when trying to log:

log4j: No appenders could be found for category (some.category.name).
log4j: Please initialize the log4j system properly.

Log4j does not have a default logging target. It is the user's responsibility to ensure that all categories can inherit an appender. This can be easily achieved by attaching an appender to the root category.

You can find info on how to configure the root logger (log4j.rootLogger) in the log4j documentation, basically adding something as simple as this at the beginning of the file:

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

This should clear those WARN messages you get on startup (make sure you don't already have an appender named stdout; also be carefull of what level you give the root logger, debug will be very verbose and every library in your app will start writing stuff to the console).

As about the log4j.properties/log4j.xml, I suggest you place this file in /WEB-INF/classes as it is important to have it exposed for different tweaks (activating/deactivating logs, changing log levels etc). You can have it inside a JAR in the classpath also (as you specified in your comment), but it will be enclosed in the archive (hopefully in the right place inside the archive) and won't be as easy to handle as if it were in /WEB-INF/classes.

Compare two Lists for differences

This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.

http://msdn.microsoft.com/en-us/library/bb397894.aspx

Rewrite all requests to index.php with nginx

To pass get variables as well use $args:

location / {
    try_files $uri $uri/ /index.php?$args;
}

jQuery animated number counter from zero to value

Your thisdoesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $thisin my example):

$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });
});

Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil you can round up to 2 decimals for instance with value.toFixed(2):

step: function () {
  $this.text(this.Counter.toFixed(2));
}

Laravel Pagination links not including other GET parameters

Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2
So the last value page takes will be the page you see ! not the page you want to see

Solution : use Input::except(array('page'))

Trees in Twitter Bootstrap

If someone wants vertical version of the treeview from Harsh's answer, you can save some time:

http://jsfiddle.net/Fh47n/

.tree li {
    margin: 0px 0;

    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}

.tree li::before{
    content: '';
    position: absolute; 
    top: 0;
    width: 1px; 
    height: 100%;
    right: auto; 
    left: -20px;
    border-left: 1px solid #ccc;
    bottom: 50px;
}
.tree li::after{
    content: '';
    position: absolute; 
    top: 30px; 
    width: 25px; 
    height: 20px;
    right: auto; 
    left: -20px;
    border-top: 1px solid #ccc;
}
.tree li a{
    display: inline-block;
    border: 1px solid #ccc;
    padding: 5px 10px;
    text-decoration: none;
    color: #666;
    font-family: arial, verdana, tahoma;
    font-size: 11px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

/*Remove connectors before root*/
.tree > ul > li::before, .tree > ul > li::after{
    border: 0;
}
/*Remove connectors after last child*/
.tree li:last-child::before{ 
      height: 30px;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
    background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
    border-color:  #94a0b4;
}

Declare an array in TypeScript

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

Is there any "font smoothing" in Google Chrome?

Ok you can use this simply

-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;

Make sure your text color and upper text-stroke-width must me same and that's it.

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

Delete directories recursively in Java

Below code recursively delete all contents in a given folder.

boolean deleteDirectory(File directoryToBeDeleted) {
    File[] allContents = directoryToBeDeleted.listFiles();
    if (allContents != null) {
        for (File file : allContents) {
            deleteDirectory(file);
        }
    }
    return directoryToBeDeleted.delete();
}

Map vs Object in JavaScript

An object behaves like a dictionary because Javascript is dynamically typed, allowing you to add or remove properties at any time.

But Map() is much better because it:

  • Provides get, set, has, and delete methods.
  • Accepts any type for the keys instead of just strings.
  • Provides an iterator for easy for-of usage and maintains order of results.
  • Doesn't have edge cases with prototypes and other properties showing up during iteration or copying.
  • Supports millions of items.
  • Is very fast.

If you need a dictionary then you should just use a Map().

However, if you're only using string-based keys and need maximum read performance, then objects might be a better choice. This is because Javascript engines compile objects down to C++ classes in the background. The access path for properties on these classes is very optimized and much faster than a function call for Map().get().

These classes are also cached, so creating a new object with the same exact properties means the engine will reuse an existing background class. Adding or removing a property causes the shape of the class to change and the backing class to be re-compiled, which is why using an object as a dictionary with lots of additions and deletions is very slow, but reads of existing keys without changing the object are very fast.

So if you have a write-once read-heavy workload with string keys then you can use an object as a high-performance dictionary, but for everything else use a Map().

How to make an ng-click event conditional?

I had this issue also and I simply found out that if you simply remove the "#" the issue goes off. Like this :

<a href="" class="disabled" ng-click="doSomething(object)">Do something</a>

How to check if C string is empty

You can check the return value from scanf. This code will just sit there until it receives a string.

int a;

do {
  // other code
  a = scanf("%s", url);

} while (a <= 0);

How to move files from one git repo to another (not a clone), preserving history

Having had a similar itch to scratch (altough only for some files of a given repository) this script proved to be really helpful: git-import

The short version is that it creates patch files of the given file or directory ($object) from the existing repository:

cd old_repo
git format-patch --thread -o "$temp" --root -- "$object"

which then get applied to a new repository:

cd new_repo
git am "$temp"/*.patch 

For details please look up:

Jenkins/Hudson - accessing the current build number?

Jenkins Pipeline also provides the current build number as the property number of the currentBuild. It can be read as currentBuild.number.

For example:

// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"

Other properties of currentBuild are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

VIM Disable Automatic Newline At End Of File

Starting with vim v7.4 you can use

:set nofixendofline

There is some information about that change here: http://ftp.vim.org/vim/patches/7.4/7.4.785 .

sweet-alert display HTML code in text

The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014.

I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc.

_x000D_
_x000D_
Swal.fire({
  title: "<i>Title</i>", 
  html: "Testno  sporocilo za objekt: <b>test</b>",  
  confirmButtonText: "V <u>redu</u>", 
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
_x000D_
_x000D_
_x000D_

Java JTextField with input hint

For any Swing component (that is, anything that extends JComponent), you can call the setToolTipText(String) method.

For more information, reference the following links:

Find a line in a file and remove it

Here you go. This solution uses a DataInputStream to scan for the position of the string you want replaced and uses a FileChannel to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.

public static long scanForString(String text, File file) throws IOException {
    if (text.isEmpty())
        return file.exists() ? 0 : -1;
    // First of all, get a byte array off of this string:
    byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);

    // Next, search the file for the byte array.
    try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

        List<Integer> matches = new LinkedList<>();

        for (long pos = 0; pos < file.length(); pos++) {
            byte bite = dis.readByte();

            for (int i = 0; i < matches.size(); i++) {
                Integer m = matches.get(i);
                if (bytes[m] != bite)
                    matches.remove(i--);
                else if (++m == bytes.length)
                    return pos - m + 1;
                else
                    matches.set(i, m);
            }

            if (bytes[0] == bite)
                matches.add(1);
        }
    }
    return -1;
}

public static void replaceText(String text, String replacement, File file) throws IOException {
    // Open a FileChannel with writing ability. You don't really need the read
    // ability for this specific case, but there it is in case you need it for
    // something else.
    try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
        long scanForString = scanForString(text, file);
        if (scanForString == -1) {
            System.out.println("String not found.");
            return;
        }
        channel.position(scanForString);
        channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
    }
}

Example

Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method Call:

replaceText("QRS", "000", new File("path/to/file");

Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ

Create Carriage Return in PHP String?

There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !

Stackoverflow reference

how to open a jar file in Eclipse

there is an Eclipse app called Import Jar As Project. I think it is quite simple and useful. https://marketplace.eclipse.org/content/import-jar-project?mpc=true&mpc_state=

redirect while passing arguments

I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".

To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P

So maybe:

def super_cool_logic():
    # execute common code here

@app.route("/foo")
def do_foo():
    # do some logic here
    super_cool_logic()
    return render_template("foo.html")

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        super_cool_logic()
        return render_template("foo.html", messages={"main":"Condition failed on page baz"})

I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)

CSS: How to align vertically a "label" and "input" inside a "div"?

Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.

position:absolute; 
top:0; bottom:0; left:0; right:0;
margin:auto;

What is "not assignable to parameter of type never" error in typescript?

You need to type result to an array of string const result: string[] = [];.

How to fix height of TR?

Putting div inside a td made it work for me.

<table width="100%">
    <tr><td><div style="font-size:2px; height:2px; vertical-align:middle;">&nbsp;</div></td></tr>

How do I make a newline after a twitter bootstrap element?

Like KingCronus mentioned in the comments you can use the row class to make the list or heading on its own line. You could use the row class on either or both elements:

<ul class="nav nav-tabs span2 row">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>

<div class="well span6 row">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

Integer ASCII value to character in BASH using printf

One option is to directly input the character you're interested in using hex or octal notation:

printf "\x41\n"
printf "\101\n"

read.csv warning 'EOF within quoted string' prevents complete reading of file

In the R help section, as pointed out above, just disabling quoting altogether, by simply adding:

    quote = "" 

to the read.csv() worked for me.

The error, "EOF within quoted string", occurred with:

    > iproscan.53A.neg     = read.csv("interproscan.53A.neg.n.csv",
    +                        colClasses=c(pb.id      = "character",
    +                                     genLoc     = "character",
    +                                     icode      = "character",
    +                                     length     = "character",
    +                                     proteinDB  = "character",
    +                                     protein.id = "character",
    +                                     prot.desc  = "character",
    +                                     start      = "character",
    +                                     end        = "character",
    +                                     evalue     = "character",
    +                                     tchar      = "character",
    +                                     date       = "character",
    +                                     ipro.id    = "character",
    +                                     prot.name  = "character",
    +                                     go.cat     = "character",
    +                                     reactome.id= "character"),
    +                                     as.is=T,header=F)
    Warning message:
    In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
      EOF within quoted string
    > dim(iproscan.53A.neg)
    [1] 69383    16

And the file read in was missing 6,619 lines. But by disabling quoting

    > iproscan.53A.neg     = read.csv("interproscan.53A.neg.n.csv",
    +                        colClasses=c(pb.id      = "character",
    +                                     genLoc     = "character",
    +                                     icode      = "character",
    +                                     length     = "character",
    +                                     proteinDB  = "character",
    +                                     protein.id = "character",
    +                                     prot.desc  = "character",
    +                                     start      = "character",
    +                                     end        = "character",
    +                                     evalue     = "character",
    +                                     tchar      = "character",
    +                                     date       = "character",
    +                                     ipro.id    = "character",
    +                                     prot.name  = "character",
    +                                     go.cat     = "character",
    +                                     reactome.id= "character"),
    +                                     as.is=T,header=F,**quote=""**)    
    > 
    > dim(iproscan.53A.neg)
    [1] 76002    16

Worked without error and all lines were successfully read in.

Python pandas: fill a dataframe row by row

My approach was, but I can't guarantee that this is the fastest solution.

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Apple uses "NSObjectProtocol" instead of "class".

public protocol UIScrollViewDelegate : NSObjectProtocol {
   ...
}

This also works for me and removed the errors I was seeing when trying to implement my own delegate pattern.

C# difference between == and Equals()

Firstly, there is a difference. For numbers

> 2 == 2.0
True

> 2.Equals(2.0)
False

And for strings

> string x = null;
> x == null
True

> x.Equals(null)
NullReferenceException

In both cases, == behaves more usefully than .Equals

How do I create dynamic variable names inside a loop?

Try this

window['marker'+i] = "some stuff"; 

ORA-28001: The password has expired

Check "PASSWORD_LIFE_TIME" by

Sql > select * from dba_profiles;

Set to Never expire

Sql> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

Then reset the password of locked user.

Differences between Oracle JDK and OpenJDK

It is very close - our build process for Oracle JDK releases builds on OpenJDK 7 by adding just a couple of pieces, like the deployment code, which includes Oracle's implementation of the Java Plugin and Java WebStart, as well as some closed source third-party components like a graphics rasterizer, some open-source third party components, like Rhino, and a few bits and pieces here and there, like additional documentation or third-party fonts. Moving forward, we intend to open source all pieces of the Oracle JDK except those that we consider commercial features such as JRockit Mission Control (not yet available in Oracle JDK) and replace encumbered third-party components with open source alternatives to achieve closer parity between the codebases.

· Yes, the garbage collection and other JVM parameters are the same.

· The performance of GC is the same in both.

Call a function with argument list in python

The simpliest way to wrap a function

    func(*args, **kwargs)

... is to manually write a wrapper that would call func() inside itself:

    def wrapper(*args, **kwargs):
        # do something before
        try:
            return func(*a, **kwargs)
        finally:
            # do something after

In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function anyFunc():

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
            try:
                # do something before
                return anyFunc(*args, **kwargs)
            finally:
                #do something after
        return wrapper

Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name:

    *args

For example you can define a function that would take any number of arguments:

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:

    **kwargs

A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments

Oracle 12c Installation failed to access the temporary location

Install it from CMD using the command

setup.exe -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

Reference

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

Fit Image into PictureBox

You could try changing the: SizeMode property of the PictureBox.

You could also set your image as the BackGroundImage of the PictureBox and try changing the BackGroundImageLayout to the correct mode.

What is the most effective way to get the index of an iterator of an std::vector?

I would prefer it - vec.begin() precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm.

Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter.

Note: it is a common name for a container iterator,std::container_type::iterator it;.

Postgres: How to convert a json string to text?

Mr. Curious was curious about this as well. In addition to the #>> '{}' operator, in 9.6+ one can get the value of a jsonb string with the ->> operator:

select to_jsonb('Some "text"'::TEXT)->>0;
  ?column?
-------------
 Some "text"
(1 row)

If one has a json value, then the solution is to cast into jsonb first:

select to_json('Some "text"'::TEXT)::jsonb->>0;
  ?column?
-------------
 Some "text"
(1 row)

check / uncheck checkbox using jquery?

You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {
   prop=true; 
}
$('#checkbox').prop('checked',prop);

or simply,

$('#checkbox').prop('checked',(value == 1));

Snippet

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
_x000D_
_x000D_

How to change font of UIButton with Swift

You should go through the titleLabel property.

button.titleLabel.font

The font property has been deprecated since iOS 3.0.

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

How do I read any request header in PHP

I was using CodeIgniter and used the code below to get it. May be useful for someone in future.

$this->input->get_request_header('X-Requested-With');

How to import js-modules into TypeScript file?

You can import the whole module as follows:

import * as FriendCard from './../pages/FriendCard';

For more details please refer the modules section of Typescript official docs.

Difference between margin and padding?

Basically, the difference between padding and margin come in terms of the background. Padding will decide the space between content, while margin decide the outside edge of elements!

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

How to declare an array of objects in C#

you need to initialize the object elements of the array.

GameObject[] houses = new GameObject[200];

for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}

Of course you initialize elements selectively using different constructors anywhere else before you reference them.

Git cli: get user info from username

Add my two cents, if you're using windows commnad line:

git config --list | findstr user.name will give username directly.

The findstr here is quite similar to grep in linux.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How do I declare a two dimensional array?

$r = array("arr1","arr2");

to echo a single array element you should write:

echo $r[0];
echo $r[1];

output would be: arr1 arr2

Disable Input fields in reactive form

I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).

In my case I had to reset my form before reloading:

this.form = undefined; this.router.navigate([path]);

How can I count text lines inside an DOM element? Can I?

I am convinced that it is impossible now. It was, though.

IE7’s implementation of getClientRects did exactly what I want. Open this page in IE8, try refreshing it varying window width, and see how number of lines in the first element changes accordingly. Here’s the key lines of the javascript from that page:

var rects = elementList[i].getClientRects();
var p = document.createElement('p');
p.appendChild(document.createTextNode('\'' + elementList[i].tagName + '\' element has ' + rects.length + ' line(s).'));

Unfortunately for me, Firefox always returns one client rectangle per element, and IE8 does the same now. (Martin Honnen’s page works today because IE renders it in IE compat view; press F12 in IE8 to play with different modes.)

This is sad. It looks like once again Firefox’s literal but worthless implementation of the spec won over Microsoft’s useful one. Or do I miss a situation where new getClientRects may help a developer?

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

How does Google reCAPTCHA v2 work behind the scenes?

Please remember that Google also use reCaptcha together with

Canvas fingerprinting 

to uniquely recognize User/Browsers without cookies!

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

String representation of an Enum

If I'm understanding you correctly, you can simply use .ToString() to retrieve the name of the enum from the value (Assuming it's already cast as the Enum); If you had the naked int (lets say from a database or something) you can first cast it to the enum. Both methods below will get you the enum name.

AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
Console.WriteLine(myCurrentSetting); // Prints: FORMS
string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
Console.WriteLine(name); // Prints: FORMS

Keep in mind though, the second technique assumes you are using ints and your index is 1 based (not 0 based). The function GetNames also is quite heavy by comparison, you are generating a whole array each time it's called. As you can see in the first technique, .ToString() is actually called implicitly. Both of these are already mentioned in the answers of course, I'm just trying to clarify the differences between them.

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

I wanted to add something to the answer already provided. maven-compiler-plugin by default will compile your project using Java 1.5 which is where m2e get's its information.

That's why you have to explicitly declare the maven-compiler-plugin in your project with something other then 1.5. Your effective pom.xml will implicitly use the default set in the maven-compiler-plugin pom.xml.

How to close off a Git Branch?

after complete the code first merge branch to master then delete that branch

git checkout master
git merge <branch-name>
git branch -d <branch-name>

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

How to force Eclipse to ask for default workspace?

if your eclipse is auto-closing at startup you may do this: open the properties of your shortcut and add -clean at the end of the path. or do this in cmd : cd C:\PATH_TO_YOUR_ECLIPSE\eclipse -clean like mentioned earlier above comments

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

How to pass a value to razor variable from javascript variable?

You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".

When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.

The Javascript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).

This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.

In short:

  1. The server gets a request.

  2. The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.

  3. The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)

  4. the browser renders the page and executes all the Javascript

How to create an executable .exe file from a .m file

The Matlab Compiler is the standard way to do this. mcc is the command. The Matlab Runtime is required to run the programs; I'm not sure if it can be directly integrated with the executable or not.

psql: command not found Mac

As a postgreSQL newbie I found the os x setup instructions on the postgresql site impenetrable. I got all kinds of errors. Fortunately the uninstaller worked fine.

cd /Library/PostgreSQL/11; open uninstall-postgresql.app/

Then I started over with a brew install followed by this article How to setup PostgreSQL on MacOS

It works fine now.

JQuery Validate Dropdown list

I have modified your code a little. Here's a working version (for me):

    <select name="dd1" id="dd1">
       <option value="none">None</option>
       <option value="o1">option 1</option>
       <option value="o2">option 2</option>
       <option value="o3">option 3</option>
    </select>  
    <div style="color:red;" id="msg_id"></div>

<script>
    $('#everything').submit(function(e){ 
        var department = $("#msg_id");
        var msg = "Please select Department";
            if ($('#dd1').val() == "") {
                department.append(msg);
                e.preventDefault();
                return false;
            }
        });
 </script>

How can I easily add storage to a VirtualBox machine with XP installed?

For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.

http://forums.virtualbox.org/viewtopic.php?f=6&t=22422

As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.

http://gparted.sourceforge.net/download.php

C# Help reading foreign characters using StreamReader

I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

How can I prevent a window from being resized with tkinter?

You can use the minsize and maxsize to set a minimum & maximum size, for example:

def __init__(self,master):
    master.minsize(width=666, height=666)
    master.maxsize(width=666, height=666)

Will give your window a fixed width & height of 666 pixels.

Or, just using minsize

def __init__(self,master):
    master.minsize(width=666, height=666)

Will make sure your window is always at least 666 pixels large, but the user can still expand the window.

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Bootstrap: change background color

You can target that div from your stylesheet in a number of ways.

Simply use

.col-md-6:first-child {
  background-color: blue;
}

Another way is to assign a class to one div and then apply the style to that class.

<div class="col-md-6 blue"></div>

.blue {
  background-color: blue;
}

There are also inline styles.

<div class="col-md-6" style="background-color: blue"></div>

Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

_x000D_
_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
    <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
      <div class="col-xs-6">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
      <div class="col-xs-6 blue">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

JavaScript split String with white space

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
    string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
    if(i != string.length-1){
        stringArray.push(" ");
    }
}

Update: Removed trailing space.

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

Quick Way to Implement Dictionary in C

I am surprised no one mentioned hsearch/hcreate set of libraries which although is not available on windows, but is mandated by POSIX, and therefore available in Linux / GNU systems.

The link has a simple and complete basic example that very well explains its usage.

It even has thread safe variant, is easy to use and very performant.

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

Selected tab's color in Bottom Navigation View

This will work:

setItemBackgroundResource(android.R.color.holo_red_light)

How to print formatted BigDecimal values?

I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:

val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)

Result displaying $formattedBigD:

1,000,000,000,000,000,000,000,000,000,000

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

How to make <input type="file"/> accept only these types?

As stated on w3schools:

audio/* - All sound files are accepted

video/* - All video files are accepted

image/* - All image files are accepted

MIME_type - A valid MIME type, with no parameters. Look at IANA MIME types for a complete list of standard MIME types

It is more efficient to use if-return-return or if-else-return?

From a performance point of view, it doesn't matter in Python, and I'd assume the same for every modern language out there.

It really comes down to style and readability. Your second option (if-else block) is more readable than the first, and a lot more readable than the one-liner ternary operation.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

Android getting value from selected radiobutton

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId)
       {
           radioButton = (RadioButton) findViewById(checkedId);
           Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
       }
   }
   );

How do I clone a single branch in Git?

If you want a shallow clone, you can do this with:

git clone -b mybranch --depth=1 https://example.com/myproject.git localname

--depth=1 implies --single-branch.

Get operating system info

Based on the answer by Fred-II I wanted to share my take on the getOS function, it avoids globals, merges both lists and detects the architecture (x32/x64)

/**
 * @param $user_agent null
 * @return string
 */
function getOS($user_agent = null)
{
    if(!isset($user_agent) && isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
    }

    // https://stackoverflow.com/questions/18070154/get-operating-system-info-with-php
    $os_array = [
        'windows nt 10'                              =>  'Windows 10',
        'windows nt 6.3'                             =>  'Windows 8.1',
        'windows nt 6.2'                             =>  'Windows 8',
        'windows nt 6.1|windows nt 7.0'              =>  'Windows 7',
        'windows nt 6.0'                             =>  'Windows Vista',
        'windows nt 5.2'                             =>  'Windows Server 2003/XP x64',
        'windows nt 5.1'                             =>  'Windows XP',
        'windows xp'                                 =>  'Windows XP',
        'windows nt 5.0|windows nt5.1|windows 2000'  =>  'Windows 2000',
        'windows me'                                 =>  'Windows ME',
        'windows nt 4.0|winnt4.0'                    =>  'Windows NT',
        'windows ce'                                 =>  'Windows CE',
        'windows 98|win98'                           =>  'Windows 98',
        'windows 95|win95'                           =>  'Windows 95',
        'win16'                                      =>  'Windows 3.11',
        'mac os x 10.1[^0-9]'                        =>  'Mac OS X Puma',
        'macintosh|mac os x'                         =>  'Mac OS X',
        'mac_powerpc'                                =>  'Mac OS 9',
        'linux'                                      =>  'Linux',
        'ubuntu'                                     =>  'Linux - Ubuntu',
        'iphone'                                     =>  'iPhone',
        'ipod'                                       =>  'iPod',
        'ipad'                                       =>  'iPad',
        'android'                                    =>  'Android',
        'blackberry'                                 =>  'BlackBerry',
        'webos'                                      =>  'Mobile',

        '(media center pc).([0-9]{1,2}\.[0-9]{1,2})'=>'Windows Media Center',
        '(win)([0-9]{1,2}\.[0-9x]{1,2})'=>'Windows',
        '(win)([0-9]{2})'=>'Windows',
        '(windows)([0-9x]{2})'=>'Windows',

        // Doesn't seem like these are necessary...not totally sure though..
        //'(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'Windows NT',
        //'(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})'=>'Windows NT', // fix by bg

        'Win 9x 4.90'=>'Windows ME',
        '(windows)([0-9]{1,2}\.[0-9]{1,2})'=>'Windows',
        'win32'=>'Windows',
        '(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})'=>'Java',
        '(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}'=>'Solaris',
        'dos x86'=>'DOS',
        'Mac OS X'=>'Mac OS X',
        'Mac_PowerPC'=>'Macintosh PowerPC',
        '(mac|Macintosh)'=>'Mac OS',
        '(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'SunOS',
        '(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'BeOS',
        '(risc os)([0-9]{1,2}\.[0-9]{1,2})'=>'RISC OS',
        'unix'=>'Unix',
        'os/2'=>'OS/2',
        'freebsd'=>'FreeBSD',
        'openbsd'=>'OpenBSD',
        'netbsd'=>'NetBSD',
        'irix'=>'IRIX',
        'plan9'=>'Plan9',
        'osf'=>'OSF',
        'aix'=>'AIX',
        'GNU Hurd'=>'GNU Hurd',
        '(fedora)'=>'Linux - Fedora',
        '(kubuntu)'=>'Linux - Kubuntu',
        '(ubuntu)'=>'Linux - Ubuntu',
        '(debian)'=>'Linux - Debian',
        '(CentOS)'=>'Linux - CentOS',
        '(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - Mandriva',
        '(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - SUSE',
        '(Dropline)'=>'Linux - Slackware (Dropline GNOME)',
        '(ASPLinux)'=>'Linux - ASPLinux',
        '(Red Hat)'=>'Linux - Red Hat',
        // Loads of Linux machines will be detected as unix.
        // Actually, all of the linux machines I've checked have the 'X11' in the User Agent.
        //'X11'=>'Unix',
        '(linux)'=>'Linux',
        '(amigaos)([0-9]{1,2}\.[0-9]{1,2})'=>'AmigaOS',
        'amiga-aweb'=>'AmigaOS',
        'amiga'=>'Amiga',
        'AvantGo'=>'PalmOS',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})'=>'Linux',
        '[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}'=>'Linux',
        '(webtv)/([0-9]{1,2}\.[0-9]{1,2})'=>'WebTV',
        'Dreamcast'=>'Dreamcast OS',
        'GetRight'=>'Windows',
        'go!zilla'=>'Windows',
        'gozilla'=>'Windows',
        'gulliver'=>'Windows',
        'ia archiver'=>'Windows',
        'NetPositive'=>'Windows',
        'mass downloader'=>'Windows',
        'microsoft'=>'Windows',
        'offline explorer'=>'Windows',
        'teleport'=>'Windows',
        'web downloader'=>'Windows',
        'webcapture'=>'Windows',
        'webcollage'=>'Windows',
        'webcopier'=>'Windows',
        'webstripper'=>'Windows',
        'webzip'=>'Windows',
        'wget'=>'Windows',
        'Java'=>'Unknown',
        'flashget'=>'Windows',

        // delete next line if the script show not the right OS
        //'(PHP)/([0-9]{1,2}.[0-9]{1,2})'=>'PHP',
        'MS FrontPage'=>'Windows',
        '(msproxy)/([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        '(msie)([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        'libwww-perl'=>'Unix',
        'UP.Browser'=>'Windows CE',
        'NetAnts'=>'Windows',
    ];

    // https://github.com/ahmad-sa3d/php-useragent/blob/master/core/user_agent.php
    $arch_regex = '/\b(x86_64|x86-64|Win64|WOW64|x64|ia64|amd64|ppc64|sparc64|IRIX64)\b/ix';
    $arch = preg_match($arch_regex, $user_agent) ? '64' : '32';

    foreach ($os_array as $regex => $value) {
        if (preg_match('{\b('.$regex.')\b}i', $user_agent)) {
            return $value.' x'.$arch;
        }
    }

    return 'Unknown';
}

How to add the text "ON" and "OFF" to toggle button

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 90px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ca2222;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(55px);_x000D_
  -ms-transform: translateX(55px);_x000D_
  transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  transform: translate(-50%,-50%);_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  font-size: 10px;_x000D_
  font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
_x000D_
_x000D_

What are naming conventions for MongoDB?

Naming convention for collection

In order to name a collection few precautions to be taken :

  1. A collection with empty string (“”) is not a valid collection name.
  2. A collection name should not contain the null character because this defines the end of collection name.
  3. Collection name should not start with the prefix “system.” as this is reserved for internal collections.
  4. It would be good to not contain the character “$” in the collection name as various driver available for database do not support “$” in collection name.

Things to keep in mind while creating a database name are :

  1. A database with empty string (“”) is not a valid database name.
  2. Database name cannot be more than 64 bytes.
  3. Database name are case-sensitive, even on non-case-sensitive file systems. Thus it is good to keep name in lower case.
  4. A database name cannot contain any of these characters “/, , ., “, *, <, >, :, |, ?, $,”. It also cannot contain a single space or null character.

For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

DateTime.ToString() format that can be used in a filename or extension?

You can make a path for your file as bellow:

string path = "fileName-"+DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

jQuery: Setting select list 'selected' based on text, failing strangely

I usually use:

$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

PHP Date Time Current Time Add Minutes

$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata')); 
echo $dateTime->modify("+10 minutes")->format("H:i:s A");

Fastest way to extract frames using ffmpeg?

In my case I need frames at least every second. I used the 'seek to' approach above but wondered if I could parallelize the task. I used the N processes with FIFO approach here: https://unix.stackexchange.com/questions/103920/parallelize-a-bash-for-loop/216475#216475

open_sem(){
  mkfifo /tmp/pipe-$$
  exec 3<>/tmp/pipe-$$
  rm /tmp/pipe-$$
  local i=$1
  for((;i>0;i--)); do
    printf %s 000 >&3
  done
}
run_with_lock(){
    local x
    read -u 3 -n 3 x && ((0==x)) || exit $x
    (
    "$@" 
    printf '%.3d' $? >&3
    )&
}
N=16
open_sem $N
time for i in {0..39} ; do run_with_lock ffmpeg -ss `echo $i` -i /tmp/input/GOPR1456.MP4  -frames:v 1 /tmp/output/period_down_$i.jpg  & done

Essentially I forked the process with & but limited the number of concurrent threads to N.

This improved the 'seek to' approach from 26 seconds to 16 seconds in my case. The only problem is the main thread does not exit cleanly back to the terminal since stdout gets flooded.

How do you get centered content using Twitter Bootstrap?

Update 2019 - Bootstrap 4

"Centered content" can mean many different things, and Bootstrap centering has changed a lot since the original post.

Horizontal Center

Bootstrap 3

  • text-center is used for display:inline elements
  • center-block to center display:block elements
  • col-*offset-* to center grid columns
  • see this answer to center the navbar

Demo Bootstrap 3 Horizontal Centering

Bootstrap 4

  • text-center is still used for display:inline elements
  • mx-auto replaces center-block to center display:block elements
  • offset-* or mx-auto can be used to center grid columns
  • justify-content-center in row can also be used to center col-*

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo Bootstrap 4 Horizontal Centering


Vertical Center

Now that Bootstrap 4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..


1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

Vertical Center Using Auto Margins Demo

my-auto represents margins on the vertical y-axis and is equivalent to:

margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

vertical center grid columns

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

Vertical Center Different Height Columns Demo


3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

Vertical Center Using Display Utils Demo

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

Access index of the parent ng-repeat from child ng-repeat

According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

so you can write

<div ng-repeat="(fIndex, f) in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething(fIndex)">Add Something</a>
    </div>
  </div>
</div>

One level up is still quite clean with $parent.$index but several parents up, things can get messy.

Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

Save PHP variables to a text file

This should do what you want, but without more context I can't tell for sure.

Writing $text to a file:

$text = "Anything";
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);

Retrieving it again:

include 'filename.php';
echo $text;

PHP Check for NULL

How about using

if (empty($result['column']))

sed: print only matching group

And for yet another option, I'd go with awk!

echo "foo bar <foo> bla 1 2 3.4" | awk '{ print $(NF-1), $NF; }'

This will split the input (I'm using STDIN here, but your input could easily be a file) on spaces, and then print out the last-but-one field, and then the last field. The $NF variables hold the number of fields found after exploding on spaces.

The benefit of this is that it doesn't matter if what precedes the last two fields changes, as long as you only ever want the last two it'll continue to work.

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

Implement division with bit-wise operator

Division of two numbers using bitwise operators.

#include <stdio.h>

int remainder, divisor;

int division(int tempdividend, int tempdivisor) {
    int quotient = 1;

    if (tempdivisor == tempdividend) {
        remainder = 0;
        return 1;
    } else if (tempdividend < tempdivisor) {
        remainder = tempdividend;
        return 0;
    }   

    do{

        tempdivisor = tempdivisor << 1;
        quotient = quotient << 1;

     } while (tempdivisor <= tempdividend);


     /* Call division recursively */
    quotient = quotient + division(tempdividend - tempdivisor, divisor);

    return quotient;
} 


int main() {
    int dividend;

    printf ("\nEnter the Dividend: ");
    scanf("%d", &dividend);
    printf("\nEnter the Divisor: ");
    scanf("%d", &divisor);   

    printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
    printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);
    getch();
}

wildcard * in CSS for classes

What you need is called attribute selector. An example, using your html structure, is the following:

div[class^="tocolor-"], div[class*=" tocolor-"] {
    color:red 
}

In the place of div you can add any element or remove it altogether, and in the place of class you can add any attribute of the specified element.

[class^="tocolor-"] — starts with "tocolor-".
[class*=" tocolor-"] — contains the substring "tocolor-" occurring directly after a space character.

Demo: http://jsfiddle.net/K3693/1/

More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs

Attach event to dynamic elements in javascript

I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT. Here is the code with a simple example:

_x000D_
_x000D_
String.prototype.addEventListener=function(eventHandler, functionToDo){_x000D_
  let selector=this;_x000D_
  document.body.addEventListener(eventHandler, function(e){_x000D_
    e=(e||window.event);_x000D_
    e.preventDefault();_x000D_
    const path=e.path;_x000D_
    path.forEach(function(elem){_x000D_
      const selectorsArray=document.querySelectorAll(selector);_x000D_
      selectorsArray.forEach(function(slt){_x000D_
        if(slt==elem){_x000D_
          if(typeof functionToDo=="function") functionToDo(el=slt, e=e);_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
// And here is how we can use it actually !_x000D_
_x000D_
"input[type='number']".addEventListener("click", function(element, e){_x000D_
 console.log( e ); // Console log the value of the current number input_x000D_
});
_x000D_
<input type="number" value="25">_x000D_
<br>_x000D_
<input type="number" value="15">_x000D_
<br><br>_x000D_
<button onclick="addDynamicInput()">Add a Dynamic Input</button>_x000D_
<script type="text/javascript">_x000D_
  function addDynamicInput(){_x000D_
    const inpt=document.createElement("input");_x000D_
          inpt.type="number";_x000D_
          inpt.value=Math.floor(Math.random()*30+1);_x000D_
    document.body.prepend(inpt);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can I get dictionary key as variable directly in Python (not by searching from value)?

keys=[i for i in mydictionary.keys()] or keys = list(mydictionary.keys())

Remove shadow below actionbar

You must set app:elevation="0dp" in the android.support.design.widget.AppBarLayout and then it works.

<android.support.design.widget.AppBarLayout
    app:elevation="0dp"... >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/transparent"
        app:popupTheme="@style/AppTheme.PopupOverlay" >


    </android.support.v7.widget.Toolbar>

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

How to stop Python closing immediately when executed in Microsoft Windows

Depending on what I'm using it for, or if I'm doing something that others will use, I typically just input("Do eighteen backflips to continue") if it's just for me, if others will be using I just create a batch file and pause it after

cd '/file/path/here'
python yourfile.py
pause 

I use the above if there is going to be files renamed, moved, copied, etc. and my cmd needs to be in the particular folder for things to fall where I want them, otherwise - just

python '/path/to/file/yourfile.py'
pause

Oracle's default date format is YYYY-MM-DD, WHY?

Are you sure you're not confusing Oracle database with Oracle SQL Developer?

The database itself has no date format, the date comes out of the database in raw form. It's up to the client software to render it, and SQL Developer does use YYYY-MM-DD as its default format, which is next to useless, I agree.

edit: As was commented below, SQL Developer can be reconfigured to display DATE values properly, it just has bad defaults.

Laravel 5 PDOException Could Not Find Driver

If your database is PostgreSQL and you have php7.2 you should run the following commands:

sudo apt-get install php7.2-pgsql

and

php artisan migrate

How can I show figures separately in matplotlib?

Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py, etc).

C compiler for Windows?

Can't you get a free version of Visual Studio Student Addition from your school? Most Universities have programs to give free software to students.

Getting the class name from a static method in Java

If you want the entire package name with it, call:

String name = MyClass.class.getCanonicalName();

If you only want the last element, call:

String name = MyClass.class.getSimpleName();

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

How can you program if you're blind?

I'm blind and from some months I'm using VINUX (a linux distro based on Ubuntu) with SODBEANS (a version of netbeans with a plug-in named SAPPY that add a TTS support). This solution works quite well but sometimes I prefer to launch Win XP and NVDA for launching many pages on FireFox because Vinux doesn't work very well when you try to open more than 3 windows of FireFox...

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

MongoDB logging all queries

db.adminCommand( { getLog: "*" } )

Then

db.adminCommand( { getLog : "global" } )

Counter in foreach loop in C#

Without Custom Foreach Version:

datas.Where((data, index) =>
{
    //Your Logic
    return false;
}).Any();

In some simple case,my way is using where + false + any.
It is fater a little than foreach + select((data,index)=>new{data,index}),and without custom Foreach method.

MyLogic:

  • use statement body run your logic.
  • because return false,new Enumrable data count is zero.
  • use Any() let yeild run.

Benchmark Test Code

[RPlotExporter, RankColumn]
public class BenchmarkTest
{
    public static IEnumerable<dynamic> TestDatas = Enumerable.Range(1, 10).Select((data, index) => $"item_no_{index}");

    [Benchmark]
    public static void ToArrayAndFor()
    {
        var datats = TestDatas.ToArray();
        for (int index = 0; index < datats.Length; index++)
        {
            var result = $"{datats[index]}{index}";
        }
    }

    [Benchmark]
    public static void IEnumrableAndForach()
    {
        var index = 0;
        foreach (var item in TestDatas)
        {
            index++;
            var result = $"{item}{index}";
        }
    }

    [Benchmark]
    public static void LinqSelectForach()
    {
        foreach (var item in TestDatas.Select((data, index) => new { index, data }))
        {
            var result = $"{item.data}{item.index}";
        }
    }

    [Benchmark]
    public static void LinqSelectStatementBodyToList()
    {
        TestDatas.Select((data, index) =>
        {
            var result = $"{data}{index}";
            return true;
        }).ToList();
    }

    [Benchmark]
    public static void LinqSelectStatementBodyToArray()
    {
        TestDatas.Select((data, index) =>
        {
            var result = $"{data}{index}";
            return true;
        }).ToArray();
    }

    [Benchmark]
    public static void LinqWhereStatementBodyAny()
    {
        TestDatas.Where((data, index) =>
        {
            var result = $"{data}{index}";
            return false;
        }).Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var summary = BenchmarkRunner.Run<BenchmarkTest>();

        System.Console.Read();
    }
}

Benchmark Result :

                         Method |     Mean |     Error |    StdDev | Rank |
------------------------------- |---------:|----------:|----------:|-----:|
                  ToArrayAndFor | 4.027 us | 0.0797 us | 0.1241 us |    4 |
            IEnumrableAndForach | 3.494 us | 0.0321 us | 0.0285 us |    1 |
               LinqSelectForach | 3.842 us | 0.0503 us | 0.0471 us |    3 |
  LinqSelectStatementBodyToList | 3.822 us | 0.0416 us | 0.0389 us |    3 |
 LinqSelectStatementBodyToArray | 3.857 us | 0.0764 us | 0.0785 us |    3 |
      LinqWhereStatementBodyAny | 3.643 us | 0.0693 us | 0.0712 us |    2 |

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

How to change text color of cmd with windows batch script every 1 second

I am doing something very similar. I'm just getting into coding, so this may not be the most efficient way of doing it, but this is how I did it:

@ECHO OFF
ECHO HELLO
ping localhost -n 1 >nul
cls
color 01
ECHO HELLO
ping localhost -n 1 >nul
cls
color 02
ECHO HELLO 

and so one and so forth.

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

How to pause a YouTube player when hiding the iframe?

Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:

function initVideos() {

  // Find all video iframes on the page:
  var iframes = $(".video").find("iframe");

  // For each of them:
  for (var i = 0; i < iframes.length; i++) {
    // If "enablejsapi" is not set on the iframe's src, set it:
    if (iframes[i].src.indexOf("enablejsapi") === -1) {
      // ...check whether there is already a query string or not:
      // (ie. whether to prefix "enablejsapi" with a "?" or an "&")
      var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&amp;";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.

(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

How to remove all of the data in a table using Django

Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :

def delete_all(self):
  Reporter.objects.all().delete()
  return HttpResponseRedirect('/')

Focus Input Box On Load

function focusOnMyInputBox(){                                 
    document.getElementById("myinputbox").focus();
}

<body onLoad="focusOnMyInputBox();">

<input type="text"  size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

how to print a string to console in c++

"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"

Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)

How to submit a form using Enter key in react.js?

import React, { useEffect, useRef } from 'react';

function Example() {

    let inp = useRef();
    useEffect(() => {
        if (!inp && !inp.current) return;
        inp.current.focus();
        return () => inp = null;
    });

    const handleSubmit = () => {
        //...
    }

    return (
        <form
            onSubmit={e => {
                e.preventDefault();
                handleSubmit(e);
            }}
        >
            <input
                name="fakename"
                defaultValue="...."
                ref={inp}
                type="radio"
                style={{
                    position: "absolute",
                    opacity: 0
                }}
            />
            <button type="submit">
                submit
            </button>
        </form>
    )
}

Enter code here sometimes in popups it would not work to binding just a form and passing the onSubmit to the form because form may not have any input.

In this case if you bind the event to the document by doing document.addEventListener it will cause problem in another parts of the application.

For solving this issue we should wrap a form and should put a input with what is hidden by css, then you focus on that input by ref it will be work correctly.

Detect rotation of Android phone in the browser with JavaScript

Cross browser way

$(window).on('resize orientationchange webkitfullscreenchange mozfullscreenchange fullscreenchange',  function(){
//code here
});

Fitting polynomial model to data in R

The easiest way to find the best fit in R is to code the model as:

lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)

After using step down AIC regression

lm.s <- step(lm.1)

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves

How to capture the browser window close event?

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

$(window).bind("beforeunload", function() {
    return true || confirm("Do you really want to close?"); 
}); 

on complete or link

$(window).unbind();

How to restart a node.js server

Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.

java.lang.OutOfMemoryError: Java heap space in Maven

Not only heap memory. also increase perm size to resolve that exception in maven use these variables in environment variable.

variable name: MAVEN_OPTS
variable value: -Xmx512m -XX:MaxPermSize=256m

Example :

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=500m"

Pandas: Looking up the list of sheets in an excel file

If you:

  • care about performance
  • don't need the data in the file at execution time.
  • want to go with conventional libraries vs rolling your own solution

Below was benchmarked on a ~10Mb xlsx, xlsb file.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

Benchmarks: ~ 14x speed improvement

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

Benchmarks: ~ 56x speed improvement

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Notes:

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

You're looking for the SyndicationFeed class, which does exactly that.

How do I detect "shift+enter" and generate a new line in Textarea?

Easy & Elegant solution:

First, pressing Enter inside a textarea does not submit the form unless you have script to make it do that. That's the behaviour the user expects and I'd recommend against changing it. However, if you must do this, the easiest approach would be to find the script that is making Enter submit the form and change it. The code will have something like

if (evt.keyCode == 13) {
    form.submit();
}

... and you could just change it to

if (evt.keyCode == 13 && !evt.shiftKey) {
    form.submit();
}

On the other hand, if you don't have access to this code for some reason, you need to do the following to make it work in all major browsers even if the caret is not at the end of the text:

jsFiddle: http://jsfiddle.net/zd3gA/1/

Code:

function pasteIntoInput(el, text) {
    el.focus();
    if (typeof el.selectionStart == "number"
            && typeof el.selectionEnd == "number") {
        var val = el.value;
        var selStart = el.selectionStart;
        el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
        el.selectionEnd = el.selectionStart = selStart + text.length;
    } else if (typeof document.selection != "undefined") {
        var textRange = document.selection.createRange();
        textRange.text = text;
        textRange.collapse(false);
        textRange.select();
    }
}

function handleEnter(evt) {
    if (evt.keyCode == 13 && evt.shiftKey) {
        if (evt.type == "keypress") {
            pasteIntoInput(this, "\n");
        }
        evt.preventDefault();
    }
}

// Handle both keydown and keypress for Opera, which only allows default
// key action to be suppressed in keypress
$("#your_textarea_id").keydown(handleEnter).keypress(handleEnter);

Get product id and product type in magento?

you can get all product information from following code

$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);


    $product_data["id"]=$_product->getId();
    $product_data["name"]=$_product->getName();
    $product_data["short_description"]=$_product->getShortDescription();
    $product_data["description"]=$_product->getDescription();
    $product_data["price"]=$_product->getPrice();
    $product_data["special price"]=$_product->getFinalPrice();
    $product_data["image"]=$_product->getThumbnailUrl();
    $product_data["model"]=$_product->getSku();
    $product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value


    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    $product_data["rating"]=($summaryData['rating_summary']*5)/100;

    $product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');

    if($_product->isSalable() ==1)
        $product_data["in_stock"]=1;
    else
        $product_data["in_stock"]=0;


    echo "<pre>";
    print_r($product_data);
    //echo "</pre>";

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

What is the difference between baud rate and bit rate?

Bit rate is a measure of the number of data bits (that's 0's and 1's) transmitted in one second. A figure of 2400 bits per second means 2400 zeros or ones can be transmitted in one second, hence the abbreviation 'bps'.

Baud rate by definition means the number of times a signal in a communications channel changes state. For example, a 2400 baud rate means that the channel can change states up to 2400 times per second. When I say 'change state' I mean that it can change from 0 to 1 up to 2400 times per second. If you think about this, it's pretty much similar to the bit rate, which in the above example was 2400 bps.

Whether you can transmit 2400 zeros or ones in one second (bit rate), or change the state of a digital signal up to 2400 times per second (baud rate), it the same thing.

How to add title to subplots in Matplotlib?

In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.

  1. The catch is you can define dynamic axes(ax) as in Line 1 of code and you can set its title inside a loop.
  2. The rows of 2D array is length (len) of axis(ax)
  3. Each row has 2 items i.e. It is list within a list (Point No.2)
  4. set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I got similar error (org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15) while using aspectj 1.8.13. Solution was to align all compilation into jdk 8 and being careful not to put aspectj library's (1.6.13 for instance) other versions to buildpath/classpath.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

How do I get a value of datetime.today() in Python that is "timezone aware"?

Especially for non-UTC timezones:

The only timezone that has its own method is timezone.utc, but you can fudge a timezone with any UTC offset if you need to by using timedelta & timezone, and forcing it using .replace.

In [1]: from datetime import datetime, timezone, timedelta

In [2]: def force_timezone(dt, utc_offset=0):
   ...:     return dt.replace(tzinfo=timezone(timedelta(hours=utc_offset)))
   ...:

In [3]: dt = datetime(2011,8,15,8,15,12,0)

In [4]: str(dt)
Out[4]: '2011-08-15 08:15:12'

In [5]: str(force_timezone(dt, -8))
Out[5]: '2011-08-15 08:15:12-08:00'

Using timezone(timedelta(hours=n)) as the time zone is the real silver bullet here, and it has lots of other useful applications.

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

Why I get 411 Length required error?

I had the same error when I imported web requests from fiddler captured sessions to Visual Studio webtests. Some POST requests did not have a StringHttpBody tag. I added an empty one to them and the error was gone. Add this after the Headers tag:

    <StringHttpBody ContentType="" InsertByteOrderMark="False">
  </StringHttpBody>

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

How to use awk sort by column 3

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

convert epoch time to date

EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(1318386508000L);
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        String formatted = format.format(date);
        System.out.println(formatted);
        format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        formatted = format.format(date);
        System.out.println(formatted);
    }
}

Output:

12/10/2011 02:28:28
12/10/2011 13:28:28

I would also suggest you start using Joda Time which is simply a much nicer date/time API...

EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

How to increase editor font size?

You can try to search in preferences (android studio IDE > preferences). In aptana studio it works like this making smaller: CMD and -, use CMD shift and =. Works?

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

Change URL parameters

you can do it via normal JS also

var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1]; 
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
    if(tempArray[i].indexOf("rows") == -1){
            newAdditionalURL += temp+tempArray[i];
                temp = "&";
            }
        }
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

When do I have to use interfaces instead of abstract classes?

Interfaces and abstracted classes seem very similar, however, there are important differences between them.

Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.

Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:

public abstract class Car{
    private String make;
    private String model

    protected Car() { }  // Default constructor

    protect Car(String make, String model){
        //Assign values to 
    }

    public abstract void howToStart();
}

Then with the Honda class we would have:

public class Honda extends implements Engine {

    public Honda() { }  // Default constructor

    public Honda(String make, String model){
        //Assign values
    }

    @Override
    public static void howToStart(){
        // Code on how to start
    }

}

Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine.

For the engine interface we could create:

public interface Engine {
    public void startup();
}

The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup(); method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:

public class Honda extends implements Engine, Transmission, List<Parts>

Hopefully this helps.

close fancy box from function from within open 'fancybox'

After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close() and I made it an inline script on an onClick. Going to check if i can call it from the parent

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

As originally suggested in a comment by GeoMac and documented on NuGet's docs the following worked for me when none of the other answers worked:

Tools / NuGet Package Manager / Package Manager Console

Update-Package -ProjectName MyProjectName -reinstall

Android: Cancel Async Task

Most of the time that I use AsyncTask my business logic is on a separated business class instead of being on the UI. In that case, I couldn't have a loop at doInBackground(). An example would be a synchronization process that consumes services and persist data one after another.

I end up handing on my task to the business object so it can handle cancelation. My setup is like this:

public abstract class MyActivity extends Activity {

    private Task mTask;
    private Business mBusiness;

    public void startTask() {
        if (mTask != null) {
            mTask.cancel(true);
        }
        mTask = new mTask();
        mTask.execute();
    }
}

protected class Task extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected void onCancelled() {
        super.onCancelled();

        mTask.cancel(true);

        // ask if user wants to try again
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return mBusiness.synchronize(this);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        mTask = null;

        if (result) {
            // done!
        }
        else {
            // ask if user wants to try again
        }
    }
}

public class Business {
    public boolean synchronize(AsyncTask<?, ?, ?> task) {
        boolean response = false;
        response = loadStuff(task);

        if (response)
            response = loadMoreStuff(task);

        return response;
    }

    private boolean loadStuff(AsyncTask<?, ?, ?> task) {
        if (task != null && task.isCancelled()) return false;

        // load stuff

        return true;
    }
}

How to use a App.config file in WPF applications?

You have to reference System.Configuration via explorer (not only append using System.Configuration). Then you can write:

string xmlDataDirectory = 
    System.Configuration.ConfigurationManager.AppSettings.Get("xmlDataDirectory");

Tested with VS2010 (thanks to www.developpez.net). Hope this helps.

What do these three dots in React do?

Is usually called spread operator, it is use to expand wherever is required

example

const SomeStyle = {
   margin:10,
   background:#somehexa
}

you can use this where ever you requires it more about spread operator Spread syntax.

SSL Error: CERT_UNTRUSTED while using npm command

npm ERR! node -v v0.8.0
npm ERR! npm -v 1.1.32

Update your node.js installation.The following commands should do it (from here):

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Edit: okay, if you really have a good reason to run an ancient version of the software, npm set ca null will fix the issue. It happened, because built-in npm certificate has expired over the years.

Conditional statement in a one line lambda function in python?

Yes, you can use the shorthand syntax for if statements.

rate = lambda(t): (200 * exp(-t)) if t > 200 else (400 * exp(-t))

Note that you don't use explicit return statements inlambdas either.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

Create folder with batch but only if it doesn't already exist

i created this for my script I use in my work for eyebeam.

:CREATES A CHECK VARIABLE

set lookup=0

:CHECKS IF THE FOLDER ALREADY EXIST"

IF EXIST "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\" (set lookup=1)

:IF CHECK is still 0 which means does not exist. It creates the folder

IF %lookup%==0 START "" mkdir "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\"

IIS Express Windows Authentication

Building upon the answer from booij boy, check if you checked the "windows authentication" feature in Control Panel -> Programs -> Turn windows features on or of -> Internet Information Services -> World Wide Web Services -> Security

Also, there seems to be a big difference when using firefox or internet explorer. After enabeling the "windows authentication" it works for me but only in IE.

Iterate over the lines of a string

Here are three possibilities:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

Measuring gives:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

But the split-based approach still rules.

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

at least, it's a bit less verbose. The need to strip trailing \ns unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('\n'), stri)

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

Extract digits from string - StringUtils Java

I've created a JUnit Test class(as a additional knowledge/info) for the same issue. Hope you'll be finding this helpful.

   public class StringHelper {
    //Separate words from String which has gigits
        public String drawDigitsFromString(String strValue){
            String str = strValue.trim();
            String digits="";
            for (int i = 0; i < str.length(); i++) {
                char chrs = str.charAt(i);              
                if (Character.isDigit(chrs))
                    digits = digits+chrs;
            }
            return digits;
        }
    }

And JUnit Test case is:

 public class StringHelperTest {
    StringHelper helper;

        @Before
        public void before(){
            helper = new StringHelper();
        }

        @Test
    public void testDrawDigitsFromString(){
        assertEquals("187111", helper.drawDigitsFromString("TCS187TCS111"));
    }
 }

SHOW PROCESSLIST in MySQL command: sleep

It's not a query waiting for connection; it's a connection pointer waiting for the timeout to terminate.

It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does.

The really worst case: It's using one connection of your pool; If you would connect multiple times via console client and just close the client without closing the connection, you could use up all your connections and have to wait for the timeout to be able to connect again... but this is highly unlikely :-)

See MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"? and https://dba.stackexchange.com/questions/1558/how-long-is-too-long-for-mysql-connections-to-sleep for more information.

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

How do you move a file?

Since you're using Tortoise you may want to check out this link on LosTechies. It should be almost exactly what you are looking for.

http://www.lostechies.com/blogs/joshua_lockwood/archive/2007/09/12/subversion-tip-of-the-day-moving-files.aspx

Difference between Encapsulation and Abstraction

Yes, it is true that Abstraction and Encapsulation are about hiding.

  • Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)

  • Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.

Replace Line Breaks in a String C#

Use the .Replace() method

Line.Replace("\n", "whatever you want to replace with");

SSL Proxy/Charles and Android trouble

Thanks for @bkurzius's answer and this update is for Charles 3.10+. (The reason is here)

  1. Open Charles
  2. Go to Proxy > SSL Proxy Settings...
  3. Check “Enable SSL Proxying”
  4. Select “Add location” and enter the host name and port (if needed)
  5. Click ok and make sure the option is checked
  6. Go to Help > SSL Proxying > Install Charles Root Certificate on a Mobile Device or Remote Browser..., and just follow the instruction. (use the Android's browser to download and install the certificate.)
  7. In “Name the certificate” enter whatever you want
  8. Click OK and you should get a message that the certificate was installed

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

Display a jpg image on a JPanel

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

How to make a div 100% height of the browser window

You can use display: flex and height: 100vh

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0px;_x000D_
}_x000D_
body {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.left, .right {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
.left {_x000D_
  background: orange;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  background: cyan;_x000D_
}
_x000D_
<div class="left">left</div>_x000D_
<div class="right">right</div>
_x000D_
_x000D_
_x000D_

What's wrong with using == to compare floats in Java?

The following automatically uses the best precision:

/**
 * Compare to floats for (almost) equality. Will check whether they are
 * at most 5 ULP apart.
 */
public static boolean isFloatingEqual(float v1, float v2) {
    if (v1 == v2)
        return true;
    float absoluteDifference = Math.abs(v1 - v2);
    float maxUlp = Math.max(Math.ulp(v1), Math.ulp(v2));
    return absoluteDifference < 5 * maxUlp;
}

Of course, you might choose more or less than 5 ULPs (‘unit in the last place’).

If you’re into the Apache Commons library, the Precision class has compareTo() and equals() with both epsilon and ULP.

How can I specify a local gem in my Gemfile?

I believe you can do this:

gem "foo", path: "/path/to/foo"

Position: absolute and parent height?

This is another late answer but i figured out a fairly simple way of placing the "bar" text in between the four squares. Here are the changes i made; In the bar section i wrapped the "bar" text within a center and div tags.

<header><center><div class="bar">bar</div></center></header>

And in the CSS section i created a "bar" class which is used in the div tag above. After adding this the bar text was centered between the four colored blocks.

.bar{
    position: relative;
}

Can I set an unlimited length for maxJsonLength in web.config?

 JsonResult result = Json(r);
 result.MaxJsonLength = Int32.MaxValue;
 result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 return result;

Python non-greedy regexes

To start with, I do not suggest using "*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the + sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the {x, y} syntax to specifically specify the desired length.

However, if you really do need non-greedy repetition, I suggest consulting the all-powerful ?. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible.

That being said, I would be very careful with the ? as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify ((1) (note the lack of a second rparen) as a match.