Programs & Examples On #Rake task

Write lines of text to a file in R

tidyverse edition with pipe and write_lines() from readr

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

CSV API for Java

The CSV format sounds easy enough for StringTokenizer but it can become more complicated. Here in Germany a semicolon is used as a delimiter and cells containing delimiters need to be escaped. You're not going to handle that easily with StringTokenizer.

I would go for http://sourceforge.net/projects/javacsv

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

Getting Date or Time only from a DateTime Object

var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

You'll get this error if you try to use a Git command when your current working directory is not within a Git repository. That is because, by default, Git will look for a .git repository directory (inside of the project root?), as pointed out by my answer to "Git won't show log unless I am in the project directory":

According to the official Linux Kernel Git documentation, GIT_DIR is [an environment variable] set to look for a .git directory (in the current working directory?) by default:

If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository.

You'll either need to cd into the repository/working copy, or you didn't initialize or clone a repository in the first place, in which case you need to initialize a repo in the directory where you want to place the repo:

git init

or clone a repository

git clone <remote-url>
cd <repository>

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

Selecting only numeric columns from a data frame

The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:

install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset) 
X2 <- split$X.quali (Gives categorical columns in the dataset)

How do I align a number like this in C?

Looking this up in my handy Harbison & Steele....

Determine the maximum width of fields.

int max_width, value_to_print;
max_width = 8;
value_to_print = 1000;
printf("%*d\n", max_width, value_to_print);

Bear in mind that max_width must be of type int to work with the asterisk, and you'll have to calculate it based on how much space you're going to want to have. In your case, you'll have to calculate the maximum width of the largest number, and add 4.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Best way to get whole number part of a Decimal number

   Public Function getWholeNumber(number As Decimal) As Integer
    Dim round = Math.Round(number, 0)
    If round > number Then
        Return round - 1
    Else
        Return round
    End If
End Function

Split / Explode a column of dictionaries into separate columns with pandas

my_df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['my_col'])

.. would have parsed the dict properly (putting each dict key into a separate df column, and key values into df rows), so the dicts would not get squashed into a single column in the first place.

how to get date of yesterday using php?

Step 1

We need set format data in function date(): Function date() returns a string formatted according to the givenformat string using the given integer timestamp or the current time ifno timestamp is given. In other words, timestampis optional anddefaults to the value of time().

<?php
echo date("F j, Y");
?>

result: March 30, 2010

Step 2

For "yesterday" date use php function mktime(): Function mktime() returns the Unix timestamp corresponding to thearguments given. This timestamp is a long integer containing the numberof seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and thetime specified. Arguments may be left out in order from right to left; any argumentsthus omitted will be set to the current value according to the localdate and time.

<?php
echo mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
?>

result: 1269820800

Step 3

Now merge all and look at this:

<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>

result: March 29, 2010

Operating similarly, it is possible to receive time hour back.

<?php
$yesterday = date("H:i:s",mktime(date("H"), 0, 0, date("m"),date("d"), date("Y")));
echo $yesterday;
?>

result: 20:00:00

or 7 days ago:

<?php
$week = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-7,date("Y")));
echo $week;
?>

result: 2010-03-23

How to get all files under a specific directory in MATLAB?

You can use regexp or strcmp to eliminate . and .. Or you could use the isdir field if you only want files in the directory, not folders.

list=dir(pwd);  %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
filenames={list(isfile).name}; %create cell array of file names

or combine the last two lines:

filenames={list(~[list.isdir]).name};

For a list of folders in the directory excluding . and ..

dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));

From this point, you should be able to throw the code in a nested for loop, and continue searching each subfolder until your dirnames returns an empty cell for each subdirectory.

How to add display:inline-block in a jQuery show() function?

<style>
.demo-ele{display:inline-block}
</style>

<div class="demo-ele" style="display:none">...</div>

<script>
$(".demo-ele").show(1000);//hide first, show with inline-block
<script>

What is the simplest way to SSH using Python?

Have a look at spurplus, a wrapper around spur and paramiko that we developed to manage remote machines and perform file operations.

Spurplus provides a check_output() function out-of-the-box:

import spurplus
with spurplus.connect_with_retries(
        hostname='some-machine.example.com', username='devop') as shell:
     out = shell.check_output(['/path/to/the/command', '--some_argument']) 
     print(out)

What does "yield break;" do in C#?

The yield break statement causes the enumeration to stop. In effect, yield break completes the enumeration without returning any additional items.

Consider that there are actually two ways that an iterator method could stop iterating. In one case, the logic of the method could naturally exit the method after returning all the items. Here is an example:

IEnumerable<uint> FindPrimes(uint startAt, uint maxCount)
{
    for (var i = 0UL; i < maxCount; i++)
    {
        startAt = NextPrime(startAt);
        yield return startAt;
    }

    Debug.WriteLine("All the primes were found.");
}

In the above example, the iterator method will naturally stop executing once maxCount primes have been found.

The yield break statement is another way for the iterator to cease enumerating. It is a way to break out of the enumeration early. Here is the same method as above. This time, the method has a limit on the amount of time that the method can execute.

IEnumerable<uint> FindPrimes(uint startAt, uint maxCount, int maxMinutes)
{
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (var i = 0UL; i < maxCount; i++)
    {
        startAt = NextPrime(startAt);
        yield return startAt;

        if (sw.Elapsed.TotalMinutes > maxMinutes)
            yield break;
    }

    Debug.WriteLine("All the primes were found.");
}

Notice the call to yield break. In effect, it is exiting the enumeration early.

Notice too that the yield break works differently than just a plain break. In the above example, yield break exits the method without making the call to Debug.WriteLine(..).

Are there any log file about Windows Services Status?

Take a look at the System log in Windows EventViewer (eventvwr from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,

Event Type: Information
Event Source:   Service Control Manager
Event Category: None
Event ID:   7036
Date:       7/1/2009
Time:       12:09:43 PM
User:       N/A
Computer:   MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Upgrading Node.js to latest version

If you are using Linux .. Just do the following steps sudo -i sudo apt install curl curl -sL https://deb.nodesource.com/setup_10.x | sudo bash - sudo apt-get install -y nodejs you should have now the latest version

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

Regular expression for address field validation

Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.

Related:

Best method for reading newline delimited files and discarding the newlines?

Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.

lines = (line.rstrip('\n') for line in open(filename))

However, you'll most likely want to use this to get rid of trailing whitespaces too.

lines = (line.rstrip() for line in open(filename))

href around input type submit

Place the link location in the action="" of a wrapping form tag.

Your first link would be:

<form action="1.html">
    <input type="submit" class="button_active" value="1">
</form>

Check if a variable exists in a list in Bash

how about

echo $list | grep -w -q $x

you could either check the output or $? of above line to make the decision.

grep -w checks on whole word patterns. Adding -q prevents echoing the list.

Margin between items in recycler view Android

  1. Find the attribute card_view:cardUseCompatPadding="true" in cards_layout.xml and delete it. Start app and you will find there is no margin between each cardview item.

  2. Add margin attributes you like. Ex:

    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp" 
    

How to check if a stored procedure exists before creating it

In addition to the answer from @Geoff I've created a simple tool which generates a SQL-file which statements for Stored Procedures, Views, Functions and Triggers.

See MyDbUtils @ CodePlex. enter image description here

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

Dockerfile copy keep subdirectory structure

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

Exception: Can't bind to 'ngFor' since it isn't a known native property

I missed let in front of talk:

<div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead.

<div *ngFor="#talk of talks"> now becomes <div *ngFor="let talk of talks">

Original answer:

I missed # in front of talk:

<div *ngFor="#talk of talks">

It is so easy to forget that #. I wish the Angular exception error message would instead say:
you forgot that # again.

How to access the php.ini file in godaddy shared hosting linux

I found a guide to reload the php5.ini file or load a new one right away. You will need to access your Godaddy hosting panel where you will find the option "system process" do a restart there and it will load the php5.ini or php.ini file right away.

2 external guides to assist you:

http://support.godaddy.com/help/article/5980/managing-system-processes-on-linux-hosting-accounts

http://www.studio-owens.com/blog/GoDaddy-and-Your-php-ini-File.htm

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Error CS1705: "which has a higher version than referenced assembly"

3 ideas for you to try:

  1. Make sure that all your dlls are compiled against the same version of Common.
  2. Check that you have project references in your solution instead of file references.
  3. Use binding redirections in your web.config. (Originally linked version at wayback machine)

Multiple Errors Installing Visual Studio 2015 Community Edition

Okay, so if you're on the same boat as me and found that none of these solutions helped you, you most likely have a problem where NuGet (or any of those packages) is failing to install from the VSIX program due it calling a method that doesn't exist on your computer (not sure what .dll it's referencing), so try this out from the following post:

  • Delete all instances of Visual Studio 2015- this includes all registry values.
  • Install a version of Visual Studio older than Update 1 (RTM version.); this is available here.
  • If you still get an error, try repairing just the Visual Studio 2015 program. This is what ultimately fixed it for me.

Hope this helped someone out. It's really frustrating that the installer's log file doesn't help at all. I had to look at the log file specific to NuGet, and that's where I noticed the error:

The installation was unable to install the extension to all the selected products. For more information, click on the install log link at the bottom of the dialog.

Method not found: 'System.Collections.Generic.IEnumerable`1 System.Security.Cryptography.X509Certificates.X509ChainStatus Microsoft.VisualStudio.ExtensionManager.IInstallableExtension.get_InvalidCertificateInformation()'.

How to parse JSON using Node.js?

Using JSON for your configuration with Node.js? Read this and get your configuration skills over 9000...

Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!

Proper applications come in 3+ layers of configuration:

  1. Server/Container config
  2. Application config
  3. (optional) Tenant/Community/Organization config
  4. User config

Most developers treat their server and app config as if it can change. It can't. You can layer changes from higher layers on top of each other, but you're modifying base requirements. Some things need to exist! Make your config act like it's immutable, because some of it basically is, just like your source code.

Failing to see that lots of your stuff isn't going to change after startup leads to anti-patterns like littering your config loading with try/catch blocks, and pretending you can continue without your properly setup application. You can't. If you can, that belongs in the community/user config layer, not the server/app config layer. You're just doing it wrong. The optional stuff should be layered on top when the application finishes it's bootstrap.

Stop banging your head against the wall: Your config should be ultra simple.

Take a look at how easy it is to setup something as complex as a protocol-agnostic and datasource-agnostic service framework using a simple json config file and simple app.js file...

container-config.js...

{
    "service": {
        "type"  : "http",
        "name"  : "login",
        "port"  : 8085
    },
    "data": {
        "type"  : "mysql",
        "host"  : "localhost",
        "user"  : "notRoot",
        "pass"  : "oober1337",
        "name"  : "connect"
    }
}

index.js... (the engine that powers everything)

var config      = require('./container-config.json');       // Get our service configuration.
var data        = require(config.data.type);            // Load our data source plugin ('npm install mysql' for mysql).
var service     = require(config.service.type);         // Load our service plugin ('http' is built-in to node).
var processor   = require('./app.js');                  // Load our processor (the code you write).

var connection  = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server      = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });

app.js... (the code that powers your protocol-agnostic and data-source agnostic service)

module.exports = function(request, response){
    response.end('Responding to: ' + request.url);
}

Using this pattern, you can now load community and user config stuff on top of your booted app, dev ops is ready to shove your work into a container and scale it. You're read for multitenant. Userland is isolated. You can now separate the concerns of which service protocol you're using, which database type you're using, and just focus on writing good code.

Because you're using layers, you can rely on a single source of truth for everything, at any time (the layered config object), and avoid error checks at every step, worrying about "oh crap, how am I going to make this work without proper config?!?".

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

jQuery check if Cookie exists, if not create it

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

jQuery - Get Width of Element when Not Visible (Display: None)

jQuery(".megamenu li.level0 .dropdown-container .sub-column ul .level1").on("mouseover", function () {
    var sum = 0;
    jQuery(this).find('ul li.level2').each(function(){
    sum -= jQuery(this).height();
    jQuery(this).parent('ul').css('margin-top', sum / 1.8);
    console.log(sum);
    });
});

On hover we can calculate the list item height.

android layout with visibility GONE

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try this piece of code..For me this code worked..

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

What does the Ellipsis object do?

Its intended use shouldn't be only for these 3rd party modules. It isn't mentioned properly in the Python documentation (or maybe I just couldn't find that) but the ellipsis ... is actually used in CPython in at least one place.

It is used for representing infinite data structures in Python. I came upon this notation while playing around with lists.

See this question for more info.

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .

you can define it like this:

new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };

and here is a more realistic example:

new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}

and finally in:

MVC 1

<%= Html.TextBox("test", new { style="width:50px" }) %> 

MVC 2

<%= Html.TextBox("test", null, new { style="width:50px" }) %> 

MVC 3

@Html.TextBox("test", null, new { style="width:50px" })

What is the best method to merge two PHP objects?

This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Once an Object is in array format you can use array_merge and convert back to Object if you need to.

abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}

Procedural way

function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}

All credit goes to: Jason Oakley

How to find controls in a repeater header or footer

This is in VB.NET, just translate to C# if you need it:

<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
    Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
                   Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
    Return ctrl
End Function

And use it easy:

Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text

Try to make it work with footer, and items controls too =)

How do I get the current mouse screen coordinates in WPF?

If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).

var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());

public System.Windows.Point GetMousePosition()
{
    var point = Forms.Control.MousePosition;
    return new Point(point.X, point.Y);
}

How to detect a docker daemon port

Reference docs of docker: https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"

2) Configuring at /etc/docker/daemon.json:

{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}

If the docker default socket is not configured Docker will wait for infinite period.i.e

Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:

# netstat -tunlp | grep -i 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      31661/dockerd 

Applicable for Docker Version 17.04, may vary with different versions of docker.

try/catch blocks with async/await

I'd like to do this way :)

const sthError = () => Promise.reject('sth error');

const test = opts => {
  return (async () => {

    // do sth
    await sthError();
    return 'ok';

  })().catch(err => {
    console.error(err); // error will be catched there 
  });
};

test().then(ret => {
  console.log(ret);
});

It's similar to handling error with co

const test = opts => {
  return co(function*() {

    // do sth
    yield sthError();
    return 'ok';

  }).catch(err => {
    console.error(err);
  });
};

jQuery pass more parameters into callback

It's actually easier than everyone's making it sound... especially if you use the $.ajax({}) base syntax vs. one of the helper functions.

Just pass in the key: value pair like you would on any object, when you setup your ajax request... (because $(this) hasn't changed context yet, it's still the trigger for the bind call above)

<script type="text/javascript">
$(".qty input").bind("keypress change", function() {
    $.ajax({
        url: "/order_items/change/"+$(this).attr("data-order-item-id")+"/qty:"+$(this).val()+"/returnas.json",
        type: "POST",
        dataType: "json",
        qty_input: $(this),
        anything_else_i_want_to_pass_in: "foo",
        success: function(json_data, textStatus, jqXHR) {
            /* here is the input, which triggered this AJAX request */
            console.log(this.qty_input);
            /* here is any other parameter you set when initializing the ajax method */
            console.log(this.anything_else_i_want_to_pass_in);
        }
    });
});
</script>

One of the reasons this is better than setting the var, is that the var is global and as such, overwritable... if you have 2 things which can trigger ajax calls, you could in theory trigger them faster than ajax call responds, and you'd have the value for the second call passed into the first. Using this method, above, that wouldn't happen (and it's pretty simple to use too).

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

Bootstrap: how do I change the width of the container?

You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.

Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.

In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.

// Container sizes
// --------------------------------------------------

// Small screen / tablet
@container-tablet:            ((720px + @grid-gutter-width));

// Medium screen / desktop
@container-desktop:           ((940px + @grid-gutter-width));

// Large screen / wide desktop
@container-lg-desktop:        ((1020px + @grid-gutter-width));

Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.

Different ways of adding to Dictionary

The first version will add a new KeyValuePair to the dictionary, throwing if key is already in the dictionary. The second, using the indexer, will add a new pair if the key doesn't exist, but overwrite the value of the key if it already exists in the dictionary.

IDictionary<string, string> strings = new Dictionary<string, string>();

strings["foo"] = "bar";          //strings["foo"] == "bar"
strings["foo"] = string.Empty;   //strings["foo"] == string.empty
strings.Add("foo", "bar");       //throws     

How do I iterate through children elements of a div using jQuery?

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output
});

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

How to delete mysql database through shell command

You can remove database directly as:

$ mysqladmin -h [host] -u [user] -p drop [database_name]

[Enter Password]

Do you really want to drop the 'hairfree' database [y/N]: y

pandas groupby sort descending order

Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.

grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)

Shuffle an array with python, randomize array item order with python

Alternative way to do this using sklearn

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

Output:

[2, 1, 3]
['two', 'one', 'three']

Advantage: You can random multiple arrays simultaneously without disrupting the mapping. And 'random_state' can control the shuffling for reproducible behavior.

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

Find and replace with a newline in Visual Studio Code

In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.

Image of multiline search in local search

If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.

Image of multiline search in global search

If you want to search for multilines by the character literal, remember to check the rightmost regex icon.

Image of regex mode in search replace


In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.

Mercurial — revert back to old version and continue from there

I just encountered a case of needing to revert just one file to previous revision, right after I had done commit and push. Shorthand syntax for specifying these revisions isn't covered by the other answers, so here's command to do that

hg revert path/to/file -r-2

That -2 will revert to the version before last commit, using -1 would just revert current uncommitted changes.

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

Convert string into Date type on Python

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

JavaScript - get the first day of the week from current date

a more generalized version of this... this will give you any day in the current week based on what day you specify.

_x000D_
_x000D_
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
  return new Date(d.setDate(diff));
}

var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);

console.log(monday);
console.log(friday);
_x000D_
_x000D_
_x000D_

"SDK Platform Tools component is missing!"

The downloaded sdk software does not contain sdk platform tools.

For this, using cmd go to "C:\Program Files\Android\android-sdk\tools" directory and then type the following command to download those missing tools:

android.bat update sdk --no-ui 

Then type y to accept all the licenses in cmd. Downloading will start in cmd itself.

Entity Framework Refresh context?

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Multiple distinct pages in one HTML file

have all the pages in distinct div areas

<div style="" id="page1">
First Page Contents
</div>

<div style="display:none" id="page2">
Second Page Contents
</div>

then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like /pages/page1.html)

var $prehashval = "";
function loop()
{
    if (location.hash.slice(1)!=$prehashval)
        hashChanged();

    $prehashval = location.hash.slice(1);
    setTimeout("loop()", 100);
}
function hashChanged()
{
    var $output;
    switch (location.hash.slice(1))
    {
        case "page1":
            document.getElementById('page1').style.display = "";
            document.getElementById('page2').style.display = "none";
            break;
        case "page2":
            document.getElementById('page1').style.display = "none";
            document.getElementById('page2').style.display = "";
            break;
        default:
            $output = location.hash.slice(1);
    }
}
loop();

Delimiters in MySQL

Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.

Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.

Example:

DELIMITER $$
/* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
DROP PROCEDURE my_procedure$$

/* Now start the procedure code */
CREATE PROCEDURE my_procedure ()
BEGIN    
  /* Inside the procedure, individual statements terminate with ; */
  CREATE TABLE tablea (
     col1 INT,
     col2 INT
  );

  INSERT INTO tablea
    SELECT * FROM table1;

  CREATE TABLE tableb (
     col1 INT,
     col2 INT
  );
  INSERT INTO tableb
    SELECT * FROM table2;
  
/* whole procedure ends with the custom delimiter */
END$$

/* Finally, reset the delimiter to the default ; */
DELIMITER ;

Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:

$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$result = $mysqli->query('DELIMITER $$');
echo $mysqli->error;

Errors with:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

Why AVD Manager options are not showing in Android Studio

I found it from the icon. Please see the device icon.

enter image description here

How to get files in a relative path in C#

Pretty straight forward, use relative path

string[] offerFiles = Directory.GetFiles(Server.MapPath("~/offers"), "*.csv");

Vue-router redirect on page not found (404)

This answer may come a bit late but I have found an acceptable solution. My approach is a bit similar to @Mani one but I think mine is a bit more easy to understand.

Putting it into global hook and into the component itself are not ideal, global hook checks every request so you will need to write a lot of conditions to check if it should be 404 and window.location.href in the component creation is too late as the request has gone into the component already and then you take it out.

What I did is to have a dedicated url for 404 pages and have a path * that for everything that not found.

{ path: '/:locale/404', name: 'notFound', component: () => import('pages/Error404.vue') },
{ path: '/:locale/*', 
  beforeEnter (to) {
    window.location = `/${to.params.locale}/404`
  }
}

You can ignore the :locale as my site is using i18n so that I can make sure the 404 page is using the right language.

On the side note, I want to make sure my 404 page is returning httpheader 404 status code instead of 200 when page is not found. The solution above would just send you to a 404 page but you are still getting 200 status code. To do this, I have my nginx rule to return 404 status code on location /:locale/404

server {
    listen                      80;
    server_name                 localhost;

    error_page  404 /index.html;
    location ~ ^/.*/404$ {
      root   /usr/share/nginx/html;
      internal;
    }

    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
      rewrite ^(.+)$ /index.html last;
    }

    location = /50x.html {
      root   /usr/share/nginx/html;
    }
}

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

creating custom tableview cells in swift

Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).

Check if checkbox is checked with jQuery

use code below

<script>

$(document).ready(function () {
  $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}

function ShowMailSection() {
  if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
      $("[id$='SecEmail']").removeClass("Hide");
  }
</script>

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

The latest Windows SDK, as mentioned above, in addition to the "Microsoft Visual Studio 2010 Shell (Integrated) Redistributable Package" for Microsoft.WebApplication.targets and "Microsoft Visual Studio Team System 2008 Database Edition GDR R2" for Microsoft.Data.Schema.SqlTasks.targets should alleviate the need to install Visual Studio 2010. However, installing VS 2010 maybe actually be less overall to download and less work in the end.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

in my case it was just an intermittent issues it seems, didn't work for a few tries, then looked at https://registry.npmjs.org (webpage worked fine), tried again, tried again and then it worked.

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

What is the difference between public, private, and protected?

The mentioned keywords are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

Android SDK Setup under Windows 7 Pro 64 bit

I initially had this problem and I believe it was because I did not have the 64 bit version of Eclipse.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.

Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).

I would suggest two workarounds : Either you make your own class that implements actionlistenner and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.

Or (and this is probably the best solution) just qualify a copy of the variable final to access it in the inner scope as the error suggests to make it a constant:

This would suit your case since you are not modifying the value of the variable.

php exec command (or similar) to not wait for result

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');

MySQL: How to reset or change the MySQL root password?

In my case this option helped : https://stackoverflow.com/a/49610152/13760371
Thank you, Rahul.

except for the following moment, when I try entered command:

UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%';

the console issued a warning:

1681 'password' is deprecated and will be removed in a future release

cured with this command:

UPDATE mysql.user SET authentication_string=CONCAT('*', UPPER(SHA1(UNHEX(SHA1('NEWPASSWORD'))))), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';

MySQL version 5.7.X

My variant:

1. > sudo service mysql stop
2. > sudo mkdir /var/run/mysqld
3. > sudo chown mysql: /var/run/mysqld
4. > sudo mysqld_safe --skip-grant-tables --skip-networking &
5. > mysql -uroot mysql
6. > UPDATE mysql.user SET authentication_string=CONCAT('*', UPPER(SHA1(UNHEX(SHA1('NEWPASSWORD'))))), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';
7. > \q;
8. > sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
9. > sudo service mysql start

Use grep --exclude/--include syntax to not grep through certain files

Use the shell globbing syntax:

grep pattern -r --include=\*.{cpp,h} rootdir

The syntax for --exclude is identical.

Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as --include="*.{cpp,h}", would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like grep pattern -r --include=foo.cpp --include=bar.h rootdir, which would only search files named foo.cpp and bar.h, which is quite likely not what you wanted.

Remove all git files from a directory?

You can use git-archive, for example:

git archive master | bzip2 > project.tar.bz2

Where master is the desired branch.

Regular Expressions and negating a whole character group

Just search for "ab" in the string then negate the result:

!/ab/.test("bamboo"); // true
!/ab/.test("baobab"); // false

It seems easier and should be faster too.

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

How to set alignment center in TextBox in ASP.NET?

Add the css styling text-align: center to the control.

Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:

<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>

Create multiple threads and wait all of them to complete

Most proposed answers don't take into account a time-out interval, which is very important to prevent a possible deadlock. Next is my sample code. (Note that I'm primarily a Win32 developer, and that's how I'd do it there.)

//'arrRunningThreads' = List<Thread>

//Wait for all threads
const int knmsMaxWait = 3 * 1000;           //3 sec timeout
int nmsBeginTicks = Environment.TickCount;
foreach(Thread thrd in arrRunningThreads)
{
    //See time left
    int nmsElapsed = Environment.TickCount - nmsBeginTicks;
    int nmsRemain = knmsMaxWait - nmsElapsed;
    if(nmsRemain < 0)
        nmsRemain = 0;

    //Then wait for thread to exit
    if(!thrd.Join(nmsRemain))
    {
        //It didn't exit in time, terminate it
        thrd.Abort();

        //Issue a debugger warning
        Debug.Assert(false, "Terminated thread");
    }
}

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

How to ignore files/directories in TFS for avoiding them to go to central source repository?

If you're using local workspaces (TFS 2012+) you can now use the .tfignore file to exclude local folders and files from being checked in.

If you add that file to source control you can ensure others on your team share the same exclusion settings.

Full details on MSDN - http://msdn.microsoft.com/en-us/library/ms245454.aspx#tfignore

For the lazy:

You can configure which kinds of files are ignored by placing a text file called .tfignore in the folder where you want rules to apply. The effects of the .tfignore file are recursive. However, you can create .tfignore files in sub-folders to override the effects of a .tfignore file in a parent folder.

The following rules apply to a .tfignore file:

  • # begins a comment line
  • The * and ? wildcards are supported.
  • A filespec is recursive unless prefixed by the \ character.
  • ! negates a filespec (files that match the pattern are not ignored)

Example file:

# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
# 
# Ignore .txt files in this folder 
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll

Java abstract interface

It is not necessary to declare the interface abstract.

Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.

No one is stopping you, though.

Other things you can explicitly state, but don't need to:

  • call super() on the first line of a constructor
  • extends Object
  • implement inherited interfaces

Is there other rules that applies with an abstract interface?

An interface is already "abstract". Applying that keyword again makes absolutely no difference.

ListView inside ScrollView is not scrolling on Android

list.setOnTouchListener(new OnTouchListener() {
    // Setting on Touch Listener for handling the touch inside ScrollView
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // Disallow the touch request for parent scroll on touch of child view
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }
});

How do I check if the mouse is over an element in jQuery?

You can test with jQuery if any child div has a certain class. Then by applying that class when you mouse over and out out a certain div, you can test whether your mouse is over it, even when you mouse over a different element on the page Much less code this way. I used this because I had spaces between divs in a pop-up, and I only wanted to close the pop up when I moved off of the pop up, not when I was moving my mouse over the spaces in the pop up. So I called a mouseover function on the content div (which the pop up was over), but it would only trigger the close function when I moused-over the content div, AND was outside the pop up!


$(".pop-up").mouseover(function(e)
    {
    $(this).addClass("over");
    });

$(".pop-up").mouseout(function(e)
    {
    $(this).removeClass("over");
    });


$("#mainContent").mouseover(function(e){
            if (!$(".expanded").hasClass("over")) {
            Drupal.dhtmlMenu.toggleMenu($(".expanded"));
        }
    });

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

How to call any method asynchronously in c#

If you use action.BeginInvoke(), you have to call EndInvoke somewhere - else the framework has to hold the result of the async call on the heap, resulting in a memory leak.

If you don't want to jump to C# 5 with the async/await keywords, you can just use the Task Parallels library in .Net 4. It's much, much nicer than using BeginInvoke/EndInvoke, and gives a clean way to fire-and-forget for async jobs:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();

I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.

Compiling php with curl, where is curl installed?

None of these will allow you to compile PHP with cURL enabled.

In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl. They generally are bundled in a separate development package.

Per example, to install libcurl in Ubuntu:

sudo apt-get install libcurl4-gnutls-dev

Or CentOS:

sudo yum install curl-devel

Then you can just do:

./configure --with-curl # other options...

If you compile cURL manually, you can specify the path to the files without the lib or include suffix. (e.g.: /usr/local if cURL headers are in /usr/local/include/curl).

Event detect when css property changed using Jquery

You can use attrchange jQuery plugin. The main function of the plugin is to bind a listener function on attribute change of HTML elements.

Code sample:

$("#myDiv").attrchange({
    trackValues: true, // set to true so that the event object is updated with old & new values
    callback: function(evnt) {
        if(evnt.attributeName == "display") { // which attribute you want to watch for changes
            if(evnt.newValue.search(/inline/i) == -1) {

                // your code to execute goes here...
            }
        }
    }
});

What is the default database path for MongoDB?

For a Windows machine start the mongod process by specifying the dbpath:

mongod --dbpath \mongodb\data

Reference: Manage mongod Processes

Can I add extension methods to an existing static class?

You can't add static methods to a type. You can only add (pseudo-)instance methods to an instance of a type.

The point of the this modifier is to tell the C# compiler to pass the instance on the left-side of the . as the first parameter of the static/extension method.

In the case of adding static methods to a type, there is no instance to pass for the first parameter.

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

Find out a Git branch creator

You can find out who created a branch in your local repository by

git reflog --format=full

Example output:

commit e1dd940
Reflog: HEAD@{0} (a <a@none>)
Reflog message: checkout: moving from master to b2
Author: b <b.none>
Commit: b <b.none>
(...)

But this is probably useless as typically on your local repository only you create branches.

The information is stored at ./.git/logs/refs/heads/branch. Example content:

0000000000000000000000000000000000000000 e1dd9409c4ba60c28ad9e7e8a4b4c5ed783ba69b a <a@none> 1438788420 +0200   branch: Created from HEAD

The last commit in this example was from user "b" while the branch "b2" was created by user "a". If you change your username you can verify that git reflog takes the information from the log and does not use the local user.

I don't know about any possibility to transmit that local log information to a central repository.

Detecting request type in PHP (GET, POST, PUT or DELETE)

You can get any query string data i.e www.example.com?id=2&name=r

You must get data using $_GET['id'] or $_REQUEST['id'].

Post data means like form <form action='' method='POST'> you must use $_POST or $_REQUEST.

How to check if a column exists in a datatable

For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.

 private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
    {
        bool iscolumnExist = true;
        try
        {
            if (null != tableNameToCheck && tableNameToCheck.Columns != null)
            {
                foreach (string columnName in columnsNames)
                {
                    if (!tableNameToCheck.Columns.Contains(columnName))
                    {
                        iscolumnExist = false;
                        break;
                    }
                }
            }
            else
            {
                iscolumnExist = false;
            }
        }            
        catch (Exception ex)
        {

        }
        return iscolumnExist;
    }

How do I check if an HTML element is empty using jQuery?

jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

How do you make a deep copy of an object?

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

Read next word in java

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }

How does String.Index work in Swift

Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.

func textViewDidChange(_ textView: UITextView) {
    tableView.beginUpdates()
    if textView.text.contains("\n"){
        textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
        textView.resignFirstResponder()
    }
    tableView.endUpdates()
}

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

This happened to me because of a partially downloaded gradle distribution zip

  • To resolve simply go to below path

    "C:/Users/your_username/.gradle"

    OR

    pull your gradle path from File->Settings->Build, Exectution, Deployment-> Gradle -> gradle service directory path.

  • Delete the partially downloaded distribution gradle folder

  • Go to Studio (no need to restart) and perform gradle sync

How to navigate a few folders up?

This is what worked best for me:

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end. Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.

Retrieving Data from SQL Using pyodbc

Just do this:

import pandas as pd
import pyodbc

cnxn = pyodbc.connect("Driver={SQL Server}\
                    ;Server=SERVER_NAME\
                    ;Database=DATABASE_NAME\
                    ;Trusted_Connection=yes")

df = pd.read_sql("SELECT * FROM myTableName", cnxn) 
df.head()

Add zero-padding to a string

string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

Clearing an input text field in Angular2

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

Working Plunker

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

2. Second Method

  • use of [(ngModel)] it should work with ngModel.

why ?

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

see working example of same with ngModel

Working Example with ngModel

Search in lists of lists by given index

Nothing wrong with using a gen exp, but if the goal is to inline the loop...

>>> import itertools, operator
>>> 'b' in itertools.imap(operator.itemgetter(1), the_list)
True

Should be the fastest as well.

How to define custom sort function in javascript?

function msort(arr){
    for(var i =0;i<arr.length;i++){
        for(var j= i+1;j<arr.length;j++){
            if(arr[i]>arr[j]){
                var swap = arr[i];
                arr[i] = arr[j];
                arr[j] = swap;
            }
        }
    }
return arr;
}

Any reason not to use '+' to concatenate two strings?

When working with multiple people, it's sometimes difficult to know exactly what's happening. Using a format string instead of concatenation can avoid one particular annoyance that's happened a whole ton of times to us:

Say, a function requires an argument, and you write it expecting to get a string:

In [1]: def foo(zeta):
   ...:     print 'bar: ' + zeta

In [2]: foo('bang')
bar: bang

So, this function may be used pretty often throughout the code. Your coworkers may know exactly what it does, but not necessarily be fully up-to-speed on the internals, and may not know that the function expects a string. And so they may end up with this:

In [3]: foo(23)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

/home/izkata/<ipython console> in foo(zeta)

TypeError: cannot concatenate 'str' and 'int' objects

There would be no problem if you just used a format string:

In [1]: def foo(zeta):
   ...:     print 'bar: %s' % zeta
   ...:     
   ...:     

In [2]: foo('bang')
bar: bang

In [3]: foo(23)
bar: 23

The same is true for all types of objects that define __str__, which may be passed in as well:

In [1]: from datetime import date

In [2]: zeta = date(2012, 4, 15)

In [3]: print 'bar: ' + zeta
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

TypeError: cannot concatenate 'str' and 'datetime.date' objects

In [4]: print 'bar: %s' % zeta
bar: 2012-04-15

So yes: If you can use a format string do it and take advantage of what Python has to offer.

How to check if input date is equal to today's date?

Try using moment.js

moment('dd/mm/yyyy').isSame(Date.now(), 'day');

You can replace 'day' string with 'year, month, minute' if you want.

Subtract days from a DateTime

DateTime dateForButton = DateTime.Now.AddDays(-1);

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.

You have to call show() either in onProgressUpdate() or in onPostExecute().

For example:

class ExampleTask extends AsyncTask<String, String, String> {

    // Your onPreExecute method.

    @Override
    protected String doInBackground(String... params) {
        // Your code.
        if (condition_is_true) {
            this.publishProgress("Show the dialog");
        }
        return "Result";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        connectionProgressDialog.dismiss();
        downloadSpinnerProgressDialog.show();
    }
}

Sorting a Python list by two fields

Sorting list of dicts using below will sort list in descending order on first column as salary and second column as age

d=[{'salary':123,'age':23},{'salary':123,'age':25}]
d=sorted(d, key=lambda i: (i['salary'], i['age']),reverse=True)

Output: [{'salary': 123, 'age': 25}, {'salary': 123, 'age': 23}]

How to print multiple variable lines in Java

You can do it with 1 printf:

System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);

Create SQLite database in android

this is the full source code to direct use,

    public class CardDBDAO {

        protected SQLiteDatabase database;
        private DataBaseHelper dbHelper;
        private Context mContext;

        public CardDBDAO(Context context) {
            this.mContext = context;
            dbHelper = DataBaseHelper.getHelper(mContext);
            open();

        }

        public void open() throws SQLException {
            if(dbHelper == null)
                dbHelper = DataBaseHelper.getHelper(mContext);
            database = dbHelper.getWritableDatabase();
        }

    }



    public class DataBaseHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME = "mydbnamedb";
        private static final int DATABASE_VERSION = 1;

        public static final String CARDS_TABLE = "tbl_cards";
        public static final String POICATEGORIES_TABLE = "tbl_poicategories";
        public static final String POILANGS_TABLE = "tbl_poilangs";

        public static final String ID_COLUMN = "id";

        public static final String POI_ID = "poi_id";
        public static final String POICATEGORIES_COLUMN = "poi_categories";

        public static final String POILANGS_COLUMN = "poi_langs";

        public static final String CARDS = "cards";
        public static final String CARD_ID = "card_id";
        public static final String CARDS_PCAT_ID = "pcat_id";

        public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
                + POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
                + POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
                + CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
                + " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";

        private static DataBaseHelper instance;

        public static synchronized DataBaseHelper getHelper(Context context) {
            if (instance == null)
                instance = new DataBaseHelper(context);
            return instance;
        }

        private DataBaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
            if (!db.isReadOnly()) {
                // Enable foreign key constraints
                // db.execSQL("PRAGMA foreign_keys=ON;");
            }
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_PCAT_TABLE);
            db.execSQL(CREATE_PLANG_TABLE);
            db.execSQL(CREATE_CARDS_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }




    public class PoiLangDAO extends CardDBDAO {

            private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
                    + " =?";

            public PoiLangDAO(Context context) {
                super(context);
            }

            public long save(PLang plang_data) {

                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                return database
                        .insert(DataBaseHelper.POILANGS_TABLE, null, values);
            }

            public long update(PLang plang_data) {
                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                long result = database.update(DataBaseHelper.POILANGS_TABLE,
                        values, WHERE_ID_EQUALS,
                        new String[] { String.valueOf(plang_data.getId()) });
                Log.d("Update Result:", "=" + result);
                return result;

            }

            public int deleteDept(PLang plang_data) {
                return database.delete(DataBaseHelper.POILANGS_TABLE,
                        WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
            }

            public List<PLang> getPLangs1() {
                List<PLang> plang_list = new ArrayList<PLang>();
                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, null, null, null,
                        null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public List<PLang> getPLangs(String pid) {
                List<PLang> plang_list = new ArrayList<PLang>();

                String selection = DataBaseHelper.POI_ID + "=?";
                String[] selectionArgs = { pid };

                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, selection,
                        selectionArgs, null, null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public void loadPLangs(String poi_id, String langarrs) {
                PLang plangbin = new PLang(poi_id, langarrs);

                List<PLang> plang_arr = new ArrayList<PLang>();
                plang_arr.add(plangbin);

                for (PLang dept : plang_arr) {
                    ContentValues values = new ContentValues();
                    values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
                    values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
                    database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
                }
            }

        }




        public class PLang {

            public PLang() {
                super();
            }

            public PLang(String poi_id, String langarrs) {
                // TODO Auto-generated constructor stub

                this.poi_id = poi_id;
                this.langarr = langarrs;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getPoi_id() {
                return poi_id;
            }

            public void setPoi_id(String poi_id) {
                this.poi_id = poi_id;
            }

            public String getLangarr() {
                return langarr;
            }

            public void setLangarr(String langarr) {
                this.langarr = langarr;
            }

            private int id;
            private String poi_id;
            private String langarr;

    }

How to create a printable Twitter-Bootstrap page

Be sure to have a stylesheet assigned for printing.
It could be a separate stylesheet:

<link rel="stylesheet" type="text/css" media="print" href="print.css">

or one you share for all devices:

<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> # Note there's no media attribute

Then, you can write your styles for printers in the separate stylesheets or in the shared one using media queries:

@media print {
    /* Your styles here */
}

JQuery get all elements by class name

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);

Is there an ignore command for git like there is for svn?

I hope it's not too late.

If you are on Windows you can just do the following to create a .gitignore file

echo name_of_the_file_you_want_to_ignore.extension > .gitignore

In order to edit .gitignore you can run

notepad .gitignore

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

Rotating videos with FFmpeg

ffmpeg -vfilters "rotate=90" -i input.mp4 output.mp4 

won't work, even with latest source...

must change the order:

ffmpeg -i input.mp4 -vf vflip output.mp4

works fine

How can I trigger a JavaScript event click

What

 l.onclick();

does is exactly calling the onclick function of l, that is, if you have set one with l.onclick = myFunction;. If you haven't set l.onclick, it does nothing. In contrast,

 l.click();

simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);, in HTML, or in any other way.

Display UIViewController as Popup in iPhone

Modal Popups in Interface Builder (Storyboards)

Step 1

On the ViewController you want as your modal popup, make the background color of the root UIView clear. Set Clear Color on root view Tip: Do not use the root UIView as your popup. Add a new UIView that is smaller to be your popup.

Step 2

Create a Segue to the ViewController that has your popup. Select "Present Modally". Segue

Two Methods To Create Popup From Here

Method One - Using the Segue

Select the Segue and change Presentation to "Over Current Context": Over Current Context

Method Two - Using the View Controller

Select the ViewController Scene that is your popup. In Attributes Inspector, under View Controller section, set Presentation to "Over Current Context": ViewController

Either method will work. That should do it!

Finished Product

Angularjs how to upload multipart form data and a file?

It is more efficient to send the files directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

Doing Multiple $http.post Requests Directly from a FileList

$scope.upload = function(url, fileList) {
    var config = {
      headers: { 'Content-Type': undefined },
      transformResponse: angular.identity
    };
    var promises = fileList.map(function(file) {
      return $http.post(url, file, config);
    });
    return $q.all(promises);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.


Working Demo of "select-ng-files" Directive that Works with ng-model1

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

PHP Fatal error: Cannot redeclare class

This error might also occur if you define the __construct method more than once.

Histogram with Logarithmic Scale and custom breaks

Another option would be to use the package ggplot2.

ggplot(mydata, aes(x = V3)) + geom_histogram() + scale_x_log10()

How to convert C# nullable int to int

In C# 7.1 and later, type can be inferred by using the default literal instead of the default operator so it can be written as below:

v2 = v1 ?? default;

Check if record exists from controller in Rails

In this case I like to use the exists? method provided by ActiveRecord:

Business.exists? user_id: current_user.id

Execute command on all files in a directory

Maxdepth

I found it works nicely with Jim Lewis's answer just add a bit like this:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
$ find . -maxdepth 1 -type f -name '*.sh' -exec {} \; > results.out

Sort Order

If you want to execute in sort order, modify it like this:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -maxdepth 2 -type f -name '*.sh' | sort | bash > results.out

Just for an example, this will execute with following order:

bash: 1: ./assets/main.sh
bash: 2: ./builder/clean.sh
bash: 3: ./builder/concept/compose.sh
bash: 4: ./builder/concept/market.sh
bash: 5: ./builder/concept/services.sh
bash: 6: ./builder/curl.sh
bash: 7: ./builder/identity.sh
bash: 8: ./concept/compose.sh
bash: 9: ./concept/market.sh
bash: 10: ./concept/services.sh
bash: 11: ./product/compose.sh
bash: 12: ./product/market.sh
bash: 13: ./product/services.sh
bash: 14: ./xferlog.sh

Unlimited Depth

If you want to execute in unlimited depth by certain condition, you can use this:

export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -type f -name '*.sh' | sort | bash > results.out

then put on top of each files in the child directories like this:

#!/bin/bash
[[ "$(dirname `pwd`)" == $DIR ]] && echo "Executing `realpath $0`.." || return

and somewhere in the body of parent file:

if <a condition is matched>
then
    #execute child files
    export DIR=`pwd`
fi

IE8 support for CSS Media Query

Taken from the css3mediaqueries.js project page.

Note: Doesn't work on @import'ed stylesheets (which you shouldn't use anyway for performance reasons). Also won't listen to the media attribute of the <link> and <style> elements.

How to check if an element exists in the xml using xpath?

Use the boolean() XPath function

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN

  • a node-set is true if and only if it is non-empty

  • a string is true if and only if its length is non-zero

  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

If there is an AttachedXml in the CreditReport of primary Consumer, then it will return true().

boolean(/mc:Consumers
          /mc:Consumer[@subjectIdentifier='Primary']
            //mc:CreditReport/mc:AttachedXml)

Writing string to a file on a new line every time

Use "\n":

file.write("My String\n")

See the Python manual for reference.

How to suppress scientific notation when printing float values?

Since this is the top result on Google, I will post here after failing to find a solution for my problem. If you are looking to format the display value of a float object and have it remain a float - not a string, you can use this solution:

Create a new class that modifies the way that float values are displayed.

from builtins import float
class FormattedFloat(float):

    def __str__(self):
        return "{:.10f}".format(self).rstrip('0')

You can modify the precision yourself by changing the integer values in {:f}

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Example JavaScript code to parse CSV data

Here's my simple vanilla JavaScript code:

let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0) 
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

bootstrap 3 navbar collapse button not working

In case it might help someone, I had a similar issue after adding Bootstrap 3 to my MVC 4 project. It turned out my problem was that I was referring to bootstrap-min.js instead of bootstrap.js in my BundleConfig.cs.

Didn't work:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                            "~/Scripts/bootstrap-min.js"));

Worked:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                        "~/Scripts/bootstrap.js"));

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Altering column size in SQL Server

For Oracle For Database:

ALTER TABLE table_name MODIFY column_name VARCHAR2(255 CHAR);

How to show full column content in a Spark Dataframe?

Below code would help to view all rows without truncation in each column

df.show(df.count(), False)

C++ - Assigning null to a std::string

I won't argue that it's a good idea (or the semantics of using nullptr with things that aren't pointers), but it's relatively simple to create a class which would provide "nullable" semantics (see nullable_string).

However, this is a much better fit for C++17's std::optional:

#include <string>
#include <iostream>
#include <optional>

// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
    if (b)
        return "Godzilla";
    else
        return {};
}

int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << std::endl;

    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create(true))
    {
        std::cout << "create(true) returned " << *str << std::endl;
    }
}

std::optional, as shown in the example, is convertible to bool, or you may use the has_value() method, has exceptions for bad access, etc. This provides you with nullable semantics, which seems to be what Maria was trying to accomplish.

And if you don't want to wait around for C++17 compatibility, see this answer about Boost.Optional.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

Use STRING_AGG function for PostgreSQL and Google BigQuery SQL:

SELECT company_id, STRING_AGG(employee, ', ')
FROM employees
GROUP BY company_id;

Add table row in jQuery

    // Create a row and append to table
    var row = $('<tr />', {})
        .appendTo("#table_id");

    // Add columns to the row. <td> properties can be given in the JSON
    $('<td />', {
        'text': 'column1'
    }).appendTo(row);

    $('<td />', {
        'text': 'column2',
        'style': 'min-width:100px;'
    }).appendTo(row);

How to generate unique ID with node.js

More easy and without addition modules

Math.random().toString(26).slice(2)

Error 'tunneling socket' while executing npm install

I also ran into the similar issue and was using CNTLM for proxy configuration. In my case HTTP_PROXY and HTTPS_PROXY are taking higher precedence over http_proxy and https_proxy so be aware of changing all proxy variables.

env|grep -i proxy

and make sure all of the below proxy variables should point to the same proxy.

HTTP-PROXY = "http://localhost:3128"
HTTPS-PROXY = "https://localhost:3128"
HTTPS_PROXY = "http://localhost:3128"
HTTP_PROXY = "http://localhost:3128"
PROXY = "http://localhost:3128"
http-proxy = "http://localhost:3128"
http_proxy = "http://localhost:3128"
https-proxy = "https://localhost:3128/"
https_proxy = "https://localhost:3128"
proxy = "http://localhost:3128/"

I know some variables are unneccessary but I'm not sure which is using what.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

For "partial" I always use it as follows:

If there's something you need to include in a page that you need to go via the controller (like you would with an Ajax call) then use "Html.RenderPartial".

If you have a 'static' include that isn't linked to a controller per-se and just in the 'shared' folder for example, use "HTML.partial"

PHP function to make slug (URL string)

What about using something that is already implemented in Core?

//Clean non UTF-8 characters    
Mage::getHelper('core/string')->cleanString($str)

Or one of the core url/ url rewrite methods..

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had a similar problem, and it was because one of my beans had been moved to another directory recently. I needed to do a "build clean" by deleting the build/classes/java directory and the problem went away. (The error message had the two different file paths conflicting with each other, although I knew one should not actually exist anymore.)

How can I switch word wrap on and off in Visual Studio Code?

Go to the Preferences tab (menu FileSettings), and then search as “word wrap”. The following animated image is helpful too.

Enter image description here

Should we pass a shared_ptr by reference or by value?

Not knowing time cost of shared_copy copy operation where atomic increment and decrement is in, I suffered from much higher CPU usage problem. I never expected atomic increment and decrement may take so much cost.

Following my test result, int32 atomic increment and decrement takes 2 or 40 times than non-atomic increment and decrement. I got it on 3GHz Core i7 with Windows 8.1. The former result comes out when no contention occurs, the latter when high possibility of contention occurs. I keep in mind that atomic operations are at last hardware based lock. Lock is lock. Bad to performance when contention occurs.

Experiencing this, I always use byref(const shared_ptr&) than byval(shared_ptr).

How to change port number for apache in WAMP

Change port number for Xampp Go to the file C:\xampp\apache\conf\httpd.conf

#Listen 12.34.56.78:80
Listen 80

Change 80 to 82

as

#Listen 12.34.56.78:82
Listen 82

now your url will be

http://localhost:82

Use dynamic variable names in JavaScript

eval is one option.

var a = 1;
var name = 'a';

document.write(eval(name)); // 1

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

How do I handle newlines in JSON?

According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).

As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

send bold & italic text on telegram bot with html

To send bold:

  1. Set the parse_mode to markdown and send *bold*
  2. Set the parse_mode to html and send <b>bold</b>

To send italic:

  1. Set the parse_mode to markdown and send _italic_
  2. Set the parse_mode to html and send <i>italic</i>

ImportError: No module named PIL

On windows 10 I managed to get there with:

cd "C:\Users\<your username>\AppData\Local\Programs\Python\Python37-32" 
python -m pip install --upgrade pip     <-- upgrading from 10.something to 19.2.2.
pip3 uninstall pillow
pip3 uninstall PIL
pip3 install image

after which in python (python 3.7 in my case) this works fine...

import PIL
from PIL import image

jQuery: checking if the value of a field is null (empty)

My Working solution is

var town_code = $('#town_code').val(); 
 if(town_code.trim().length == 0){
    var town_code = 0;
 }

Custom toast on Android: a simple example

Heads Up, Updates to toasts in Android 11

Custom toasts from the background are blocked, Android 11 protects users by deprecating custom toast views. For security reasons and to maintain a good user experience, the system blocks toasts that contain custom views if those toasts are sent from the background by an app that targets Android 11.

addCallback() method added in Android R If you want to be notified when a toast (text or custom) appears or disappears.

The most important text in toast API changes that for apps that target Android 11 the getView() method returns null when you access it, So, ensure to protect your apps from FATAL EXCEPTION, you know what I mean :)

Use snackbars instead if applicable.

It's recommended that you use snackbars instead where possible. If your app's use case prevents you from using snackbars, such as when you need to send the user a message while your app is in the background, you can still use text toasts because they aren't restricted by the new behavior change.

See the official docs for more details on the topic.

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

Simple pagination in javascript

I created a class structure for collections in general that would meet this requirement. and it looks like this:

class Collection {

    constructor() {
        this.collection = [];
        this.index = 0;
    }

    log() {
        return console.log(this.collection);
    }

    push(value) {
        return this.collection.push(value);
    }

    pushAll(...values) {
        return this.collection.push(...values);
    }

    pop() {
        return this.collection.pop();
    }

    shift() {
        return this.collection.shift();
    }

    unshift(value) {
        return this.collection.unshift(value);
    }

    unshiftAll(...values) {
        return this.collection.unshift(...values);
    }

    remove(index) {
        return this.collection.splice(index, 1);
    }

    add(index, value) {
        return this.collection.splice(index, 0, value);
    }

    replace(index, value) {
        return this.collection.splice(index, 1, value);
    }

    clear() {
        this.collection.length = 0;
    }

    isEmpty() {
        return this.collection.length === 0;
    }

    viewFirst() {
        return this.collection[0];
    }

    viewLast() {
        return this.collection[this.collection.length - 1];
    }

    current(){
        if((this.index <= this.collection.length - 1) && (this.index >= 0)){
            return this.collection[this.index];
        }
        else{
            return `Object index exceeds collection range.`;
        }
    }

    next() {
        this.index++;
        this.index > this.collection.length - 1 ? this.index = 0 : this.index;
        return this.collection[this.index];
    }

    previous(){
        this.index--;
        this.index < 0 ? (this.index = this.collection.length-1) : this.index;
        return this.collection[this.index];
    }
}

...and essentially what you would do is have a collection of arrays of whatever length for your pages pushed into the class object, and then use the next() and previous() functions to display whatever 'page' (index) you wanted to display. Would essentially look like this:

let books = new Collection();
let firstPage - [['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'],];
let secondPage - [['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'],];
books.pushAll(firstPage, secondPage); // loads each array individually
books.current() // display firstPage
books.next() // display secondPage

Could not find method compile() for arguments Gradle

In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...

If you experienced this issue in a git project, do git status and remove the unrevisioned files. (For me elasticsearch had a problem with plugins/analysis-icu).

Gradle Version : 5.1.1

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.\{,5\}//' file.dat worked like a charm for me

How to change facet labels?

Here's another solution that's in the spirit of the one given by @naught101, but simpler and also does not throw a warning on the latest version of ggplot2.

Basically, you first create a named character vector

hospital_names <- c(
                    `Hospital#1` = "Some Hospital",
                    `Hospital#2` = "Another Hospital",
                    `Hospital#3` = "Hospital Number 3",
                    `Hospital#4` = "The Other Hospital"
                    )

And then you use it as a labeller, just by modifying the last line of the code given by @naught101 to

... + facet_grid(hospital ~ ., labeller = as_labeller(hospital_names))

Hope this helps.

Split function in oracle to comma separated values with automatic sequence

Oracle Setup:

CREATE OR REPLACE FUNCTION split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
  p_result       SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
    END IF;
  END IF;
  RETURN p_result;
END;
/

Query

SELECT ROWNUM AS ID,
       COLUMN_VALUE AS Data
FROM   TABLE( split_String( 'A,B,C,D' ) );

Output:

ID DATA
-- ----
 1 A
 2 B
 3 C
 4 D

how to use javascript Object.defineProperty

_x000D_
_x000D_
Object.defineProperty(Array.prototype, "last", {_x000D_
  get: function() {_x000D_
    if (this[this.length -1] == undefined) { return [] }_x000D_
    else { return this[this.length -1] }_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log([1,2,3,4].last) //returns 4
_x000D_
_x000D_
_x000D_

Why is synchronized block better than synchronized method?

In your case both are equivalent!

Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.

In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.

public static synchronized int getCount() {
    // ...
}

is same as

public int getCount() {
    synchronized (ClassName.class) {
        // ...
    }
}

Using LIKE in an Oracle IN clause

No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:

SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

How to view table contents in Mysql Workbench GUI?

Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.

enter image description here

This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:

enter image description here

CSS @media print issues with background-color;

Best "solution" I have found is to provide a prominent "Print" button or link which pops up a small dialogue box explaining boldly, briefly and concisely that they need to adjust printer settings (with an ABC 123 bullet point instruction) to enable background and image printing. This has been very successful for me.

How to check if a Ruby object is a Boolean

No. Not like you have your code. There isn't any class named Boolean. Now with all the answers you have you should be able to create one and use it. You do know how to create classes don't you? I only came here because I was just wondering this idea myself. Many people might say "Why? You have to just know how Ruby uses Boolean". Which is why you got the answers you did. So thanks for the question. Food for thought. Why doesn't Ruby have a Boolean class?

NameError: uninitialized constant Boolean

Keep in mind that Objects do not have types. They are classes. Objects have data. So that's why when you say data types it's a bit of a misnomer.

Also try rand 2 because rand 1 seems to always give 0. rand 2 will give 1 or 0 click run a few times here. https://repl.it/IOPx/7

Although I wouldn't know how to go about making a Boolean class myself. I've experimented with it but...

class Boolean < TrueClass
  self
end

true.is_a?(Boolean) # => false
false.is_a?(Boolean) # => false

At least we have that class now but who knows how to get the right values?

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation

The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.

Hope this saves somebody else some time, and teaches the search engines about this open source gem :)

HTTP GET in VB.NET

Try this:

WebRequest request = WebRequest.CreateDefault(RequestUrl);
request.Method = "GET";

WebResponse response;
try { response = request.GetResponse(); }
catch (WebException exc) { response = exc.Response; }

if (response == null)
    throw new HttpException((int)HttpStatusCode.NotFound, "The requested url could not be found.");

using(StreamReader reader = new StreamReader(response.GetResponseStream())) {
    string requestedText = reader.ReadToEnd();

    // do what you want with requestedText
}

Sorry about the C#, I know you asked for VB, but I didn't have time to convert.

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

How to use && in EL boolean expressions in Facelets?

In addition to the answer of BalusC, use the following Java RegExp to replace && with and:

Search:  (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3

You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.

Multipart File upload Spring Boot

@RequestBody MultipartFile[] submissions

should be

@RequestParam("file") MultipartFile[] submissions

The files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.

You can also replace HttpServletRequest with MultipartHttpServletRequest, which gives you access to the headers of the individual parts.

Member '<method>' cannot be accessed with an instance reference

cannot be accessed with an instance reference

It means you're calling a STATIC method and passing it an instance. The easiest solution is to remove Static, eg:

public static void ExportToExcel(IEnumerable data, string sheetName) {

Finding duplicate integers in an array and display how many times they occurred

Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

In the console is telling you that is a conflict with login. I think that you should declare also in the index.html thymeleaf. Something like:

    <html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:th="http://www.thymeleaf.org" 
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>k</title> 
</head>

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>