Programs & Examples On #Blink

Blink is an open source rendering engine forked from WebKit. It is included in Google Chrome 28+ and Opera 14+. Blink includes a different multiprocess architecture than WebKit2, and the V8 JavaScript engine, rather than JavaScriptCore.

Imitating a blink tag with CSS3 animations

If you want smooth blinking text or something a like you can use following code:

_x000D_
_x000D_
 .blinking {
    -webkit-animation: 1s blink ease infinite;
    -moz-animation: 1s blink ease infinite;
    -ms-animation: 1s blink ease infinite;
    -o-animation: 1s blink ease infinite;
    animation: 1s blink ease infinite;
  }

  @keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-moz-keyframes blink {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-webkit-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-ms-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-o-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }
_x000D_
<span class="blinking">I am smoothly blinking</span>
_x000D_
_x000D_
_x000D_

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

The appearance of the scroll bars can be controlled with WebKit's -webkit-scrollbar pseudo-elements [blog]. You can disable the default appearance and behaviour by setting -webkit-appearance [docs] to none.

Because you're removing the default style, you'll also need to specify the style yourself or the scroll bar will never show up. The following CSS recreates the appearance of the hiding scroll bars:

Example (jsfiddle)

CSS
.frame::-webkit-scrollbar {
    -webkit-appearance: none;
}

.frame::-webkit-scrollbar:vertical {
    width: 11px;
}

.frame::-webkit-scrollbar:horizontal {
    height: 11px;
}

.frame::-webkit-scrollbar-thumb {
    border-radius: 8px;
    border: 2px solid white; /* should match background, can't be transparent */
    background-color: rgba(0, 0, 0, .5);
}

.frame::-webkit-scrollbar-track { 
    background-color: #fff; 
    border-radius: 8px; 
} 
WebKit (Chrome) Screenshot

screenshot showing webkit's scrollbar, without needing to hover

Where does flask look for image files?

use absolute path where the image actually exists (e.g) '/home/artitra/pictures/filename.jpg'

or create static folder inside your project directory like this

| templates
   - static/
         - images/
              - yourimagename.jpg

then do this

app = Flask(__name__, static_url_path='/static')

then you can access your image like this in index.html

src ="/static/images/yourimage.jpg" 

in img tag

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

Try This:

_x000D_
_x000D_
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">_x000D_
    <a href="{{ url('/Dashboard') }}">_x000D_
 <i class="fa fa-dashboard"></i> <span>Dashboard</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

Gradle: How to Display Test Results in the Console in Real Time?

Following on from Benjamin Muschko's answer (19 March 2011), you can use the -i flag along with grep, to filter out 1000s of unwanted lines. Examples:

Strong filter - Only display each unit test name and test result and the overall build status. Setup errors or exceptions are not displayed.

./gradlew test -i | grep -E " > |BUILD"

Soft filter - Display each unit test name and test result, as well as setup errors/exceptions. But it will also include some irrelevant info:

./gradlew test -i | grep -E -v "^Executing |^Creating |^Parsing |^Using |^Merging |^Download |^title=Compiling|^AAPT|^future=|^task=|:app:|V/InstrumentationResultParser:"

Soft filter, Alternative syntax: (search tokens are split into individual strings)

./gradlew test -i | grep -v -e "^Executing " -e "^Creating " -e "^Parsing " -e "^Using " -e "^Merging " -e "^Download " -e "^title=Compiling" -e "^AAPT" -e "^future=" -e "^task=" -e ":app:" -e "V/InstrumentationResultParser:"

Explanation of how it works:

The first command is ./gradlew test -i and "-i" means "Info/Verbose" mode, which prints the result of each test in real-time, but also displays large amounts of unwanted debug lines.

So the output of the first command, ./gradlew test -i, is piped to a second command grep, which will filter out many unwanted lines, based on a regular expression. "-E" enables the regular expression mode for a single string; "-e" enables regular expressions for multiple strings; and "|" in the regex string means "or".

In the strong filter, a unit test name and test result is allowed to display using " > ", and the overall status is allowed with "BUILD".

In the soft filter, the "-v" flag means "not containing" and "^" means "start of line". So it strips out all lines that start with "Executing " or start with "Creating ", etc.


Example for Android instrumentation unit tests, with gradle 5.1:

./gradlew connectedDebugAndroidTest --continue -i | grep -v -e \
    "^Transforming " -e "^Skipping " -e "^Cache " -e "^Performance " -e "^Creating " -e \
    "^Parsing " -e "^file " -e "ddms: " -e ":app:" -e "V/InstrumentationResultParser:"

Example for Jacoco unit test coverage, with gradle 4.10:

./gradlew createDebugCoverageReport --continue -i | grep -E -v "^Executing |^Creating |^Parsing |^Using |^Merging |^Download |^title=Compiling|^AAPT|^future=|^task=|:app:|V/InstrumentationResultParser:"

Google Maps setCenter()

For me above solutions didn't work then I tried

map.setCenter(new google.maps.LatLng(lat, lng));

and it worked as expected.

How do I escape a reserved word in Oracle?

you have to rename the column to an other name because TABLE is reserved by Oracle.

You can see all reserved words of Oracle in the oracle view V$RESERVED_WORDS.

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

map3 = new HashMap<>();

map3.putAll(map1);
map3.putAll(map2);

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);

This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.

How to execute a java .class from the command line

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were

S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class

My code contained the following line

System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());

First, I had to move to the classpath directory

cd /D "S:\Accessibility\tools\src\test\java"

Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.

set classpath=%classpath%;.;..\..\..\src\main\resources; 

Then, I had to run java using the classname.

java com.accessibility.HelloWorld 

Allow only numbers to be typed in a textbox

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

In my case, I solved adding return in the onClientClick:

Code Behind

function verify(){
  if (document.getElementById("idName").checked == "") {
    alert("Fill the field");
    return false;
  }
}

Design Surface

<asp:Button runat="server" ID="send" Text="Send" onClientClick="return verify()" />

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Typescript from v1.4 has the type keyword which declares a type alias (analogous to a typedef in C/C++). You can declare your callback type thus:

type CallbackFunction = () => void;

which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:

type CallbackFunctionVariadic = (...args: any[]) => void;

Then you can say, for example,

let callback: CallbackFunctionVariadic = function(...args: any[]) {
  // do some stuff
};

If you want a function that takes an arbitrary number of arguments and returns anything (including void):

type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;

You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:

type CallbackFunctionSomeVariadic =
  (arg1: string, arg2: number, ...args: any[]) => void;

This can be useful for things like EventEmitter handlers.

Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.

What exactly are iterator, iterable, and iteration?

Here's another view using collections.abc. This view may be useful the second time around or later.

From collections.abc we can see the following hierarchy:

builtins.object
    Iterable
        Iterator
            Generator

i.e. Generator is derived from Iterator is derived from Iterable is derived from the base object.

Hence,

  • Every iterator is an iterable, but not every iterable is an iterator. For example, [1, 2, 3] and range(10) are iterables, but not iterators. x = iter([1, 2, 3]) is an iterator and an iterable.
  • A similar relationship exists between Iterator and Generator.
  • Calling iter() on an iterator or a generator returns itself. Thus, if it is an iterator, then iter(it) is it is True.
  • Under the hood, a list comprehension like [2 * x for x in nums] or a for loop like for x in nums:, acts as though iter() is called on the iterable (nums) and then iterates over nums using that iterator. Hence, all of the following are functionally equivalent (with, say, nums=[1, 2, 3]):
    • for x in nums:
    • for x in iter(nums):
    • for x in iter(iter(nums)):
    • for x in iter(iter(iter(iter(iter(nums))))):

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

What is VanillaJS?

Using "VanillaJS" means using plain JavaScript without any additional libraries like jQuery.

People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries.

Here's a funny site that jokingly talks about this: http://vanilla-js.com/

Use awk to find average of a column

Try this:

ls -l  | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'

NR is an AWK builtin variable to count the no. of records

@ViewChild in *ngIf

Working on Angular 8 No need to import ChangeDector

ngIf allows you not to load the element and avoid adding more stress to your application. Here's how I got it running without ChangeDetector

elem: ElementRef;

@ViewChild('elemOnHTML', {static: false}) set elemOnHTML(elemOnHTML: ElementRef) {
    if (!!elemOnHTML) {
      this.elem = elemOnHTML;
    }
}

Then when I change my ngIf value to be truthy I would use setTimeout like this for it to wait only for the next change cycle:

  this.showElem = true;
  console.log(this.elem); // undefined here
  setTimeout(() => {
    console.log(this.elem); // back here through ViewChild set
    this.elem.do();
  });

This also allowed me to avoid using any additional libraries or imports.

How to create a property for a List<T>

public class MyClass<T>
{
  private List<T> list;

  public List<T> MyList { get { return list; } set { list = value; } }
}

Then you can do something like

MyClass<int> instance1 = new MyClass<int>();
List<int> integers = instance1.MyList;

MyClass<Person> instance2 = new MyClass<Person>();
IEnumerable<Person> persons = instance2.MyList;

How to download a file from a website in C#

You can use this code to Download file from a WebSite to Desktop:

using System.Net;

WebClient client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");

How can I listen for a click-and-hold in jQuery?

I wrote some code to make it easy

_x000D_
_x000D_
//Add custom event listener_x000D_
$(':root').on('mousedown', '*', function() {_x000D_
    var el = $(this),_x000D_
        events = $._data(this, 'events');_x000D_
    if (events && events.clickHold) {_x000D_
        el.data(_x000D_
            'clickHoldTimer',_x000D_
            setTimeout(_x000D_
                function() {_x000D_
                    el.trigger('clickHold')_x000D_
                },_x000D_
                el.data('clickHoldTimeout')_x000D_
            )_x000D_
        );_x000D_
    }_x000D_
}).on('mouseup mouseleave mousemove', '*', function() {_x000D_
    clearTimeout($(this).data('clickHoldTimer'));_x000D_
});_x000D_
_x000D_
//Attach it to the element_x000D_
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold_x000D_
$('#HoldListener').on('clickHold', function() {_x000D_
    console.log('Worked!');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<img src="http://lorempixel.com/400/200/" id="HoldListener">
_x000D_
_x000D_
_x000D_

See on JSFiddle

Now you need just to set the time of holding and add clickHold event on your element

How to implement a tree data-structure in Java?

There are a couple of tree data structures in Java, such as DefaultMutableTreeNode in JDK Swing, Tree in Stanford parser package, and other toy codes. But none of these are sufficient yet small enough for general purpose.

Java-tree project attempts to provide another general-purpose tree data structure in Java. The difference between this and others are

  • Totally free. You can use it anywhere (except in your homework :P)
  • Small but general enough. I put everything of the data structure in one class file, so it would be easy to copy/paste.
  • Not just a toys. I am aware of dozens of Java tree codes that can only handle binary trees or limited operations. This TreeNode is much more than that. It provides different ways of visiting nodes, such as preorder, postorder, breadthfirst, leaves, path to root, etc. Moreover, iterators are provided too for the sufficiency.
  • More utils will be added. I am willing to add more operations to make this project comprehensive, especially if you send a request through github.

AngularJS - pass function to directive

use dash and lower case for attribute name ( like other answers said ) :

 <test color1="color1" update-fn="updateFn()"></test>

And use "=" instead of "&" in directive scope:

 scope: { updateFn: '='}

Then you can use updateFn like any other function:

 <button ng-click='updateFn()'>Click</button>

There you go!

Remove files from Git commit

If for any reason (as it was in my case) you'll have trouble reseting all files from the last commit - as in git reset --soft HEAD^ - and your case mets the following conditions, you can do as I explain below.

  1. the file you are trying to remove already existed in repository before the last commit
  2. you can undo all changes in the file since the previous commit (HEAD~2 - the commit just before the last commit)

You can then undo all the changes since the previous commit (HEAD~2), save the file, stage it (git add filename) and then run git commit --amend --no-edit. This will commit the "new changes" - which is actually recommitting the file to the last commit as it was before the last commit.

Sending mail attachment using Java

For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.

If you want both attachment and text try this based on the accepted answer :

    Properties props = new java.util.Properties();
    props.put("mail.smtp.host", "yourHost");
    props.put("mail.smtp.port", "yourHostPort");
    props.put("mail.smtp.auth", "true");             
    props.put("mail.smtp.starttls.enable", "true");


    // Session session = Session.getDefaultInstance(props, null);
    Session session = Session.getInstance(props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("user", "password");
                }
              });


    Message msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        msg.setSubject("your subject");

        Multipart multipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText("your text");

        MimeBodyPart attachmentBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"

        multipart.addBodyPart(textBodyPart);  // add the text part
        multipart.addBodyPart(attachmentBodyPart); // add the attachement part

        msg.setContent(multipart);


        Transport.send(msg);
    } catch (MessagingException e) {
        LOGGER.log(Level.SEVERE,"Error while sending email",e);
    }

Update :

If you want to send a mail as an html content formated you have to do

    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setContent(content, "text/html");

So basically setText is for raw text and will be well display on every server email including gmail, setContent is more for an html template and if you content is formatted as html it will maybe also works in gmail

Can lambda functions be templated?

In C++20 this is possible using the following syntax:

auto lambda = []<typename T>(T t){
    // do something
};

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

How do I remove an item from a stl vector with a certain value?

Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.

Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html

std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2

Thanks to Jim Buck for pointing out my error.

Error: request entity too large

In my case it was not enough to add these lines :

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

I tried adding the parameterLimit option on urlencoded function as the documentation says and error no longer appears.

The parameterLimit option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to 1000.

Try with this code:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

How to delete specific characters from a string in Ruby?

For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.

text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04

OR, AND Operator

There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...

cond1 && cond2 && cond3

If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...

cond1 || cond2 || cond3

If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.

The bitwise counterparts, & and | are not escaping.

Hope that helps.

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

ViewBag, ViewData and TempData

ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:

Similarities between ViewBag & ViewData :

  • Helps to maintain data when you move from controller to view.
  • Used to pass data from controller to corresponding view.
  • Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}


public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

@ViewBag.Name 
@ViewData["Name"] 

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}

The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

How to make GREP select only numeric values?

No need to used grep here, Try this:

df . -B MB | tail -1 | awk {'print substr($5, 1, length($5)-1)'}

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

How do I increase modal width in Angular UI Bootstrap?

When we open a modal it accept size as a paramenter:

Possible values for it size: sm, md, lg

$scope.openModal = function (size) {
var modal = $modal.open({
      size: size,
      templateUrl: "/app/user/welcome.html",
      ...... 
      });
}

HTML:

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('sm')">Small Modal</button>

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('md')">Medium Modal</button>

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('lg')">Large Modal</button>

If you want any specific size, add style on model HTML:

<style>.modal-dialog {width: 500px;} </style>

How to convert this var string to URL in Swift

In swift 3 use:

let url = URL(string: "Whatever url you have(eg: https://google.com)")

Load image from url

Try this:

InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Response.Redirect to new window

This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?

Launch Android application without main Activity and start Service on launching application

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Compile a DLL in C/C++, then call it from another program

The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.

You have two options to use a dll

  • Either use a lib file to link the symbols -- compile time dynamic linking
  • Use LoadLibrary() or some suitable function to load the library, retrieve a function pointer (GetProcAddress) and call it -- runtime dynamic linking

Exporting classes will not work if you follow the second method though.

How would you count occurrences of a string (actually a char) within a string?

public static int GetNumSubstringOccurrences(string text, string search)
{
    int num = 0;
    int pos = 0;

    if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(search))
    {
        while ((pos = text.IndexOf(search, pos)) > -1)
        {
            num ++;
            pos += search.Length;
        }
    }
    return num;
}

Can MySQL convert a stored UTC time to local timezone?

I propose to use

SET time_zone = 'proper timezone';

being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.

Custom format for time command

The accepted answer gives me this output

# bash date.sh
Time in seconds: 51
date.sh: line 12: unexpected EOF while looking for matching `"'
date.sh: line 21: syntax error: unexpected end of file

This is how I solved the issue

#!/bin/bash

date1=$(date --date 'now' +%s) #date since epoch in seconds at the start of script
somecommand
date2=$(date --date 'now' +%s) #date since epoch in seconds at the end of script
difference=$(echo "$((date2-$date1))") # difference between two values
date3=$(echo "scale=2 ; $difference/3600" | bc) # difference/3600 = seconds in hours
echo SCRIPT TOOK $date3 HRS TO COMPLETE # 3rd variable for a pretty output.

How to change option menu icon in the action bar?

This works properly in my case:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),
                                              R.drawable.change_pass);
toolbar.setOverflowIcon(drawable);

How to run shell script file using nodejs?

Also, you can use shelljs plugin. It's easy and it's cross-platform.

Install command:

npm install [-g] shelljs

What is shellJS

ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!

An example of how it works:

var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

Also, you can use from the command line:

$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Name does not exist in the current context

I also faced a similar issue, the problem was the form was inside a folder and the file .aspx.designer.cs I had the namespace referencing specifically to that directory; which caused the error to appear in several components:

El nombre no existe en el contexto actual

This in your case, a possible solution is to leave the namespace line of the Members_Jobs.aspx.designer.cs file specified globally, ie change this

namespace stman.Members {

For this

namespace stman {

It's what helped me solve the problem.

I hope to be helpful

SELECT where row value contains string MySQL

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

How to prevent a dialog from closing when a button is clicked

This code will work for you, because i had a simmilar problem and this worked for me. :)

1- Override Onstart() method in your fragment-dialog class.

@Override
public void onStart() {
    super.onStart();
    final AlertDialog D = (AlertDialog) getDialog();
    if (D != null) {
        Button positive = (Button) D.getButton(Dialog.BUTTON_POSITIVE);
        positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (edittext.equals("")) {
   Toast.makeText(getActivity(), "EditText empty",Toast.LENGTH_SHORT).show();
                } else {
                D.dismiss(); //dissmiss dialog
                }
            }
        });
    }
}

PHP file_get_contents() and setting request headers

Yes.

When calling file_get_contents on a URL, one should use the stream_create_context function, which is fairly well documented on php.net.

This is more or less exactly covered on the following page at php.net in the user comments section: http://php.net/manual/en/function.stream-context-create.php

MySQL vs MySQLi when using PHP

I have abandoned using mysqli. It is simply too unstable. I've had queries that crash PHP using mysqli but work just fine with the mysql package. Also mysqli crashes on LONGTEXT columns. This bug has been raised in various forms since at least 2005 and remains broken. I'd honestly like to use prepared statements but mysqli just isn't reliable enough (and noone seems to bother fixing it). If you really want prepared statements go with PDO.

Define a fixed-size list in Java

Create an array of size 100. If you need the List interface, then call Arrays.asList on it. It'll return a fixed-size list backed by the array.

How does Access-Control-Allow-Origin header work?

1. A client downloads javascript code MyCode.js from http://siteA - the origin.

The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)

2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.

Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.

How can I change the Y-axis figures into percentages in a barplot?

ggplot2 and scales packages can do that:

y <- c(12, 20)/100
x <- c(1, 2)

library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)

It seems like the stat() option has been taken off, causing the error message. Try this:

library(scales)

myplot <- ggplot(mtcars, aes(factor(cyl))) + 
          geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=percent)

myplot

SQL Server - Create a copy of a database table and place it in the same database?

If you want to duplicate the table with all its constraints & keys follows this below steps:

  1. Open the database in SQL Management Studio.
  2. Right-click on the table that you want to duplicate.
  3. Select Script Table as -> Create to -> New Query Editor Window. This will generate a script to recreate the table in a new query window.
  4. Change the table name and relative keys & constraints in the script.
  5. Execute the script.

Then for copying the data run this below script:

SET IDENTITY_INSERT DuplicateTable ON

INSERT Into DuplicateTable ([Column1], [Column2], [Column3], [Column4],... ) 
SELECT [Column1], [Column2], [Column3], [Column4],... FROM MainTable

SET IDENTITY_INSERT DuplicateTable OFF

How to fully delete a git repository created with init?

You can create an alias for it. I am using ZSH shell with Oh-my-Zsh and here is an handy alias:

# delete and re-init git
# usage: just type 'gdelinit' in a local repository
alias gdelinit="trash .git && git init"

I am using Trash to trash the .git folder since using rm is really dangerous:

trash .git

Then I am re-initializing the git repo:

git init

Trigger a button click with JavaScript on the Enter key in a text box

This also might help, a small JavaScript function, which works fine:

<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }

function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script> 
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />

I know this question is solved, but I just found something, which can be helpful for others.

How to replace unicode characters in string with something else python?

Funny the answer is hidden in among the answers.

str.replace("•", "something") 

would work if you use the right semantics.

str.replace(u"\u2022","something") 

works wonders ;) , thnx to RParadox for the hint.

Adding horizontal spacing between divs in Bootstrap 3

Do you mean something like this? JSFiddle

Attribute used:

margin-left: 50px;

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

I run at this when I tried to add privileges to performance_schema, which is mysql bug http://bugs.mysql.com/bug.php?id=44898 (workaround to add --single-transaction).

set initial viewcontroller in appdelegate - swift

if you are not using storyboard, you can try this

var window: UIWindow?
var initialViewController :UIViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    initialViewController  = MainViewController(nibName:"MainViewController",bundle:nil)

    let frame = UIScreen.mainScreen().bounds
    window = UIWindow(frame: frame)

    window!.rootViewController = initialViewController
    window!.makeKeyAndVisible()

    return true
}

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

How to use pip with python 3.4 on windows?

"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."

Have you tried it?

Visual Studio 2017 errors on standard headers

I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.

I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.

jQuery: click function exclude children.

I'm using following markup and had encoutered the same problem:

<ul class="nav">
    <li><a href="abc.html">abc</a></li>
    <li><a href="def.html">def</a></li>
</ul>

Here I have used the following logic:

$(".nav > li").click(function(e){
    if(e.target != this) return; // only continue if the target itself has been clicked
    // this section only processes if the .nav > li itself is clicked.
    alert("you clicked .nav > li, but not it's children");
});

In terms of the exact question, I can see that working as follows:

$(".example").click(function(e){
   if(e.target != this) return; // only continue if the target itself has been clicked
   $(".example").fadeOut("fast");
});

or of course the other way around:

$(".example").click(function(e){
   if(e.target == this){ // only if the target itself has been clicked
       $(".example").fadeOut("fast");
   }
});

Hope that helps.

What's a quick way to comment/uncomment lines in Vim?

Use Control-V to select rectangles of text: go to the first # character, type Ctrl+V, move right once, and then down, up to the end of the comments. Now type x: you're deleting all the # characters followed by one space.

Sync data between Android App and webserver

I'll try to answer all your questions by addressing the larger question: How can I sync data between a webserver and an android app?


Syncing data between your webserver and an android app requires a couple of different components on your android device.

Persistent Storage:

This is how your phone actually stores the data it receives from the webserver. One possible method for accomplishing this is writing your own custom ContentProvider backed by a Sqlite database. A decent tutorial for a content provider can be found here: http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

A ContentProvider defines a consistent interface to interact with your stored data. It could also allow other applications to interact with your data if you wanted. Behind your ContentProvider could be a Sqlite database, a Cache, or any arbitrary storage mechanism.

While I would certainly recommend using a ContentProvider with a Sqlite database you could use any java based storage mechanism you wanted.

Data Interchange Format:

This is the format you use to send the data between your webserver and your android app. The two most popular formats these days are XML and JSON. When choosing your format, you should think about what sort of serialization libraries are available. I know off-hand that there's a fantastic library for json serialization called gson: https://github.com/google/gson, although I'm sure similar libraries exist for XML.

Synchronization Service

You'll want some sort of asynchronous task which can get new data from your server and refresh the mobile content to reflect the content of the server. You'll also want to notify the server whenever you make local changes to content and want to reflect those changes. Android provides the SyncAdapter pattern as a way to easily solve this pattern. You'll need to register user accounts, and then Android will perform lots of magic for you, and allow you to automatically sync. Here's a good tutorial: http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-1/


As for how you identify if the records are the same, typically you'll create items with a unique id which you store both on the android device and the server. You can use that to make sure you're referring to the same reference. Furthermore, you can store column attributes like "updated_at" to make sure that you're always getting the freshest data, or you don't accidentally write over newly written data.

Dynamically add script tag with src that may include document.write

Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.

Inserting Dynamic Javascript the right way

eval command in Bash and its typical uses

Update: Some people say one should -never- use eval. I disagree. I think the risk arises when corrupt input can be passed to eval. However there are many common situations where that is not a risk, and therefore it is worth knowing how to use eval in any case. This stackoverflow answer explains the risks of eval and alternatives to eval. Ultimately it is up to the user to determine if/when eval is safe and efficient to use.


The bash eval statement allows you to execute lines of code calculated or acquired, by your bash script.

Perhaps the most straightforward example would be a bash program that opens another bash script as a text file, reads each line of text, and uses eval to execute them in order. That's essentially the same behavior as the bash source statement, which is what one would use, unless it was necessary to perform some kind of transformation (e.g. filtering or substitution) on the content of the imported script.

I rarely have needed eval, but I have found it useful to read or write variables whose names were contained in strings assigned to other variables. For example, to perform actions on sets of variables, while keeping the code footprint small and avoiding redundancy.

eval is conceptually simple. However, the strict syntax of the bash language, and the bash interpreter's parsing order can be nuanced and make eval appear cryptic and difficult to use or understand. Here are the essentials:

  1. The argument passed to eval is a string expression that is calculated at runtime. eval will execute the final parsed result of its argument as an actual line of code in your script.

  2. Syntax and parsing order are stringent. If the result isn't an executable line of bash code, in scope of your script, the program will crash on the eval statement as it tries to execute garbage.

  3. When testing you can replace the eval statement with echo and look at what is displayed. If it is legitimate code in the current context, running it through eval will work.


The following examples may help clarify how eval works...

Example 1:

eval statement in front of 'normal' code is a NOP

$ eval a=b
$ eval echo $a
b

In the above example, the first eval statements has no purpose and can be eliminated. eval is pointless in the first line because there is no dynamic aspect to the code, i.e. it already parsed into the final lines of bash code, thus it would be identical as a normal statement of code in the bash script. The 2nd eval is pointless too, because, although there is a parsing step converting $a to its literal string equivalent, there is no indirection (e.g. no referencing via string value of an actual bash noun or bash-held script variable), so it would behave identically as a line of code without the eval prefix.



Example 2:

Perform var assignment using var names passed as string values.

$ key="mykey"
$ val="myval"
$ eval $key=$val
$ echo $mykey
myval

If you were to echo $key=$val, the output would be:

mykey=myval

That, being the final result of string parsing, is what will be executed by eval, hence the result of the echo statement at the end...



Example 3:

Adding more indirection to Example 2

$ keyA="keyB"
$ valA="valB"
$ keyB="that"
$ valB="amazing"
$ eval eval \$$keyA=\$$valA
$ echo $that
amazing

The above is a bit more complicated than the previous example, relying more heavily on the parsing-order and peculiarities of bash. The eval line would roughly get parsed internally in the following order (note the following statements are pseudocode, not real code, just to attempt to show how the statement would get broken down into steps internally to arrive at the final result).

 eval eval \$$keyA=\$$valA  # substitution of $keyA and $valA by interpreter
 eval eval \$keyB=\$valB    # convert '$' + name-strings to real vars by eval
 eval $keyB=$valB           # substitution of $keyB and $valB by interpreter
 eval that=amazing          # execute string literal 'that=amazing' by eval

If the assumed parsing order doesn't explain what eval is doing enough, the third example may describe the parsing in more detail to help clarify what is going on.



Example 4:

Discover whether vars, whose names are contained in strings, themselves contain string values.

a="User-provided"
b="Another user-provided optional value"
c=""

myvarname_a="a"
myvarname_b="b"
myvarname_c="c"

for varname in "myvarname_a" "myvarname_b" "myvarname_c"; do
    eval varval=\$$varname
    if [ -z "$varval" ]; then
        read -p "$varname? " $varname
    fi
done

In the first iteration:

varname="myvarname_a"

Bash parses the argument to eval, and eval sees literally this at runtime:

eval varval=\$$myvarname_a

The following pseudocode attempts to illustrate how bash interprets the above line of real code, to arrive at the final value executed by eval. (the following lines descriptive, not exact bash code):

1. eval varval="\$" + "$varname"      # This substitution resolved in eval statement
2. .................. "$myvarname_a"  # $myvarname_a previously resolved by for-loop
3. .................. "a"             # ... to this value
4. eval "varval=$a"                   # This requires one more parsing step
5. eval varval="User-provided"        # Final result of parsing (eval executes this)

Once all the parsing is done, the result is what is executed, and its effect is obvious, demonstrating there is nothing particularly mysterious about eval itself, and the complexity is in the parsing of its argument.

varval="User-provided"

The remaining code in the example above simply tests to see if the value assigned to $varval is null, and, if so, prompts the user to provide a value.

Command to change the default home directory of a user

Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.

Change the user's home directory:

usermod -d /newhome/username username

usermod is the command to edit an existing user.
-d (abbreviation for --home) will change the user's home directory.

Change the user's home directory + Move the contents of the user's current directory:

usermod -m -d /newhome/username username

-m (abbreviation for --move-home) will move the content from the user's current directory to the new directory.

Application not picking up .css file (flask/python)

Still having problems after following the solution provided by codegeek:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}"> ?

In Google Chrome pressing the reload button (F5) will not reload the static files. If you have followed the accepted solution but still don't see the changes you have made to CSS, then press ctrl + shift + R to ignore cached files and reload the static files.

In Firefox pressing the reload button appears to reload the static files.

In Edge pressing the refresh button does not reload the static file. Pressing ctrl + shift + R is supposed to ignore cached files and reload the static files. However this does not work on my computer.

How to empty a list?

list = []

will reset list to an empty list.

Note that you generally should not shadow reserved function names, such as list, which is the constructor for a list object -- you could use lst or list_ instead, for instance.

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

javascript close current window

You cannot close a window with javascript that you did not open. It will not work in chrome or firefox.

See https://stackoverflow.com/a/19768082/2623781 for more information.

How do I start an activity from within a Fragment?

I done it, below code is working for me....

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);

        Button newPage = (Button)v.findViewById(R.id.click);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HomeActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }

and Please make sure that your destination activity should be register in Manifest.xml file,

but in my case all tabs are not shown in HomeActivity, is any solution for that ?

How to apply Hovering on html area tag?

You can use jQuery to achieve this

Example:

$(function () {
        $('.map').maphilight();
    });

Go through this LINK to know more.

If the above one doesnt work then go through this link.

EDIT :

Give same class to each area tag like class="mapping"

and try this below code

$('.mapping').mouseover(function() {
    alert($(this).attr('id'));
}).mouseout(function(){
    alert('Mouseout....');      
});

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.

Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.

Hope this helped. :)

"Press Any Key to Continue" function in C

You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.

In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:

#include <termios.h>

struct termios info;
tcgetattr(0, &info);          /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON;      /* disable canonical mode */
info.c_cc[VMIN] = 1;          /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0;         /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */

Now when you read from stdin (with getchar(), or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.

Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.

Trying to Validate URL Using JavaScript

Import in an npm package like

https://www.npmjs.com/package/valid-url

and use it to validate your url.

Best data type to store money values in MySQL

You can use DECIMAL or NUMERIC both are same

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL

i.e. DECIMAL(10,2)

Example settings

Good read

Converting HTML files to PDF

Did you try WKHTMLTOPDF?

It's a simple shell utility, an open source implementation of WebKit. Both are free.

We've set a small tutorial here

EDIT( 2017 ):

If it was to build something today, I wouldn't go that route anymore.
But would use http://pdfkit.org/ instead.
Probably stripping it of all its nodejs dependencies, to run in the browser.

Why should Java 8's Optional not be used in arguments

This is because we have different requirements to an API user and an API developer.

A developer is responsible for providing a precise specification and a correct implementation. Therefore if the developer is already aware that an argument is optional the implementation must deal with it correctly, whether it being a null or an Optional. The API should be as simple as possible to the user, and null is the simplest.

On the other hand, the result is passed from the API developer to the user. However the specification is complete and verbose, there is still a chance that the user is either unaware of it or just lazy to deal with it. In this case, the Optional result forces the user to write some extra code to deal with a possible empty result.

input[type='text'] CSS selector does not apply to default-type text inputs?

By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”

It is generally best to explicitly specify essential attributes such as type=text instead of defaulting them. The reason is that there is no simple reliable way to refer to the input elements with defaulted type attribute.

Fastest way to write huge data in text file Java

_x000D_
_x000D_
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
 * @author Naresh Bhabat_x000D_
 * _x000D_
Following  implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
 * ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
 *      for 10 threads:Total time required for reading and writing the text in_x000D_
 *         :seconds 349.317_x000D_
 * _x000D_
 *         For 100:Total time required for reading the text and writing   : seconds 464.042_x000D_
 * _x000D_
 *         For 1000 : Total time required for reading and writing text :466.538 _x000D_
 *         For 10000  Total time required for reading and writing in seconds 479.701_x000D_
 *_x000D_
 * _x000D_
 */_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
 static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
 static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
 static volatile RandomAccessFile fileToWrite;_x000D_
 static volatile RandomAccessFile file;_x000D_
 static volatile String fileContentsIter;_x000D_
 static volatile int position = 0;_x000D_
_x000D_
 public static void main(String[] args) throws IOException, InterruptedException {_x000D_
  long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
  try {_x000D_
   fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
   file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
   seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
  } catch (IOException e) {_x000D_
   // TODO Auto-generated catch block_x000D_
   e.printStackTrace();_x000D_
  }_x000D_
  Thread currentThread = Thread.currentThread();_x000D_
  System.out.println(currentThread.getName());_x000D_
  long currentTimeMillis2 = System.currentTimeMillis();_x000D_
  double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
  System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
 }_x000D_
_x000D_
 /**_x000D_
  * @throws IOException_x000D_
  * Something  asynchronously serious_x000D_
  */_x000D_
 public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
  ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
  while (true) {_x000D_
   String readLine = file.readLine();_x000D_
   if (readLine == null) {_x000D_
    break;_x000D_
   }_x000D_
   Runnable genuineWorker = new Runnable() {_x000D_
    @Override_x000D_
    public void run() {_x000D_
     // do hard processing here in this thread,i have consumed_x000D_
     // some time and eat some exception in write method._x000D_
     writeToFile(FILEPATH_WRITE, readLine);_x000D_
     // System.out.println(" :" +_x000D_
     // Thread.currentThread().getName());_x000D_
_x000D_
    }_x000D_
   };_x000D_
   executor.execute(genuineWorker);_x000D_
  }_x000D_
  executor.shutdown();_x000D_
  while (!executor.isTerminated()) {_x000D_
  }_x000D_
  System.out.println("Finished all threads");_x000D_
  file.close();_x000D_
  fileToWrite.close();_x000D_
 }_x000D_
_x000D_
 /**_x000D_
  * @param filePath_x000D_
  * @param data_x000D_
  * @param position_x000D_
  */_x000D_
 private static void writeToFile(String filePath, String data) {_x000D_
  try {_x000D_
   // fileToWrite.seek(position);_x000D_
   data = "\n" + data;_x000D_
   if (!data.contains("Randomization")) {_x000D_
    return;_x000D_
   }_x000D_
   System.out.println("Let us do something time consuming to make this thread busy"+(position++) + "   :" + data);_x000D_
   System.out.println("Lets consume through this loop");_x000D_
   int i=1000;_x000D_
   while(i>0){_x000D_
   _x000D_
    i--;_x000D_
   }_x000D_
   fileToWrite.write(data.getBytes());_x000D_
   throw new Exception();_x000D_
  } catch (Exception exception) {_x000D_
   System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
     + " \n This can be used for marking failure of the records");_x000D_
   //exception.printStackTrace();_x000D_
_x000D_
  }_x000D_
_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

How do you create a UIImage View Programmatically - Swift

Make sure to put:

imageView.translatesAutoresizingMaskIntoConstraints = false

Your image view will not show if you don't put that, don't ask me why.

When should I use Kruskal as opposed to Prim (and vice versa)?

One important application of Kruskal's algorithm is in single link clustering.

Consider n vertices and you have a complete graph.To obtain a k clusters of those n points.Run Kruskal's algorithm over the first n-(k-1) edges of the sorted set of edges.You obtain k-cluster of the graph with maximum spacing.

Indent multiple lines quickly in vi

  1. Press "SHIFT + v" to enter VISUAL LINE mode.
  2. Select the text you wish to indent but using either the cursor keys or the "j" and "k" keys.
  3. To indent right press "SHIFT + dot" (> character). To indent left press "SHIFT + comma" (< character).

Source: https://www.fir3net.com/UNIX/General/how-do-i-tab-multiple-lines-within-vi.html

How to plot a subset of a data frame in R?

This chunk should do the work:

plot(var2 ~ var1, data=subset(dataframe, var3 < 150))

My best regards.

How this works:

  1. Fisrt, we make selection using the subset function. Other possibilities can be used, like, subset(dataframe, var4 =="some" & var5 > 10). The "&" operator can be used to select all "some" and over 10. Also the operator "|" could be used to select "some" or "over 10".
  2. The next step is to plot the results of the subset, using tilde (~) operator, that just imply a formula, in this case var.response ~ var.independet. Of course this is not a formula, but works great for this case.

How can I convert a stack trace to a string?

Code from Apache Commons Lang 3.4 (JavaDoc):

public static String getStackTrace(final Throwable throwable) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw, true);
    throwable.printStackTrace(pw);
    return sw.getBuffer().toString();
}

The difference with the other answers is that it uses autoFlush on the PrintWriter.

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

How to split a string in Java

You can try like this also

 String concatenated_String="hi^Hello";

 String split_string_array[]=concatenated_String.split("\\^");

What is "origin" in Git?

origin is not the remote repository name. It is rather a local alias set as a key in place of the remote repository URL.

It avoids the user having to type the whole remote URL when prompting a push.

This name is set by default and for convention by Git when cloning from a remote for the first time.

This alias name is not hard coded and could be changed using following command prompt:

git remote rename origin mynewalias

Take a look at http://git-scm.com/docs/git-remote for further clarifications.

Transport security has blocked a cleartext HTTP

** Finally!!! Resolved App transport Security **

  1. Follow the follow the screen shot. Do it in Targets info Section.

enter image description here

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

error: (-215) !empty() in function detectMultiScale

I had the same problem with opencv-python and I used a virtual environment. If it's your case, you should find the xml files at:

/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml

/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml

Please be sure that you're using the absolute path. Otherwise, it won't work.

How to use global variable in node.js?

Global variables can be used in Node when used wisely.

Declaration of global variables in Node:

a = 10;
GLOBAL.a = 10;
global.a = 10;

All of the above commands the same actions with different syntaxes.

Use global variables when they are not about to be changed

Here an example of something that can happen when using global variables:

// app.js
a = 10; // no var or let or const means global

// users.js
app.get("/users", (req, res, next) => {
   res.send(a); // 10;
});

// permissions.js
app.get("/permissions", (req, res, next) => {
   a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
   res.send(a); // 11;
});

Explained:

Run users route first and receive 10;

Then run permissions route and receive 11;

Then run again the users route and receive 11 as well instead of 10;

Global variables can be overtaken!

Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.

When to use global vars?

As I said - when var is not about to be changed. Anyways it's more recommended that you will be using the process.env object from the config file.

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Using JavaMail with TLS

With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.

Here's an example using Google's SMTP servers:

Email email = EmailBuilder.startingBlank()
        .from("lollypop", "[email protected]")
        .to("C.Cane", "[email protected]")
        .withSubject("hey")
        .withPlainText("We should meet up!")
        .withHTMLText("<b>We should meet up!</b>")
        .buildEmail();

MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
        .buildMailer()
        .sendMail(email);

MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
        .buildMailer()
        .sendMail(email);

MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
        .buildMailer()
        .sendMail(email);

If you have two-factor login turned on, you need to generate an application specific password from your Google account.

How do you create a dropdownlist from an enum in ASP.NET MVC?

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

For example:

public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

You can then do this in your view:

@Html.EnumDropDownListFor(model => model.MyEnumProperty)

Hope this helps you!

**EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands.See Enum section in Microsoft's release notes for MVC 5.1.

Update: It does support the Display attribute [Display(Name = "Sample")] though, so one can use that.

[Update - just noticed this, and the code looks like an extended version of the code here: https://blogs.msdn.microsoft.com/stuartleeks/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums/, with a couple of additions. If so, attribution would seem fair ;-)]

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

Generating random numbers with normal distribution in Excel

Use the NORMINV function together with RAND():

=NORMINV(RAND(),10,7)

To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.


Sample output (column A), 500 numbers generated with this formula:

enter image description here

PHP-FPM doesn't write to error log

Check the Owner directory of "PHP-FPM"

You can do:

ls -lah /var/log/php-fpm/
chown -R webusr:webusr /var/log/php-fpm/
chmod -R 777 /var/log/php-fpm/

Use of def, val, and var in scala

To provide another perspective, "def" in Scala means something that will be evaluated each time when it's used, while val is something that is evaluated immediately and only once. Here, the expression def person = new Person("Kumar",12) entails that whenever we use "person" we will get a new Person("Kumar",12) call. Therefore it's natural that the two "person.age" are non-related.

This is the way I understand Scala(probably in a more "functional" manner). I'm not sure if

def defines a method
val defines a fixed value (which cannot be modified)
var defines a variable (which can be modified)

is really what Scala intends to mean though. I don't really like to think that way at least...

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

.NET unique object identifier

Checked out the ObjectIDGenerator class? This does what you're attempting to do, and what Marc Gravell describes.

The ObjectIDGenerator keeps track of previously identified objects. When you ask for the ID of an object, the ObjectIDGenerator knows whether to return the existing ID, or generate and remember a new ID.

The IDs are unique for the life of the ObjectIDGenerator instance. Generally, a ObjectIDGenerator life lasts as long as the Formatter that created it. Object IDs have meaning only within a given serialized stream, and are used for tracking which objects have references to others within the serialized object graph.

Using a hash table, the ObjectIDGenerator retains which ID is assigned to which object. The object references, which uniquely identify each object, are addresses in the runtime garbage-collected heap. Object reference values can change during serialization, but the table is updated automatically so the information is correct.

Object IDs are 64-bit numbers. Allocation starts from one, so zero is never a valid object ID. A formatter can choose a zero value to represent an object reference whose value is a null reference (Nothing in Visual Basic).

How to get build time stamp from Jenkins build variables?

If you want add a timestamp to every request from browser to jenkins server. You can refer to the jenkins crumb issuer mechanism, and you can hack the /scripts/hudson-behavior.js add modify here. so it will transform a timestamp to server.

    /**
     * Puts a hidden input field to the form so that the form submission will have the crumb value
     */
    appendToForm : function(form) {
        // add here. ..... you code
        if(this.fieldName==null)    return; // noop
        var div = document.createElement("div");
        div.innerHTML = "<input type=hidden name='"+this.fieldName+"' value='"+this.value+"'>";
        form.appendChild(div);
    }

Adding a default value in dropdownlist after binding with database

After data-binding, do this:

ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code

Or follow Brian's second suggestion if you want to do it in markup.

You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".

<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />

Method call if not null in C#

What you're looking for is the Null-Conditional (not "coalescing") operator: ?.. It's available as of C# 6.

Your example would be obj?.SomeMethod();. If obj is null, nothing happens. When the method has arguments, e.g. obj?.SomeMethod(new Foo(), GetBar()); the arguments are not evaluated if obj is null, which matters if evaluating the arguments would have side effects.

And chaining is possible: myObject?.Items?[0]?.DoSomething()

Split string into individual words Java

Use split() method

Eg:

String s = "I want to walk my dog";
String[] arr = s.split(" ");    

for ( String ss : arr) {
    System.out.println(ss);
}

Execute another jar in a Java program

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

java- reset list iterator to first element of the list

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)

Write applications in C or C++ for Android?

The Android NDK is a toolset that lets you implement parts of your app in native code, using languages such as C and C++. For certain types of apps, this can help you reuse code libraries written in those languages.

For more info on how to get started with native development, follow this link.

Sample applications can be found here.

How to insert DECIMAL into MySQL database

Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

Main differences between SOAP and RESTful web services in Java

SOAP

Simple Object Access Protocol (SOAP) is a standard, an XML language, defining a message architecture and message formats. It is used by Web services. It contains a description of the operations.

WSDL is an XML-based language for describing Web services and how to access them. It will run on SMTP, HTTP, FTP, etc. It requires middleware support and well-defined mechanism to define services like WSDL+XSD and WS-Policy. SOAP will return XML based data

REST

Representational State Transfer (RESTful) web services. They are second-generation Web services.

RESTful web services communicate via HTTP rather than SOAP-based services and do not require XML messages or WSDL service-API definitions. For REST middleware is not required, only HTTP support is needed. It is a WADL standard, REST can return XML, plain text, JSON, HTML, etc.

Tri-state Check box in HTML?

Like @Franz answer you can also do it with a select. For example:

<select>
  <option></option>
  <option value="Yes">Yes</option>
  <option value="No">No</option>
</select>

With this you can also give a concrete value that will be send with the form, I think that with javascript indeterminate version of checkbox, it will send the underline value of the checkbox.

At least, you can use it as a callback when javascript is disabled. For example, give it an id and in the load event change it to the javascript version of the checkbox with indeterminate status.

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

MATLAB error: Undefined function or method X for input arguments of type 'double'

The error code indicates the function definition cannot be found. Make sure you're calling the function from the same workspace as the divrat.m file is stored. And make sure divrat function is not a subfunction, it should be first function declaration in the file. You can also try to call the function from the same divrat.m file in order to see if the problem is with workspace selection or the function.

By the way, why didn't you simply say

s = sqrt(diag(C));

Wouldn't it be the same?

Nodemailer with Gmail and NodeJS

Same problem happened to me too. I tested my system on localhost then deployed to the server (which is located at different country) then when I try the system on production server I saw this error. I tried these to fix it:

  1. https://www.google.com/settings/security/lesssecureapps Enabled it but it was not my solution
  2. https://g.co/allowaccess I allowed access from outside for a limited time and this solved my problem.

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

Java Spring - How to use classpath to specify a file location?

Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean

<bean class="test.Test1">
        <property name="path" value="classpath:/test/test1.xml" />
    </bean>

and you get it in your bean as Resource:

public void setPath(Resource path) throws IOException {
    File file = path.getFile();
    System.out.println(file);
    }

output

D:\workspace1\spring\target\test-classes\test\test1.xml

Now you can use it in new FileReader(file)

Copy file from source directory to binary directory using CMake

If you want to put the content of example into install folder after build:

code/
  src/
  example/
  CMakeLists.txt

try add the following to your CMakeLists.txt:

install(DIRECTORY example/ DESTINATION example)

Python group by

The following function will quickly (no sorting required) group tuples of any length by a key having any index:

# given a sequence of tuples like [(3,'c',6),(7,'a',2),(88,'c',4),(45,'a',0)],
# returns a dict grouping tuples by idx-th element - with idx=1 we have:
# if merge is True {'c':(3,6,88,4),     'a':(7,2,45,0)}
# if merge is False {'c':((3,6),(88,4)), 'a':((7,2),(45,0))}
def group_by(seqs,idx=0,merge=True):
    d = dict()
    for seq in seqs:
        k = seq[idx]
        v = d.get(k,tuple()) + (seq[:idx]+seq[idx+1:] if merge else (seq[:idx]+seq[idx+1:],))
        d.update({k:v})
    return d

In the case of your question, the index of key you want to group by is 1, therefore:

group_by(input,1)

gives

{'ETH': ('5238761','5349618','962142','7795297','7341464','5594916','1550003'),
 'KAT': ('11013331', '9843236'),
 'NOT': ('9085267', '11788544')}

which is not exactly the output you asked for, but might as well suit your needs.

There is no tracking information for the current branch

You could specify what branch you want to pull:

git pull origin master

Or you could set it up so that your local master branch tracks github master branch as an upstream:

git branch --set-upstream-to=origin/master master
git pull

This branch tracking is set up for you automatically when you clone a repository (for the default branch only), but if you add a remote to an existing repository you have to set up the tracking yourself. Thankfully, the advice given by git makes that pretty easy to remember how to do.

How to pass command line arguments to a rake task

I use a regular ruby argument in the rake file:

DB = ARGV[1]

then I stub out the rake tasks at the bottom of the file (since rake will look for a task based on that argument name).

task :database_name1
task :database_name2

command line:

rake mytask db_name

this feels cleaner to me than the var=foo ENV var and the task args[blah, blah2] solutions.
the stub is a little jenky, but not too bad if you just have a few environments that are a one-time setup

Assign pandas dataframe column dtypes

you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs) and pass in a dictionary with the dtypes you want to dtype

here's an example:

import pandas as pd
wheel_number = 5
car_name = 'jeep'
minutes_spent = 4.5

# set the columns
data_columns = ['wheel_number', 'car_name', 'minutes_spent']

# create an empty dataframe
data_df = pd.DataFrame(columns = data_columns)
df_temp = pd.DataFrame([[wheel_number, car_name, minutes_spent]],columns = data_columns)
data_df = data_df.append(df_temp, ignore_index=True) 

In [11]: data_df.dtypes
Out[11]:
wheel_number     float64
car_name          object
minutes_spent    float64
dtype: object

data_df = data_df.astype(dtype= {"wheel_number":"int64",
        "car_name":"object","minutes_spent":"float64"})

now you can see that it's changed

In [18]: data_df.dtypes
Out[18]:
wheel_number       int64
car_name          object
minutes_spent    float64

How do I parse a URL into hostname and path in javascript?

The modern way:

new URL("http://example.com/aa/bb/")

Returns an object with properties hostname and pathname, along with a few others.

The first argument is a relative or absolute URL; if it's relative, then you need to specify the second argument (the base URL). For example, for a URL relative to the current page:

new URL("/aa/bb/", location)

In addition to browsers, this API is also available in Node.js since v7, through require('url').URL.

How can I convert the "arguments" object to an array in JavaScript?

If you're using jQuery, the following is a good deal easier to remember in my opinion:

function sortArgs(){
  return $.makeArray(arguments).sort();
}

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Well, apparently I had to change my PUT calling function updateUser. I removed the @Consumes, the @RequestMapping and also added a @ResponseBody to the function. So my method looked like this:

@RequestMapping(value="/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void updateUser(@PathVariable int id, @RequestBody User temp){
    Set<User> set1= obj2.getUsers();
    for(User a:set1)
    {
        if(id==a.getId())
        {
            set1.remove(a);
            a.setId(temp.getId());
            a.setName(temp.getName());
            set1.add(a);
        }
    }
    Userlist obj3=new Userlist(set1);
    obj2=obj3;
}

And it worked!!! Thank you all for the response.

How to catch a specific SqlException error?

Sort of, kind of. See Cause and Resolution of Database Engine Errors

class SqllErrorNumbers
{ 
   public const int BadObject = 208;
   public const int DupKey = 2627;
}

try
{
   ...
}
catch(SqlException sex)
{
   foreach(SqlErrorCode err in sex.Errors)
   {
      switch (err.Number)
      {
      case SqlErrorNumber.BadObject:...
      case SqllErrorNumbers.DupKey: ...
      }
   }
}

The problem though is that a good DAL layer would us TRY/CATCH inside the T-SQL (stored procedures), with a pattern like Exception handling and nested transactions. Alas a T-SQL TRY/CATCH block cannot raise the original error code, will have to raise a new error, with code above 50000. This makes client side handling a problem. In the next version of SQL Server there is a new THROW construct that allow to re-raise the original exception from T-SQL catch blocks.

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

Imitating a blink tag with CSS3 animations

I'm going to hell for this :

=keyframes($name)
  @-webkit-keyframes #{$name}
    @content
  @-moz-keyframes #{$name}
    @content
  @-ms-keyframes #{$name}
    @content
  @keyframes #{$name}
    @content


+keyframes(blink)
  25%
    zoom: 1
    opacity: 1

  65%
    opacity: 1 

  66%
    opacity: 0

  100%
    opacity: 0

body
  font-family: sans-serif
  font-size: 4em
  background: #222
  text-align: center

  .blink
    color: rgba(#fff, 0.9)
    +animation(blink 1s 0s reverse infinite)
    +transform(translateZ(0))

.table
  display: table
  height: 5em
  width: 100%
  vertical-align: middle

  .cell
    display: table-cell
    width: 100%
    height: 100%
    vertical-align: middle

http://codepen.io/anon/pen/kaGxC (sass with bourbon)

write newline into a file

Files.write(Paths.get(filepath),texttobewrittentofile,StandardOpenOption.APPEND ,StandardOpenOption.CREATE);    

This creates a file, if it does not exist If files exists, it is uses the existing file and text is appended If you want everyline to be written to the next line add lineSepartor for newline into file.

String texttobewrittentofile = text + System.lineSeparator();

Threading pool similar to the multiprocessing Pool?

Here's the result I finally ended up using. It's a modified version of the classes by dgorissen above.

File: threadpool.py

from queue import Queue, Empty
import threading
from threading import Thread


class Worker(Thread):
    _TIMEOUT = 2
    """ Thread executing tasks from a given tasks queue. Thread is signalable, 
        to exit
    """
    def __init__(self, tasks, th_num):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon, self.th_num = True, th_num
        self.done = threading.Event()
        self.start()

    def run(self):       
        while not self.done.is_set():
            try:
                func, args, kwargs = self.tasks.get(block=True,
                                                   timeout=self._TIMEOUT)
                try:
                    func(*args, **kwargs)
                except Exception as e:
                    print(e)
                finally:
                    self.tasks.task_done()
            except Empty as e:
                pass
        return

    def signal_exit(self):
        """ Signal to thread to exit """
        self.done.set()


class ThreadPool:
    """Pool of threads consuming tasks from a queue"""
    def __init__(self, num_threads, tasks=[]):
        self.tasks = Queue(num_threads)
        self.workers = []
        self.done = False
        self._init_workers(num_threads)
        for task in tasks:
            self.tasks.put(task)

    def _init_workers(self, num_threads):
        for i in range(num_threads):
            self.workers.append(Worker(self.tasks, i))

    def add_task(self, func, *args, **kwargs):
        """Add a task to the queue"""
        self.tasks.put((func, args, kwargs))

    def _close_all_threads(self):
        """ Signal all threads to exit and lose the references to them """
        for workr in self.workers:
            workr.signal_exit()
        self.workers = []

    def wait_completion(self):
        """Wait for completion of all the tasks in the queue"""
        self.tasks.join()

    def __del__(self):
        self._close_all_threads()


def create_task(func, *args, **kwargs):
    return (func, args, kwargs)

To use the pool

from random import randrange
from time import sleep

delays = [randrange(1, 10) for i in range(30)]

def wait_delay(d):
    print('sleeping for (%d)sec' % d)
    sleep(d)

pool = ThreadPool(20)
for i, d in enumerate(delays):
    pool.add_task(wait_delay, d)
pool.wait_completion()

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Simple function to sort an array of objects

var people = 
[{"name": 'a75',"item1": "false","item2":"false"}, 
{"name": 'z32',"item1": "true","item2":  "false"}, 
{"name": 'e77',"item1": "false","item2": "false"}]; 

function mycomparator(a,b) {   return parseInt(a.name) - parseInt(b.name);  } 
people.sort(mycomparator); 

something along the lines of this maybe (or as we used to say, this should work).

How do I initialize a TypeScript Object with a JSON-Object?

For simple objects, I like this method:

class Person {
  constructor(
    public id: String, 
    public name: String, 
    public title: String) {};

  static deserialize(input:any): Person {
    return new Person(input.id, input.name, input.title);
  }
}

var person = Person.deserialize({id: 'P123', name: 'Bob', title: 'Mr'});

Leveraging the ability to define properties in the constructor lets it be concise.

This gets you a typed object (vs all the answers that use Object.assign or some variant, which give you an Object) and doesn't require external libraries or decorators.

Replace a value if null or undefined in JavaScript

Here’s the JavaScript equivalent:

var i = null;
var j = i || 10; //j is now 10

Note that the logical operator || does not return a boolean value but the first value that can be converted to true.

Additionally use an array of objects instead of one single object:

var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''

That can be accessed by index.

In Perl, how can I read an entire file into a string?

I don't know if it's good practice, but I used to use this:

($a=<F>);

Checking for directory and file write permissions in .NET

according to this link: http://www.authorcode.com/how-to-check-file-permission-to-write-in-c/

it's easier to use existing class SecurityManager

string FileLocation = @"C:\test.txt";
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, FileLocation);
if (SecurityManager.IsGranted(writePermission))
{
  // you have permission
}
else
{
 // permission is required!
}

but it seems it's been obsoleted, it is suggested to use PermissionSet instead.

[Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework.  Please use the PermissionSet property of either AppDomain or Assembly instead.")]

How to initialize java.util.date to empty

Try initializing with null value.

private java.util.Date date2 = null;

Also private java.util.Date date2 = ""; will not work as "" is a string.

C# get string from textbox

if in string:

string yourVar = yourTextBoxname.Text;

if in numbers:

int yourVar = int.Parse(yourTextBoxname.Text);

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

What do *args and **kwargs mean?

Just to clarify how to unpack the arguments, and take care of missing arguments etc.

def func(**keyword_args):
  #-->keyword_args is a dictionary
  print 'func:'
  print keyword_args
  if keyword_args.has_key('b'): print keyword_args['b']
  if keyword_args.has_key('c'): print keyword_args['c']

def func2(*positional_args):
  #-->positional_args is a tuple
  print 'func2:'
  print positional_args
  if len(positional_args) > 1:
    print positional_args[1]

def func3(*positional_args, **keyword_args):
  #It is an error to switch the order ie. def func3(**keyword_args, *positional_args):
  print 'func3:'
  print positional_args
  print keyword_args

func(a='apple',b='banana')
func(c='candle')
func2('apple','banana')#It is an error to do func2(a='apple',b='banana')
func3('apple','banana',a='apple',b='banana')
func3('apple',b='banana')#It is an error to do func3(b='banana','apple')

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

PHP preg_match - only allow alphanumeric strings and - _ characters

Why to use regex? PHP has some built in functionality to do that

<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols

Adjusting and image Size to fit a div (bootstrap)

If any of you looking for Bootstrap-4. Here it is

<div class="row no-gutters">
    <div class="col-10">
        <img class="img-fluid" src="/resources/img1.jpg" alt="">
    </div>
</div>

'str' object has no attribute 'decode'. Python 3 error?

For Python3

html = """\\u003Cdiv id=\\u0022contenedor\\u0022\\u003E \\u003Ch2 class=\\u0022text-left m-b-2\\u0022\\u003EInformaci\\u00f3n del veh\\u00edculo de patente AA345AA\\u003C\\/h2\\u003E\\n\\n\\n\\n \\u003Cdiv class=\\u0022panel panel-default panel-disabled m-b-2\\u0022\\u003E\\n \\u003Cdiv class=\\u0022panel-body\\u0022\\u003E\\n \\u003Ch2 class=\\u0022table_title m-b-2\\u0022\\u003EInformaci\\u00f3n del Registro Automotor\\u003C\\/h2\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ERegistro Seccional\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL N\\u00b0 1\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDirecci\\u00f3n\\u003C\\/label\\u003E\\n \\u003Cp\\u003EMAESTRO ANGEL D\\u0027ELIA 766\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EPiso\\u003C\\/label\\u003E\\n \\u003Cp\\u003EPB\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDepartamento\\u003C\\/label\\u003E\\n \\u003Cp\\u003E-\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EC\\u00f3digo postal\\u003C\\/label\\u003E\\n \\u003Cp\\u003E1663\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ELocalidad\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EProvincia\\u003C\\/label\\u003E\\n \\u003Cp\\u003EBUENOS AIRES\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ETel\\u00e9fono\\u003C\\/label\\u003E\\n \\u003Cp\\u003E(11)46646647\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EHorario\\u003C\\/label\\u003E\\n \\u003Cp\\u003E08:30 a 12:30\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003C\\/div\\u003E\\n\\u003C\\/div\\u003E \\n\\n\\u003Cp class=\\u0022text-center m-t-3 m-b-1 hidden-print\\u0022\\u003E\\n \\u003Ca href=\\u0022javascript:window.print();\\u0022 class=\\u0022btn btn-default\\u0022\\u003EImprim\\u00ed la consulta\\u003C\\/a\\u003E \\u0026nbsp; \\u0026nbsp;\\n \\u003Ca href=\\u0022\\u0022 class=\\u0022btn use-ajax btn-primary\\u0022\\u003EHacer otra consulta\\u003C\\/a\\u003E\\n\\u003C\\/p\\u003E\\n\\u003C\\/div\\u003E"""
print(html.replace("\\/", "/").encode().decode('unicode_escape'))

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

How do I activate a Spring Boot profile when running from IntelliJ?

Try add this command in your build.gradle

enter image description here

So for running configure that shape:

enter image description here

pass post data with window.location.href

Add a form to your HTML, something like this:

<form style="display: none" action="/the/url" method="POST" id="form">
  <input type="hidden" id="var1" name="var1" value=""/>
  <input type="hidden" id="var2" name="var2" value=""/>
</form>

and use JQuery to fill these values (of course you can also use javascript to do something similar)

$("#var1").val(value1);
$("#var2").val(value2);

Then finally submit the form

$("#form").submit();

on the server side you should be able to get the data you sent by checking var1 and var2, how to do this depends on what server-side language you are using.

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

how to POST/Submit an Input Checkbox that is disabled?

Since:

  • setting readonly attribute to checkbox isn't valid according to HTML specification,
  • using hidden element to submit value isn't very pretty way and
  • setting onclick JavaScript that prevents from changing value isn't very nice too

I'm gonna offer you another possibility:

Set your checkbox as disabled as normal. And before the form is submitted by user enable this checkbox by JavaScript.

<script>
    function beforeSumbit() {
        var checkbox = document.getElementById('disabledCheckbox');
        checkbox.disabled = false;
    }
</script>
...
<form action="myAction.do" method="post" onSubmit="javascript: beforeSubmit();">
    <checkbox name="checkboxName" value="checkboxValue" disabled="disabled" id="disabledCheckbox" />
    <input type="submit />
</form>

Because the checkbox is enabled before the form is submitted, its value is posted in common way. Only thing that isn't very pleasant about this solution is that this checkbox becomes enabled for a while and that can be seen by users. But it's just a detail I can live with.

The easiest way to transform collection to array?

Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Just a quick update for anyone else who might run into this issue. As of today, changing the %userprofile%\documents\iisexpress\config\applicationhost.config does NOT work any longer (this was working fine until now, not sure if this is due to a Windows update). After hours of frustration, I changed the web.config to add these handlers to system.webserver to get it to work:

<handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

How to pass boolean values to a PowerShell script from a command prompt

This is an older question, but there is actually an answer to this in the PowerShell documentation. I had the same problem, and for once RTFM actually solved it. Almost.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe

Documentation for the -File parameter states that "In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}"

I had to write it like this:

PowerShell.Exe -File MyFile.ps1 {-SomeBoolParameter:False}

So no '$' before the true/false statement, and that worked for me, on PowerShell 4.0

Recommended Fonts for Programming?

I use Bitstream Vera Sans Mono, but you need to activate ClearType to get it readable .

I like the 'Illegal1 = O0' readablility test, mentioned earlier in this thread, thanks for that.

Is bool a native C type?

stdbool.h defines macros true and false, but remember they are defined to be 1 and 0.

That is why sizeof(true) is 4.

Disabling submit button until all fields have values

All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.

var $input = $('input:text'),
    $register = $('#register');    
$register.attr('disabled', true);

$input.keyup(function() {
    var trigger = false;
    $input.each(function() {
        if (!$(this).val()) {
            trigger = true;
        }
    });
    trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});

Check working example at http://jsfiddle.net/DKNhx/3/

Print a div using javascript in angularJS single page application

This is what worked for me in Chrome and Firefox! This will open the little print window and close it automatically once you've clicked print.

var printContents = document.getElementById('div-id-selector').innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no,top=50');
            popupWin.window.focus();
            popupWin.document.open();
            popupWin.document.write('<!DOCTYPE html><html><head><title>TITLE OF THE PRINT OUT</title>' 
                                    +'<link rel="stylesheet" type="text/css" href="app/directory/file.css" />' 
                                    +'</head><body onload="window.print(); window.close();"><div>' 
                                    + printContents + '</div></html>');
            popupWin.document.close();

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Controls in .NET are not generally thread safe. That means you shouldn't access a control from a thread other than the one where it lives. To get around this, you need to invoke the control, which is what your 2nd sample is attempting.

However, in your case all you've done is pass the long-running method back to the main thread. Of course, that's not really what you want to do. You need to rethink this a little so that all you're doing on the main thread is setting a quick property here and there.

How to select count with Laravel's fluent query builder?

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();

Online PHP syntax checker / validator

http://phpcodechecker.com/ performs syntax check and a custom check for common errors.

I'm a novice, but it helped me.

How do I return a proper success/error message for JQuery .ajax() using PHP?

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Additional fix, you should check whether the query succeed or not.

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

On the client side:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Hope it helps.

Best implementation for Key Value Pair Data Structure?

Use something like this:

class Tree < T > : Dictionary < T, IList< Tree < T > > >  
{  
}  

It's ugly, but I think it will give you what you want. Too bad KeyValuePair is sealed.

Batch program to to check if process exists

TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
  specific commands to perform if the process was not found
)
exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
  specific commands to perform if the process
  was not terminated because it was not found
)
exit

What is the format for the PostgreSQL connection string / URL?

host or hostname would be the i.p address of the remote server, or if you can access it over the network by computer name, that should work to.

Duplicating a MySQL table, indices, and data

Expanding on this answer one could use a stored procedure:

CALL duplicate_table('tableName');

Which will result in a duplicate table called tableName_20181022235959 If called when

SELECT NOW();

results:

2018-10-22 23:59:59

Implementation

DELIMITER $$
CREATE PROCEDURE duplicate_table(IN tableName VARCHAR(255))
  BEGIN
    DECLARE schemaName VARCHAR(255) DEFAULT SCHEMA();
    DECLARE today VARCHAR(14) DEFAULT REPLACE(REPLACE(REPLACE(NOW(), '-', ''), ' ', ''), ':', ''); -- update @ year 10000
    DECLARE backupTableName VARCHAR(255) DEFAULT CONCAT(tableName, '_', today);

    IF fn_table_exists(schemaName, tableName)
      THEN
        CALL statement(CONCAT('CREATE TABLE IF NOT EXISTS ', backupTableName,' LIKE ', tableName));
        CALL statement(CONCAT('INSERT INTO ', backupTableName,' SELECT * FROM ', tableName));
        CALL statement(CONCAT('CHECKSUM TABLE ', backupTableName,', ', tableName));
      ELSE
        SELECT CONCAT('ERROR: Table "', tableName, '" does not exist in the schema "', schemaName, '".') AS ErrorMessage;
      END IF;
  END $$
DELIMITER ;

DELIMITER $$
CREATE FUNCTION fn_table_exists(schemaName VARCHAR(255), tableName VARCHAR(255))
  RETURNS TINYINT(1)
  BEGIN
    DECLARE totalTablesCount INT DEFAULT (
      SELECT COUNT(*)
      FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = schemaName COLLATE utf8_general_ci)
        AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
    );
    RETURN IF(
      totalTablesCount > 0,
      TRUE,
      FALSE
    );
  END $$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
  BEGIN
      SET @dynamic_statement := dynamic_statement;
      PREPARE prepared_statement FROM @dynamic_statement;
      EXECUTE prepared_statement;
      DEALLOCATE PREPARE prepared_statement;
  END $$
DELIMITER ;

onchange event on input type=range is not triggering in firefox while dragging

For a good cross-browser behavior, and understandable code, best is to use the onchange attribute in combination of a form:

_x000D_
_x000D_
function showVal(){
  valBox.innerHTML = inVal.value;
}
_x000D_
<form onchange="showVal()">
  <input type="range" min="5" max="10" step="1" id="inVal">
</form>

<span id="valBox"></span>
_x000D_
_x000D_
_x000D_

The same using oninput, the value is changed directly.

_x000D_
_x000D_
function showVal(){
  valBox.innerHTML = inVal.value;
}
_x000D_
<form oninput="showVal()">
  <input type="range" min="5" max="10" step="1" id="inVal">
</form>

<span id="valBox"></span>
_x000D_
_x000D_
_x000D_

Android offline documentation and sample codes

At first choose your API level from the following links:

API Level 17: http://dl-ssl.google.com/android/repository/docs-17_r02.zip

API Level 18: http://dl-ssl.google.com/android/repository/docs-18_r02.zip

API Level 19: http://dl-ssl.google.com/android/repository/docs-19_r02.zip

Android-L API doc: http://dl-ssl.google.com/android/repository/docs-L_r01.zip

API Level 24 doc: https://dl-ssl.google.com/android/repository/docs-24_r01.zip

download and extract it in your sdk driectory.



In your eclipse IDE:

at project -> properties -> java build path -> Libraries -> Android x.x -> android.jar -> javadoc

press edit in right:

javadoc URL -> Browse

select "docs/reference/" in archive extracted directory

press validate... to validate this javadoc.



In your IntelliJ IDEA

at file -> Project Structure Select SDKs from left panel -> select your sdk from middle panel -> in right panel go to Documentation Paths tab so click plus icon and select docs/reference/ in archive extracted directory.


enjoy the offline javadoc...

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Vue.js toggle class on click

This answer relevant for Vue.js version 2

<th 
  class="initial " 
  v-on:click="myFilter"
  v-bind:class="{ active: isActive }"
>
  <span class="wkday">M</span>
</th>

The rest of the answer by Douglas is still applicable (setting up the new Vue instance with isActive: false, etc).

Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers

How do I change the default schema in sql developer?

After you granted the permissions to the specified user you have to do this at filtering:

First step:

First Step to change default Tables

Second step:

Second Step to change default Tables

Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).

Find by key deep in a nested array

I've created library for this purpose: https://github.com/dominik791/obj-traverse

You can use findFirst() method like this:

var foundObject = findFirst(rootObject, 'options', { 'id': '1' });

And now foundObject variable stores a reference to the object that you're looking for.

Python time measure function

There is an easy tool for timing. https://github.com/RalphMao/PyTimer

It can work like a decorator:

from pytimer import Timer
@Timer(average=False)      
def matmul(a,b, times=100):
    for i in range(times):
        np.dot(a,b)        

Output:

matmul:0.368434
matmul:2.839355

It can also work like a plug-in timer with namespace control(helpful if you are inserting it to a function which has a lot of codes and may be called anywhere else).

timer = Timer()                                           
def any_function():                                       
    timer.start()                                         

    for i in range(10):                                   

        timer.reset()                                     
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        timer.checkpoint('block1')                        

        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
        timer.checkpoint('block2')                        
        np.dot(np.ones((100,1000)), np.zeros((1000,1000)))

    for j in range(20):                                   
        np.dot(np.ones((100,1000)), np.zeros((1000,500)))
    timer.summary()                                       

for i in range(2):                                        
    any_function()                                        

Output:

========Timing Summary of Default Timer========
block2:0.065062
block1:0.032529
========Timing Summary of Default Timer========
block2:0.065838
block1:0.032891

Hope it will help

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

How to delete projects in Intellij IDEA 14?

Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like

'C:/xxxxxx/pom.xml' already exists in VFS

Here is what I found would work.

  1. Remove module
  2. File -> Invalidate Cache (at this point the Intelli IDEA wants to restart)
  3. Close project
  4. Delete the folder form system explorer.
  5. Now you can create a project with same name as before.

Plot a bar using matplotlib using a dictionary

The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label) where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label does the same work as xticks(). One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label). For detailed information please refer the documentation.

import matplotlib.pyplot as plt

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())

#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()

enter image description here

Additionally the same plot can be generated without using range(). But the problem encountered was that tick_label just worked for the last plt.bar() call. Hence xticks() was used for labelling:

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()

enter image description here

AngularJS : Custom filters and ng-repeat

You can call more of 1 function filters in the same ng-repeat filter

<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">

Use -notlike to filter out multiple strings in PowerShell

Easiest way I find for multiple searches is to pipe them all (probably heavier CPU use) but for your example user:

Get-EventLog -LogName Security | where {$_.UserName -notlike "*user1"} |  where {$_.UserName -notlike "*user2"}

Python Checking a string's first and last character

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]
'"xxx'

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

How to get the pure text without HTML element using JavaScript?

This answer will work to get just the text for any HTML element.

This first parameter "node" is the element to get the text from. The second parameter is optional and if true will add a space between the text within elements if no space would otherwise exist there.

function getTextFromNode(node, addSpaces) {
    var i, result, text, child;
    result = '';
    for (i = 0; i < node.childNodes.length; i++) {
        child = node.childNodes[i];
        text = null;
        if (child.nodeType === 1) {
            text = getTextFromNode(child, addSpaces);
        } else if (child.nodeType === 3) {
            text = child.nodeValue;
        }
        if (text) {
            if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text;
            result += text;
        }
    }
    return result;
}

How do you find the row count for all your tables in Postgres

Here is a much simpler way.

tables="$(echo '\dt' | psql -U "${PGUSER}" | tail -n +4 | head -n-2 | tr -d ' ' | cut -d '|' -f2)"
for table in $tables; do
printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"
done

output should look like this

auth_group: 0
auth_group_permissions: 0
auth_permission: 36
auth_user: 2
auth_user_groups: 0
auth_user_user_permissions: 0
authtoken_token: 2
django_admin_log: 0
django_content_type: 9
django_migrations: 22
django_session: 0
mydata_table1: 9011
mydata_table2: 3499

you can update the psql -U "${PGUSER}" portion as needed to access your database

note that the head -n-2 syntax may not work in macOS, you could probably just use a different implementation there

Tested on psql (PostgreSQL) 11.2 under CentOS 7


if you want it sorted by table, then just wrap it with sort

for table in $tables; do
printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"
done | sort -k 2,2nr

output;

mydata_table1: 9011
mydata_table2: 3499
auth_permission: 36
django_migrations: 22
django_content_type: 9
authtoken_token: 2
auth_user: 2
auth_group: 0
auth_group_permissions: 0
auth_user_groups: 0
auth_user_user_permissions: 0
django_admin_log: 0
django_session: 0

Modelling an elevator using Object-Oriented Analysis and Design

Donald Knuth's The Art of Computer Programming Vol.1 has a demonstration of elevator and the data-structures. Knuth presents a very thorough discussion and program.

Knuth(1997) "Information Structures", The Art of Computer Programming Vol. 1 pp.302-308

Differences between Ant and Maven

Just to list some more differences:

  • Ant doesn't have formal conventions. You have to tell Ant exactly where to find the source, where to put the outputs, etc.
  • Ant is procedural. You have to tell Ant exactly what to do; tell it to compile, copy, then compress, etc.
  • Ant doesn't have a lifecycle.
  • Maven uses conventions. It knows where your source code is automatically, as long as you follow these conventions. You don't need to tell Maven where it is.
  • Maven is declarative; All you have to do is create a pom.xml file and put your source in the default directory. Maven will take care of the rest.
  • Maven has a lifecycle. You simply call mvn install and a series of sequence steps are executed.
  • Maven has intelligence about common project tasks. To run tests, simple execute mvn test, as long as the files are in the default location. In Ant, you would first have to JUnit JAR file is, then create a classpath that includes the JUnit JAR, then tell Ant where it should look for test source code, write a goal that compiles the test source and then finally execute the unit tests with JUnit.

Update:

This came from Maven: The Definitive Guide. Sorry, I totally forgot to cite it.

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here