Programs & Examples On #Dashboard designer

TCPDF output without saving file

Hint - with a saving file:

$pdf->Output('sandbox/pdf/example.pdf', 'F');

CSS: Position loading indicator in the center of the screen

You can use this OnLoad or during fetch infos from DB

In HTML Add following code:

<div id="divLoading">
<p id="loading">
    <img src="~/images/spinner.gif">
</p>

In CSS add following Code:

#divLoading {
  margin: 0px;
  display: none;
  padding: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
  z-index: 30001;
  opacity: 0.8;}

#loading {
   position: absolute;
   color: White;
  top: 50%;
  left: 45%;}

if you want to show and hide from JS:

  document.getElementById('divLoading').style.display = 'none'; //Not Visible
  document.getElementById('divLoading').style.display = 'block';//Visible

error 1265. Data truncated for column when trying to load data from txt file

I have seen the same warning when my data has extra space, tabs, newlines or other characters in my column which is decimal(10,2) to solve that, I had to remove those characters from value.

here is how I handled it.

LOAD DATA LOCAL INFILE 'c:/Users/Hitesh/Downloads/InventoryMasterReportHitesh.csv' 
INTO TABLE stores_inventory_tmp 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(@col1, @col2, @col3, @col4, @col5)
SET sku = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col1,'\t',''), '$',''), '\r', ''), '\n', ''))
, product_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col2,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_number = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col3,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col4,'\t',''), '$',''), '\r', ''), '\n', ''))
, price = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col5,'\t',''), '$',''), '\r', ''), '\n', ''))
;

I've got that hint from this answer

inject bean reference into a Quartz job in Spring?

This is a quite an old post which is still useful. All the solutions that proposes these two had little condition that not suite all:

  • SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); This assumes or requires it to be a spring - web based project
  • AutowiringSpringBeanJobFactory based approach mentioned in previous answer is very helpful, but the answer is specific to those who don't use pure vanilla quartz api but rather Spring's wrapper for the quartz to do the same.

If you want to remain with pure Quartz implementation for scheduling(Quartz with Autowiring capabilities with Spring), I was able to do it as follows:

I was looking to do it quartz way as much as possible and thus little hack proves helpful.

 public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory{

    private AutowireCapableBeanFactory beanFactory;

    public AutowiringSpringBeanJobFactory(final ApplicationContext applicationContext){
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        beanFactory.initializeBean(job, job.getClass().getName());
        return job;
    }
}


@Configuration
public class SchedulerConfig {   
    @Autowired private ApplicationContext applicationContext;

    @Bean
    public AutowiringSpringBeanJobFactory getAutowiringSpringBeanJobFactory(){
        return new AutowiringSpringBeanJobFactory(applicationContext);
    }
}


private void initializeAndStartScheduler(final Properties quartzProperties)
            throws SchedulerException {
        //schedulerFactory.initialize(quartzProperties);
        Scheduler quartzScheduler = schedulerFactory.getScheduler();

        //Below one is the key here. Use the spring autowire capable job factory and inject here
        quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory);
        quartzScheduler.start();
    }

quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory); gives us an autowired job instance. Since AutowiringSpringBeanJobFactory implicitly implements a JobFactory, we now enabled an auto-wireable solution. Hope this helps!

On postback, how can I check which control cause postback in Page_Init event

if (Request.Params["__EVENTTARGET"] != null)
{
  if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
  {
    DoWhateverYouWant();
  }
}

How to Set Active Tab in jQuery Ui

Simple jQuery solution - find the <a> element where href="x" and click it:

$('a[href="#tabs-2"]').click();

How can I install pip on Windows?

Simple CMD way

Use CURL to download get-pip.py:

curl --http1.1 https://bootstrap.pypa.io/get-pip.py --output get-pip.py

Execute the downloaded Python file

python get-pip.py

Then add C:\Python37\Scripts path to your environment variable. It assumes that there is a Python37 folder in your C drive. That folder name may vary according to the installed Python version

Now you can install Python packages by running

pip install awesome_package_name

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Git - remote: Repository not found

You might be logged in with some other GitHub credentials before. Exactly that's why this error is happening.

Usually, mac is storing your GitHub credential to the keychain access tool. Your previous git account details are there. So it is getting mismatched with your current git repo which is in other accounts.

The solution is simple and straight forward,

  1. Go to keychain access in your mac.
  2. On the left side under the category you can find all items. Click that.
  3. Right side top search "git".
  4. You will get some items regarding Github.
  5. Delete all those items.

That's it, here you go.

Try to push again. It will ask you the git username and password. Your new credentials will be stored again in the keychain and your push will be done.

Hurray!

Revert back to me, If you need more help.

Thanks

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

Print Currency Number Format in PHP

sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php

I use this function:

function formatDollars($dollars){
  return '$ '.sprintf('%0.2f', $dollars);
}

php execute a background process

Use this function to run your program in background. It cross-platform and fully customizable.

<?php
function startBackgroundProcess(
    $command,
    $stdin = null,
    $redirectStdout = null,
    $redirectStderr = null,
    $cwd = null,
    $env = null,
    $other_options = null
) {
    $descriptorspec = array(
        1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
        2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
    );
    if (is_string($stdin)) {
        $descriptorspec[0] = array('pipe', 'r');
    }
    $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
    if (!is_resource($proc)) {
        throw new \Exception("Failed to start background process by command: $command");
    }
    if (is_string($stdin)) {
        fwrite($pipes[0], $stdin);
        fclose($pipes[0]);
    }
    if (!is_string($redirectStdout)) {
        fclose($pipes[1]);
    }
    if (!is_string($redirectStderr)) {
        fclose($pipes[2]);
    }
    return $proc;
}

Note that after command started, by default this function closes the stdin and stdout of running process. You can redirect process output into some file via $redirectStdout and $redirectStderr arguments.

Note for windows users:
You cannot redirect stdout/stderr to nul in the following manner:

startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');

However, you can do this:

startBackgroundProcess('ping yandex.com >nul 2>&1');

Notes for *nix users:

1) Use exec shell command if you want get actual PID:

$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));

2) Use $stdin argument if you want to pass some data to the input of your program:

startBackgroundProcess('cat > input.txt', "Hello world!\n");

Most useful NLog configurations

I provided a couple of reasonably interesting answers to this question:

Nlog - Generating Header Section for a log file

Adding a Header:

The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:

Define the header and file layouts:

  <variable name="HeaderLayout" value="This is the header.  Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}"/>
  <variable name="FileLayout" value="${longdate} | ${logger} | ${level} | ${message}" />

Define the targets using the layouts:

<target name="fileHeader" xsi:type="File" fileName="xxx.log" layout="${HeaderLayout}" />
<target name="file" xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />

Define the loggers:

<rules>
  <logger name="headerlogger" minlevel="Trace" writeTo="fileHeader" final="true" />
  <logger name="*" minlevel="Trace" writeTo="file" />
</rules>

Write the header, probably early in the program:

  GlobalDiagnosticsContext.Set("version", "01.00.00.25");

  LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");

This is largely just another version of the "Treating exceptions differently" idea.

Log each log level with a different layout

Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:

  <variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <targets> 
    <target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace"> 
      <target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" /> 
    </target> 
    <target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug"> 
      <target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" /> 
    </target> 
    <target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info"> 
      <target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" /> 
    </target> 
    <target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn"> 
      <target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" /> 
    </target> 
    <target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error"> 
      <target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" /> 
    </target> 
    <target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal"> 
      <target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" /> 
    </target> 
  </targets> 


    <rules> 
      <logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" /> 
      <logger name="*" minlevel="Info" writeTo="dbg" /> 
    </rules> 

Again, very similar to Treating exceptions differently.

How to replace specific values in a oracle database column?

If you need to update the value in a particular table:

UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');

where

  TABLE-NAME         - The name of the table being updated
  COLUMN-NAME        - The name of the column being updated
  STRING-TO-REPLACE  - The value to replace
  REPLACEMENT-STRING - The replacement

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

how to convert a string to date in mysql?

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL

SELECT  STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM    table

say for example use the below query to get output

SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table

For String format use the below link

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

How to break out or exit a method in Java?

How to break out in java??

Ans: Best way: System.exit(0);

Java language provides three jump statemnts that allow you to interrupt the normal flow of program.

These include break , continue ,return ,labelled break statement for e.g

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            outerLoop://Label
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break outerLoop;
                        }
                     System.out.println();                  
                    }
             System.out.println();
            }
    }   
}

Output: 1

Now Note below Program:

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break ;
                        }                   
                    }
             System.out.println();
            }
    }   
}

output:

1
11
111
1111

and so on upto

1111111111

Similarly you can use continue statement just replace break with continue in above example.

Things to Remember :

A case label cannot contain a runtime expressions involving variable or method calls

outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved

What is the difference between an abstract function and a virtual function?

Most of the above examples use code - and they are very very good. I need not add to what they say, but the following is a simple explanation that makes use of analogies rather than code/technical terms.

Simple Explanation - Explanation using analogies

Abstract Method

Think George W Bush. He says to his soldiers: "Go fight in Iraq". And that's it. All he has specified is that fighting must be done. He does not specify how exactly that will happen. But I mean, you can't just go out and "fight": what does that mean exactly? do I fight with a B-52 or my derringer? Those specific details are left to someone else. This is an abstract method.

Virtual Method

David Petraeus is high up in the army. He has defined what fight means:

  1. Find the enemy
  2. Neutralise him.
  3. Have a beer afterwards

The problem is that it is a very general method. It's a good method that works, but sometimes is not specific enough. Good thing for Petraeus is that his orders have leeway and scope - he has allowed others to change his definition of "fight", according to their particular requirements.

Private Job Bloggs reads Petraeus' order and is given permission to implement his own version of fight, according to his particular requirements:

  1. Find enemy.
  2. Shoot him in the head.
  3. Go Home
  4. Have beer.

Nouri al Maliki also receives the same orders from Petraeus. He is to fight also. But he is a politician, not an infantry man. Obviously he cannot go around shooting his politican enemies in the head. Because Petraeus has given him a virtual method, then Maliki can implement his own version of the fight method, according to his particular circumstances:

  1. Find enemy.
  2. Have him arrested with some BS trumped up charges.
  3. Go Home
  4. Have beer.

IN other words, a virtual method provides boilerplate instructions - but these are general instructions, which can be made more specific by people down the army heirarchy, according to their particular circumstances.

The difference between the two

  • George Bush does not prove any implementation details. This must be provided by someone else. This is an abstract method.

  • Petraeus on the other hand does provide implementation details but he has given permission for his subordinates to override his orders with their own version, if they can come up with something better.

hope that helps.

Why do we assign a parent reference to the child object in Java?

It's simple.

Parent parent = new Child();

In this case the type of the object is Parent. Ant Parent has only one properties. It's name.

Child child = new Child();

And in this case the type of the object is Child. Ant Child has two properties. They're name and salary.

The fact is that there's no need to initialize non-final field immediately at the declaration. Usually this’s done at run-time because often you cannot know exactly what exactly implementation will you need. For example imagine that you have a class hierarchy with class Transport at the head. And three subclasses: Car, Helicopter and Boat. And there's another class Tour which has field Transport. That is:

class Tour {
   Transport transport;
}  

As long as an user hasn't booked a trip and hasn't chosen a particular type of transport you can't initialize this field. It's first.

Second, assume that all of these classes must have a method go() but with a different implementation. You can define a basic implementation by default in the superclass Transport and own unique implementations in each subclass. With this initialization Transport tran; tran = new Car(); you can call the method tran.go() and get result without worrying about specific implementation. It’ll call overrided method from particular subclass.

Moreover you can use instance of subclass everywhere where instance of superclass is used. For example you want provide opportunity to rent your transport. If you don't use polymorphism, you have to write a lot of methods for each case: rentCar(Car car), rentBoat(Boat boat) and so forth. At the same time polymorphism allows you to create one universal method rent(Transport transport). You can pass in it object of any subclass of Transport. In addition, if over time your logic will increase up and you'll need to create another class in the hierarchy? When using polymorphism you don't need to change anything. Just extend class Transport and pass your new class into the method:

public class Airplane extends Transport {
    //implementation
}

and rent(new Airplane()). And new Airplane().go() in second case.

How do you align left / right a div without using float?

You could just use a margin-left with a percentage.

HTML

<div class="goleft">Left Div</div>
<div class="goright">Right Div</div>

CSS

.goright{
    margin-left:20%;
}
.goleft{
    margin-right:20%;
}

(goleft would be the same as default, but can reverse if needed)

text-align doesn't always work as intended for layout options, it's mainly just for text. (But is often used for form elements too).

The end result of doing this will have a similar effect to a div with float:right; and width:80% set. Except, it won't clump together like a float will. (Saving the default display properties for the elements that come after).

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

Setting device orientation in Swift iOS

Swift 3

Orientation rotation is more complicated if a view controller is embedded in UINavigationController or UITabBarController the navigation or tab bar controller takes precedence and makes the decisions on autorotation and supported orientations.

Use the following extensions on UINavigationController and UITabBarController so that view controllers that are embedded in one of these controllers get to make the decisions:

UINavigationController extension

extension UINavigationController {

override open var shouldAutorotate: Bool {
    get {
        if let visibleVC = visibleViewController {
            return visibleVC.shouldAutorotate
        }
        return super.shouldAutorotate
    }
}

override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
    get {
        if let visibleVC = visibleViewController {
            return visibleVC.preferredInterfaceOrientationForPresentation
        }
        return super.preferredInterfaceOrientationForPresentation
    }
}

override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    get {
        if let visibleVC = visibleViewController {
            return visibleVC.supportedInterfaceOrientations
        }
        return super.supportedInterfaceOrientations
    }
 }}

UITabBarController extension

extension UITabBarController {

override open var shouldAutorotate: Bool {
    get {
        if let selectedVC = selectedViewController{
            return selectedVC.shouldAutorotate
        }
        return super.shouldAutorotate
    }
}

override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
    get {
        if let selectedVC = selectedViewController{
            return selectedVC.preferredInterfaceOrientationForPresentation
        }
        return super.preferredInterfaceOrientationForPresentation
    }
}

override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    get {
        if let selectedVC = selectedViewController{
            return selectedVC.supportedInterfaceOrientations
        }
        return super.supportedInterfaceOrientations
    }
}}

Now you can override the supportedInterfaceOrientations, shouldAutoRotate and preferredInterfaceOrientationForPresentation in the view controller you want to lock down otherwise you can leave out the overrides in other view controllers that you want to inherit the default orientation behavior specified in your app's plist.

Lock to Specific Orientation

class YourViewController: UIViewController {
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    get {
        return .portrait
    }
}}

Disable Rotation

    class YourViewController: UIViewController {
open override var shouldAutorotate: Bool {
    get {
        return false
    }
}}

Change Preferred Interface Orientation For Presentation

class YourViewController: UIViewController {
open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
    get {
        return .portrait
    }
}}

Bogus foreign key constraint fail

Maybe you received an error when working with this table before. You can rename the table and try to remove it again.

ALTER TABLE `area` RENAME TO `area2`;
DROP TABLE IF EXISTS `area2`;

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

How to use '-prune' option of 'find' in sh?

There are quite a few answers; some of them are a bit too much theory-heavy. I'll leave why I needed prune once so maybe the need-first/example kind of explanation is useful to someone :)

Problem

I had a folder with about 20 node directories, each having its node_modules directory as expected.

Once you get into any project, you see each ../node_modules/module. But you know how it is. Almost every module has dependencies, so what you are looking at is more like projectN/node_modules/moduleX/node_modules/moduleZ...

I didn't want to drown with a list with the dependency of the dependency of...

Knowing -d n / -depth n, it wouldn't have helped me, as the main/first node_modules directory I wanted of each project was at a different depth, like this:

Projects/MysuperProjectName/project/node_modules/...
Projects/Whatshisname/version3/project/node_modules/...
Projects/project/node_modules/...
Projects/MysuperProjectName/testProject/november2015Copy/project/node_modules/...
[...]

How can I get the first a list of paths ending at the first node_modules and move to the next project to get the same?

Enter -prune

When you add -prune, you'll still have a standard recursive search. Each "path" is analyzed, and every find gets spit out and find keeps digging down like a good chap. But it's the digging down for more node_modules what I didn't want.

So, the difference is that in any of those different paths, -prune will find to stop digging further down that particular avenue when it has found your item. In my case, the node_modules folder.

Add & delete view from Layout

This is the best way

LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them 
lp.removeViewAt(0); // and so on

If you have xml layout then no need to add dynamically.just call

lp.removeViewAt(0);

window.onload vs document.onload

In short

  • window.onload is not supported by IE 6-8
  • document.onload is not supported by any modern browser (event is never fired)

_x000D_
_x000D_
window.onload   = () => console.log('window.onload works');   // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
_x000D_
_x000D_

How to remove numbers from a string?

This can be done without regex which is more efficient:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
    num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

Any tools to generate an XSD schema from an XML instance document?

If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.

C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.

xsd.exe -
   Utility to generate schema or class files from given source.

xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]

Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language

I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path> flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path> flags to get classes that I can import and use in my day to day .Net projects

Push item to associative array in PHP

i use php5.6

code:

$person = ["name"=>"mohammed", "age"=>30];

$person['addr'] = "Sudan";

print_r($person) 

output

Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )

CSS 3 slide-in from left transition

USE THIS FOR RIGHT TO LEFT SLIDING :

HTML:

   <div class="nav ">
       <ul>
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">CONTACT</a></li>
       </ul>
   </div>

CSS:

/*nav*/
.nav{
    position: fixed;
    right:0;
    top: 70px;
    width: 250px;
    height: calc(100vh - 70px);
    background-color: #333;
    transform: translateX(100%);
    transition: transform 0.3s ease-in-out;

}
.nav-view{
    transform: translateX(0);
}
.nav ul{
    margin: 0;
    padding: 0;
}
.nav ul li{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.nav ul li a{
    color: #fff;
    display: block;
    padding: 10px;
    border-bottom: solid 1px rgba(255,255,255,0.4);
    text-decoration: none;
}

JS:

  $(document).ready(function(){
  $('a#click-a').click(function(){
    $('.nav').toggleClass('nav-view');
  });
});

Unpivot with column name

Your query is very close. You should be able to use the following which includes the subject in the final select list:

select u.name, u.subject, u.marks
from student s
unpivot
(
  marks
  for subject in (Maths, Science, English)
) u;

See SQL Fiddle with demo

subsetting a Python DataFrame

I've found that you can use any subset condition for a given column by wrapping it in []. For instance, you have a df with columns ['Product','Time', 'Year', 'Color']

And let's say you want to include products made before 2014. You could write,

df[df['Year'] < 2014]

To return all the rows where this is the case. You can add different conditions.

df[df['Year'] < 2014][df['Color' == 'Red']

Then just choose the columns you want as directed above. For instance, the product color and key for the df above,

df[df['Year'] < 2014][df['Color'] == 'Red'][['Product','Color']]

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

For usages of Write-Host, PSScriptAnalyzer produces the following diagnostic:

Avoid using Write-Host because it might not work in all hosts, does not work when there is no host, and (prior to PS 5.0) cannot be suppressed, captured, or redirected. Instead, use Write-Output, Write-Verbose, or Write-Information.

See the documentation behind that rule for more information. Excerpts for posterity:

The use of Write-Host is greatly discouraged unless in the use of commands with the Show verb. The Show verb explicitly means "show on the screen, with no other possibilities".

Commands with the Show verb do not have this check applied.

Jeffrey Snover has a blog post Write-Host Considered Harmful in which he claims Write-Host is almost always the wrong thing to do because it interferes with automation and provides more explanation behind the diagnostic, however the above is a good summary.

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

How is the AND/OR operator represented as in Regular Expressions?

Does this work without alternation?

^((part)1(, \22)?)?(part2)?$

or why not this?

^((part)1(, (\22))?)?(\4)?$

The first works for all conditions the second for all but part2(using GNU sed 4.1.5)

Android: Force EditText to remove focus?

editText.setFocusableInTouchMode(true)

The EditText will be able to get the focus when the user touch it. When the main layout (activity, dialog, etc.) becomes visible the EditText doesn't automatically get the focus even though it is the first view in the layout.

How can I make one python file run another?

Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:

  1. Put this in main.py:

    #!/usr/bin/python
    import yoursubfile
    
  2. Put this in yoursubfile.py

    #!/usr/bin/python
    print("hello")
    
  3. Run it:

    python main.py 
    
  4. It prints:

    hello
    

Thus main.py runs yoursubfile.py

There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

Predict() - Maybe I'm not understanding it

First, you want to use

model <- lm(Total ~ Coupon, data=df)

not model <-lm(df$Total ~ df$Coupon, data=df).

Second, by saying lm(Total ~ Coupon), you are fitting a model that uses Total as the response variable, with Coupon as the predictor. That is, your model is of the form Total = a + b*Coupon, with a and b the coefficients to be estimated. Note that the response goes on the left side of the ~, and the predictor(s) on the right.

Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon, not Total.

Third, judging by your specification of newdata, it looks like you're actually after a model to fit Coupon as a function of Total, not the other way around. To do this:

model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)

How to print a stack trace in Node.js?

@isaacs answer is correct, but if you need more specific or cleaner error stack, you can use this function:

function getCleanerStack() {
   var err = new Error();
   Error.captureStackTrace(err, getStack);

   return err.stack;
}

This function is inspired directly from the console.trace function in NodeJS.

Source code: Recent version or Old version.

libclntsh.so.11.1: cannot open shared object file.

I had to install the dependency

oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64

Operator overloading in Java

As many others have answered: Java doesn't support user-defined operator overloading.

Maybe this is off-topic, but I want to comment on some things I read in some answers.

About readability.
Compare:

  1. c = a + b
  2. c = a.add(b)

Look again!
Which one is more readable?

A programming language that allows the creation of user-defined types, should allow them to act in the same way as the built-in types (or primitive types).

So Java breaks a fundamental principle of Generic Programming:
We should be able to interchange objects of built-in types with objects of user-defined types.
(You may be wondering: "Did he say 'objects of built-in'?". Yes, see here.)

About String concatenation:

Mathematicians use the symbol + for commutative operations on sets.
So we can be sure that a + b = b + a.
String concatenation (in most programming languages) doesn't respect this common mathematical notation.

a := "hello";
b := "world";
c := (a + b = b + a);

or in Java:

String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);

Extra:
Notice how in Java equality and identity are confused. The == (equality) symbol means:
a. Equality for primitive types.
b. Identity-check for user-defined types, therefore, we are forced to use the function equals() for equality.
But... What has this to do with operator overloading?
If the language allows the operator overloading the user could give the proper meaning to the equality operator.

Passing variables through handlebars partial

Just in case, here is what I did to get partial arguments, kind of. I’ve created a little helper that takes a partial name and a hash of parameters that will be passed to the partial:

Handlebars.registerHelper('render', function(partialId, options) {
  var selector = 'script[type="text/x-handlebars-template"]#' + partialId,
      source = $(selector).html(),
      html = Handlebars.compile(source)(options.hash);

  return new Handlebars.SafeString(html);
});

The key thing here is that Handlebars helpers accept a Ruby-like hash of arguments. In the helper code they come as part of the function’s last argument—options— in its hash member. This way you can receive the first argument—the partial name—and get the data after that.

Then, you probably want to return a Handlebars.SafeString from the helper or use “triple-stash”—{{{— to prevent it from double escaping.

Here is a more or less complete usage scenario:

<script id="text-field" type="text/x-handlebars-template">
  <label for="{{id}}">{{label}}</label>
  <input type="text" id="{{id}}"/>
</script>

<script id="checkbox-field" type="text/x-handlebars-template">
  <label for="{{id}}">{{label}}</label>
  <input type="checkbox" id="{{id}}"/>
</script>

<script id="form-template" type="text/x-handlebars-template">
  <form>
    <h1>{{title}}</h1>
    {{ render 'text-field' label="First name" id="author-first-name" }}
    {{ render 'text-field' label="Last name" id="author-last-name" }}
    {{ render 'text-field' label="Email" id="author-email" }}
    {{ render 'checkbox-field' label="Private?" id="private-question" }}
  </form>
</script>

Hope this helps …someone. :)

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

Viewing root access files/folders of android on windows

If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

Is there a Wikipedia API?

JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia

http://code.google.com/p/jwpl/

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152

Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297

MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx

Negative weights using Dijkstra's Algorithm

TL;DR: The answer depends on your implementation. For the pseudo code you posted, it works with negative weights.


Variants of Dijkstra's Algorithm

The key is there are 3 kinds of implementation of Dijkstra's algorithm, but all the answers under this question ignore the differences among these variants.

  1. Using a nested for-loop to relax vertices. This is the easiest way to implement Dijkstra's algorithm. The time complexity is O(V^2).
  2. Priority-queue/heap based implementation + NO re-entrance allowed, where re-entrance means a relaxed vertex can be pushed into the priority-queue again to be relaxed again later.
  3. Priority-queue/heap based implementation + re-entrance allowed.

Version 1 & 2 will fail on graphs with negative weights (if you get the correct answer in such cases, it is just a coincidence), but version 3 still works.

The pseudo code posted under the original problem is the version 3 above, so it works with negative weights.

Here is a good reference from Algorithm (4th edition), which says (and contains the java implementation of version 2 & 3 I mentioned above):

Q. Does Dijkstra's algorithm work with negative weights?

A. Yes and no. There are two shortest paths algorithms known as Dijkstra's algorithm, depending on whether a vertex can be enqueued on the priority queue more than once. When the weights are nonnegative, the two versions coincide (as no vertex will be enqueued more than once). The version implemented in DijkstraSP.java (which allows a vertex to be enqueued more than once) is correct in the presence of negative edge weights (but no negative cycles) but its running time is exponential in the worst case. (We note that DijkstraSP.java throws an exception if the edge-weighted digraph has an edge with a negative weight, so that a programmer is not surprised by this exponential behavior.) If we modify DijkstraSP.java so that a vertex cannot be enqueued more than once (e.g., using a marked[] array to mark those vertices that have been relaxed), then the algorithm is guaranteed to run in E log V time but it may yield incorrect results when there are edges with negative weights.


For more implementation details and the connection of version 3 with Bellman-Ford algorithm, please see this answer from zhihu. It is also my answer (but in Chinese). Currently I don't have time to translate it into English. I really appreciate it if someone could do this and edit this answer on stackoverflow.

How to get N rows starting from row M from sorted table in T-SQL

I read all of the responses here and finally came up with a usable solution that is simple. The performance issues arise from the BETWEEN statement, not the generation of the row numbers themselves. So I used an algorithm to do dynamic paging by passing the page number and the number of records.

The passes are not start row and number of rows, but rather "rows per page (500)" and "page number (4)" which would be rows 1501 - 2000. These values can be replaced by stored procedure variables so you are not locked into using a specific paging amount.

select * from (
    select
        (((ROW_NUMBER() OVER(ORDER BY MyField) - 1) / 500) + 1) AS PageNum
        , *
    from MyTable
) as PagedTable
where PageNum = 4;

Swift GET request with parameters

I use:

let dictionary = ["method":"login_user",
                  "cel":mobile.text!
                  "password":password.text!] as  Dictionary<String,String>

for (key, value) in dictionary {
    data=data+"&"+key+"="+value
    }

request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);

Blue and Purple Default links, how to remove?

By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

DECLARE @t1 TABLE (
    TableID     int         IDENTITY,
    FieldValue  varchar(20)
)

--<< No empty string
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

--<< A record with an empty string already exists
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

How to avoid 'cannot read property of undefined' errors?

What you are doing raises an exception (and rightfully so).

You can always do

try{
   window.a.b.c
}catch(e){
   console.log("YO",e)
}

But I wouldn't, instead think of your use case.

Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?

Usually, you'd like to actually validate what sort of object you're dealing with.

Also, on a side note you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to get text from EditText?

String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);

Convert string to float?

String s = "3.14";
float f = Float.parseFloat(s);

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

How can I pass command-line arguments to a Perl program?

You can access them directly, by assigning the special variable @ARGV to a list of variables. So, for example:

( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;

perl tmp.pl 1 2 3 4 5

enter image description here

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

this problem arises when we use vectors in place of scalars for example in a for loop the range should be a scalar, in case you have given a vector in that place you get error. So to avoid the problem use the length of the vector you have used

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

How to make an ng-click event conditional?

I use the && expression which works perfectly for me.

For example,

<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>

If vm.slideOneValid is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.

Just remember to add ng-model to the element to make ng-disabled work.

SQL Server: Best way to concatenate multiple columns?

Blockquote

Using concatenation in Oracle SQL is very easy and interesting. But don't know much about MS-SQL.

Blockquote

Here we go for Oracle : Syntax: SQL> select First_name||Last_Name as Employee from employees;

Result: EMPLOYEE

EllenAbel SundarAnde MozheAtkinson

Here AS: keyword used as alias. We can concatenate with NULL values. e.g. : columnm1||Null

Suppose any of your columns contains a NULL value then the result will show only the value of that column which has value.

You can also use literal character string in concatenation.

e.g. select column1||' is a '||column2 from tableName; Result: column1 is a column2. in between literal should be encolsed in single quotation. you cna exclude numbers.

NOTE: This is only for oracle server//SQL.

How do I install Python 3 on an AWS EC2 instance?

As of Amazon Linux version 2017.09 python 3.6 is now available:

sudo yum install python36 python36-virtualenv python36-pip

See the Release Notes for more info and other packages

Are there any log file about Windows Services Status?

Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.

You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.

How to write loop in a Makefile?

The following will do it if, as I assume by your use of ./a.out, you're on a UNIX-type platform.

for number in 1 2 3 4 ; do \
    ./a.out $$number ; \
done

Test as follows:

target:
    for number in 1 2 3 4 ; do \
        echo $$number ; \
    done

produces:

1
2
3
4

For bigger ranges, use:

target:
    number=1 ; while [[ $$number -le 10 ]] ; do \
        echo $$number ; \
        ((number = number + 1)) ; \
    done

This outputs 1 through 10 inclusive, just change the while terminating condition from 10 to 1000 for a much larger range as indicated in your comment.

Nested loops can be done thus:

target:
    num1=1 ; while [[ $$num1 -le 4 ]] ; do \
        num2=1 ; while [[ $$num2 -le 3 ]] ; do \
            echo $$num1 $$num2 ; \
            ((num2 = num2 + 1)) ; \
        done ; \
        ((num1 = num1 + 1)) ; \
    done

producing:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3

How do I compare two DateTime objects in PHP 5.2.8?

As of PHP 7.x, you can use the following:

$aDate = new \DateTime('@'.(time()));
$bDate = new \DateTime('@'.(time() - 3600));

$aDate <=> $bDate; // => 1, `$aDate` is newer than `$bDate`

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

How to negate a method reference predicate

I'm planning to static import the following to allow for the method reference to be used inline:

public static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
}

e.g.

Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();

Update: Starting from Java-11, the JDK offers a similar solution built-in as well.

how to sort an ArrayList in ascending order using Collections and Comparator

Here a complete example :

Suppose we have a Person class like :

public class Person
{
    protected String fname;
    protected String lname;

    public Person()
    {

    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public boolean equals(Object objet)
    {
        if(objet instanceof Person)
        {
            Person p = (Person) objet;
            return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
        }
        else return super.equals(objet);
    }

    @Override
    public String toString()
    {
        return "Person(fname : " + getFname + ", lname : " + getLname + ")";
    }

    /** Getters and Setters **/
}

Now we create a comparator :

import java.util.Comparator;

public class ComparePerson implements Comparator<Person>
{
    @Override
    public int compare(Person p1, Person p2)
    {
        if(p1.getFname().equalsIgnoreCase(p2.getFname()))
        {
            return p1.getLname().compareTo(p2.getLname());
        }
        return p1.getFname().compareTo(p2.getFname());
    }
}

Finally suppose we have a group of persons :

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Group
{
    protected List<Person> listPersons;

    public Group()
    {
        this.listPersons = new ArrayList<Person>();
    }

    public Group(List<Person> listPersons)
    {
        this.listPersons = listPersons;
    }

    public void order(boolean asc)
    {
        Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
        Collections.sort(this.listPersons, comp);
    }

    public void display()
    {
        for(Person p : this.listPersons)
        {
            System.out.println(p);
        }
    }

    /** Getters and Setters **/
}

Now we try this :

import java.util.ArrayList;
import java.util.List;

public class App
{
    public static void main(String[] args)
    {
        Group g = new Group();
        List listPersons = new ArrayList<Person>();
        g.setListPersons(listPersons);

        Person p;

        p = new Person("A", "B");
        listPersons.add(p);

        p = new Person("C", "D");
        listPersons.add(p);

        /** you can add Person as many as you want **/

        g.display();

        g.order(true);
        g.display();

        g.order(false);
        g.display();
    }
}

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

How to insert an item into an array at a specific index (JavaScript)?

Here's a working function that I uses in one of my application.

This checks if item exit

let ifExist = (item, strings = [ '' ], position = 0) => {
     // output into an array with empty string. Important just in case their is no item. 
    let output = [ '' ];
    // check to see if the item that will be positioned exist.
    if (item) {
        // output should equal to array of strings. 
        output = strings;
       // use splice in order to break the array. 
       // use positition param to state where to put the item
       // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position. 
        output.splice(position, 0, item);
    }
    //empty string is so we do not concatenate with comma or anything else. 
    return output.join("");
};

And then I call it below.

ifExist("friends", [ ' ( ', ' )' ], 1)}  // output: ( friends )
ifExist("friends", [ ' - '], 1)}  // output:  - friends 
ifExist("friends", [ ':'], 0)}  // output:   friends: 

Parse JSON String into a Particular Object Prototype in JavaScript

The current answers contain a lot of hand-rolled or library code. This is not necessary.

  1. Use JSON.parse('{"a":1}') to create a plain object.

  2. Use one of the standardized functions to set the prototype:

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

Define an <img>'s src attribute in CSS

After trying these solutions I still wasn't satisfied but I found a solution in this article and it works in Chrome, Firefox, Opera, Safari, IE8+

#divId {

  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
  width: 180px; /* Width of new image */
  height: 236px; /* Height of new image */
  padding-left: 180px; /* Equal to width of new image */

}

Pandas Replace NaN with blank/empty string

Use a formatter, if you only want to format it so that it renders nicely when printed. Just use the df.to_string(... formatters to define custom string-formatting, without needlessly modifying your DataFrame or wasting memory:

df = pd.DataFrame({
    'A': ['a', 'b', 'c'],
    'B': [np.nan, 1, np.nan],
    'C': ['read', 'unread', 'read']})
print df.to_string(
    formatters={'B': lambda x: '' if pd.isnull(x) else '{:.0f}'.format(x)})

To get:

   A B       C
0  a      read
1  b 1  unread
2  c      read

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

How do you get the currently selected <option> in a <select> via JavaScript?

Using the selectedOptions property:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It works in all browsers except Internet Explorer.

Split string into strings by length?

length = 4
string = "abcdefgh"
str_dict = [ o for o in string ]
parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ]   ) for j in xrange(len(string)/length  )]

Python CSV error: line contains NULL byte

I encountered this when using scrapy and fetching a zipped csvfile without having a correct middleware to unzip the response body before handing it to the csvreader. Hence the file was not really a csv file and threw the line contains NULL byte error accordingly.

Looping through a hash, or using an array in PowerShell

You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

Installing Google Protocol Buffers on mac

If you landed here looking for how to install Protocol Buffers on Mac, it can be done using Homebrew by running the command below

brew install protobuf

It installs the latest version of protobuf available. For me, at the time of writing, this installed the v3.7.1

If you'd like to install an older version, please look up the available ones from the package page Protobuf Package - Homebrew and install that specific version of the package.

The oldest available protobuf version in this package is v3.6.1.3

Phonegap + jQuery Mobile, real world sample or tutorial

you may check this website: Phonegap RSS feeds, Javascript, this is an example about rss reader which uses the phonegap and jquery-mobile techniques

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

I had the same error. In my case, using Appium, I had two versions of ADB

$ /usr/local/bin/adb version 36

and

$ /Users/user/Library/Android/sdk/platform-tools/adb version 39

The solution was:

  1. be sure that your $PATH in bash_profile is pointing to: /Users/user/Library/Android/sdk/platform-tools/

  2. stop the adb server: adb kill-server and check Appium is stopped.

  3. delete the adb version 36 (or you can rename it to have a backup): rm /usr/local/bin/adb

  4. start adb server: adb start-server or just starting Appium

Copy multiple files in Python

If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*") to get a list of all the filenames, loop over the list and use shutil.copy to copy each file.

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

Edit package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

and Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

Setting PHPMyAdmin Language

In config.inc.php in the top-level directory, set

$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users

If Lang isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

Controlling execution order of unit tests in Visual Studio

As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.

I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).

Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.

orderedtest - it works but I don't recommend it because:

  1. An orderedtest a text file that lists your tests in the order they should be executed. If you change a method name, you must fix the file.
  2. The test execution order is respected inside a class. You can't order which class executes its tests first.
  3. An orderedtest file is bound to a configuration, either Debug or Release
  4. You can have several orderedtest files but a given method can not be repeated in different orderedtest files. So you can't have one orderedtest file for Debug and another for Release.

Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.

You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.

The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.

This means the test method that is declared in the first place executes before the one that is declared in second place, etc.

To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.

  • A010_FirstTest
  • A020_SecondTest
  • etc
  • A100_TenthTest

I strongly suggest some old and tested rules:

  • use a step of 10 because you will need to insert a test method later on
  • avoid the need to renumber your tests by using a generous step between test numbers
  • use 3 digits to number your tests if you are running more than 10 tests
  • use 4 digits to number your tests if you are running more than 100 tests

VERY IMPORTANT

In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.

Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.

Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

Run Stored Procedure in SQL Developer?

Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer. After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.

  • Under packages, select your desired package and right click on the package name (not on the stored procedure name).

  • You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below

I'm using SQL developer version 4.1.3.20

Understanding slice notation

In Python, the most basic form for slicing is the following:

l[start:end]

where l is some collection, start is an inclusive index, and end is an exclusive index.

In [1]: l = list(range(10))

In [2]: l[:5] # First five elements
Out[2]: [0, 1, 2, 3, 4]

In [3]: l[-5:] # Last five elements
Out[3]: [5, 6, 7, 8, 9]

When slicing from the start, you can omit the zero index, and when slicing to the end, you can omit the final index since it is redundant, so do not be verbose:

In [5]: l[:3] == l[0:3]
Out[5]: True

In [6]: l[7:] == l[7:len(l)]
Out[6]: True

Negative integers are useful when doing offsets relative to the end of a collection:

In [7]: l[:-1] # Include all elements but the last one
Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8]

In [8]: l[-3:] # Take the last three elements
Out[8]: [7, 8, 9]

It is possible to provide indices that are out of bounds when slicing such as:

In [9]: l[:20] # 20 is out of index bounds, and l[20] will raise an IndexError exception
Out[9]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [11]: l[-20:] # -20 is out of index bounds, and l[-20] will raise an IndexError exception
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Keep in mind that the result of slicing a collection is a whole new collection. In addition, when using slice notation in assignments, the length of the slice assignments do not need to be the same. The values before and after the assigned slice will be kept, and the collection will shrink or grow to contain the new values:

In [16]: l[2:6] = list('abc') # Assigning fewer elements than the ones contained in the sliced collection l[2:6]

In [17]: l
Out[17]: [0, 1, 'a', 'b', 'c', 6, 7, 8, 9]

In [18]: l[2:5] = list('hello') # Assigning more elements than the ones contained in the sliced collection l [2:5]

In [19]: l
Out[19]: [0, 1, 'h', 'e', 'l', 'l', 'o', 6, 7, 8, 9]

If you omit the start and end index, you will make a copy of the collection:

In [14]: l_copy = l[:]

In [15]: l == l_copy and l is not l_copy
Out[15]: True

If the start and end indexes are omitted when performing an assignment operation, the entire content of the collection will be replaced with a copy of what is referenced:

In [20]: l[:] = list('hello...')

In [21]: l
Out[21]: ['h', 'e', 'l', 'l', 'o', '.', '.', '.']

Besides basic slicing, it is also possible to apply the following notation:

l[start:end:step]

where l is a collection, start is an inclusive index, end is an exclusive index, and step is a stride that can be used to take every nth item in l.

In [22]: l = list(range(10))

In [23]: l[::2] # Take the elements which indexes are even
Out[23]: [0, 2, 4, 6, 8]

In [24]: l[1::2] # Take the elements which indexes are odd
Out[24]: [1, 3, 5, 7, 9]

Using step provides a useful trick to reverse a collection in Python:

In [25]: l[::-1]
Out[25]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

It is also possible to use negative integers for step as the following example:

In[28]:  l[::-2]
Out[28]: [9, 7, 5, 3, 1]

However, using a negative value for step could become very confusing. Moreover, in order to be Pythonic, you should avoid using start, end, and step in a single slice. In case this is required, consider doing this in two assignments (one to slice, and the other to stride).

In [29]: l = l[::2] # This step is for striding

In [30]: l
Out[30]: [0, 2, 4, 6, 8]

In [31]: l = l[1:-1] # This step is for slicing

In [32]: l
Out[32]: [2, 4, 6]

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

struct in class

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}

How to install packages offline?

Download the wheel file (for example dlb-0.5.0-py3-none-any.whl) from Pypi and

pip install dlb-0.5.0-py3-none-any.whl

PHP: How do you determine every Nth iteration of a loop?

How about: if(($counter % $display) == 0)

How to align an image dead center with bootstrap

Twitter bootstrap has a class that centers: .pagination-centered

It worked for me to do:

<div class="row-fluid">
   <div class="span12 pagination-centered"><img src="header.png" alt="header" /></div>
</div>

The css for the class is:

.pagination-centered {
  text-align: center;
}

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

The maximum message size quota for incoming messages (65536) has been exceeded

As per this question's answer

You will want something like this:

<bindings>
     <basicHttpBinding>
         <binding name="basicHttp" allowCookies="true"
 maxReceivedMessageSize="20000000"
 maxBufferSize="20000000"
 maxBufferPoolSize="20000000">
             <readerQuotas maxDepth="32"
 maxArrayLength="200000000"
 maxStringContentLength="200000000"/>
         </binding>
     </basicHttpBinding> </bindings>

Please also read comments to the accepted answer there, those contain valuable input.

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

How do I clear all variables in the middle of a Python script?

This is a modified version of Alex's answer. We can save the state of a module's namespace and restore it by using the following 2 methods...

__saved_context__ = {}

def saveContext():
    import sys
    __saved_context__.update(sys.modules[__name__].__dict__)

def restoreContext():
    import sys
    names = sys.modules[__name__].__dict__.keys()
    for n in names:
        if n not in __saved_context__:
            del sys.modules[__name__].__dict__[n]

saveContext()

hello = 'hi there'
print hello             # prints "hi there" on stdout

restoreContext()

print hello             # throws an exception

You can also add a line "clear = restoreContext" before calling saveContext() and clear() will work like matlab's clear.

find a minimum value in an array of floats

Python has a min() built-in function:

>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828

How can I mix LaTeX in with Markdown?

Perhaps mathJAX is the ticket. It's built on jsMath, a 2004 vintage JavaScript library.

As of 5-Feb-2015 I'd switch to recommend KaTeX - most performant Javascript LaTeX library from Khan Academy.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

return SQL table as JSON in python

I would supplement The Demz answer with the psycopg2 version:

import psycopg2 
import psycopg2.extras
import json
connection = psycopg2.connect(dbname=_cdatabase, host=_chost, port=_cport , user=_cuser, password=_cpassword)
cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # This line allows dictionary access.
#select some records into "rows"
jsonout= json.dumps([dict(ix) for ix in rows])

If (Array.Length == 0)

You can use

if (array == null || array.Length == 0)

OR

if (!(array != null && array.Length != 0))

NOTE!!!!! To insure that c# will implement the short circuit correctly; you have to compare that the object with NULL before you go to the children compare of the object.

C# 7.0 and above

if(!(array?.Length != 0))

How to select the last record of a table in SQL?

In Oracle, you can do:

SELECT *
FROM (SELECT EMP.*,ROWNUM FROM EMP ORDER BY ROWNUM DESC)
WHERE ROWNUM=1;

This is one of the possible ways.

How to keep Docker container running after starting services?

you can run plain cat without any arguments as mentioned by bro @Sa'ad to simply keep the container working [actually doing nothing but waiting for user input] (Jenkins' Docker plugin does the same thing)

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

How to set iframe size dynamically

Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.

<style>
    #myFrame { width:100%; height:100%; }
</style>

<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>

Why does Eclipse Java Package Explorer show question mark on some classes?

It means the class is not yet added to the repository.

If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.

For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

Replace Multiple String Elements in C#

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

How to add conditional attribute in Angular 2?

If it's an input element you can write something like.... <input type="radio" [checked]="condition"> The value of condition must be true or false.

Also for style attributes... <h4 [style.color]="'red'">Some text</h4>

What are 'get' and 'set' in Swift?

variable declares and call like this in a class

class X {
    var x: Int = 3

}
var y = X()
print("value of x is: ", y.x)

//value of x is:  3

now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.

class X {
    var _x: Int = 3
    var x: Int {
        get {
            return _x
        }
        set(newVal) {  //set always take 1 argument
            if newVal >= 3 {
             _x = newVal //updating _x with the input value by the user
            print("new value is: ", _x)
            }
            else {
                print("error must be greater than 3")
            }
        }
    }
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8

if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

In Chrome Dev Tools you can run the following:

$x("some xpath")

Always show vertical scrollbar in <select>

It will work in IE7. But here you need to fixed the size less than the number of option and not use overflow-y:scroll. In your example you have 2 option but you set size=10, which will not work.

Suppose your select has 10 option, then fixed size=9.

Here, in your code reference you used height:100px with size:2. I remove the height css, because its not necessary and change the size:5 and it works fine.

Here is your modified code from jsfiddle:

<select size="5" style="width:100px;">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
</select>

this will generate a larger select box than size:2 create.In case of small size the select box will not display the scrollbar,you have to check with appropriate size quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2 and size greater than 2(e.g: 3,5).

Here is your desired result. I think this will help you:

CSS

  .wrapper{
    border: 1px dashed red;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 150px;
 }
 .wrapper .selection{
   width:150px;
   border:1px solid #ccc
 }

HTML

<div class="wrapper">
<select size="15" class="selection">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>
</div>

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

How to generate a git patch for a specific commit?

For generating the patches from the topmost commits from a specific sha1 hash:

git format-patch -<n> <SHA1>

The last 10 patches from head in a single patch file:

git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch

How to run functions in parallel?

If your functions are mainly doing I/O work (and less CPU work) and you have Python 3.2+, you can use a ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def run_io_tasks_in_parallel(tasks):
    with ThreadPoolExecutor() as executor:
        running_tasks = [executor.submit(task) for task in tasks]
        for running_task in running_tasks:
            running_task.result()

run_io_tasks_in_parallel([
    lambda: print('IO task 1 running!'),
    lambda: print('IO task 2 running!'),
])

If your functions are mainly doing CPU work (and less I/O work) and you have Python 2.6+, you can use the multiprocessing module:

from multiprocessing import Process

def run_cpu_tasks_in_parallel(tasks):
    running_tasks = [Process(target=task) for task in tasks]
    for running_task in running_tasks:
        running_task.start()
    for running_task in running_tasks:
        running_task.join()

run_cpu_tasks_in_parallel([
    lambda: print('CPU task 1 running!'),
    lambda: print('CPU task 2 running!'),
])

How to dynamically add a style for text-align using jQuery

You have the right idea, as documentation shows:

http://docs.jquery.com/CSS/css#namevalue

Are you sure you're correctly identify this with class or id?

For example, if your class is myElementClass

$('.myElementClass').css('text-align','center');

Also, I haven't worked with Firebug in a while, but are you looking at the dom and not the html? Your source isn't changed by javascript, but the dom is. Look in the dom tab and see if the change was applied.

Clang vs GCC - which produces faster binaries?

The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.

How to create a String with carriage returns?

Thanks for your answers. I missed that my data is stored in a List<String> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

This is an issue that can happen in Android Studio if you modify Project Structure Modules. In this case you may need to add the dependencies again. In a text editor edit the 'build.gradle' file to include the required dependencies:

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

This should update your '{your_project_name}.iml' file with lib components:

<orderEntry type="library" exported="" name="appcompat-v7-19.0.1" level="project" />

How to get item count from DynamoDB?

If you happen to reach here, and you are working with C#, here is the code:

var cancellationToken = new CancellationToken();

var request = new ScanRequest("TableName") {Select = Select.COUNT};

var result = context.Client.ScanAsync(request, cancellationToken).Result;

totalCount = result.Count;

How to create a custom string representation for a class object?

Ignacio Vazquez-Abrams' approved answer is quite right. It is, however, from the Python 2 generation. An update for the now-current Python 3 would be:

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object, metaclass=MC):
    pass

print(C)

If you want code that runs across both Python 2 and Python 3, the six module has you covered:

from __future__ import print_function
from six import with_metaclass

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(with_metaclass(MC)):
    pass

print(C)

Finally, if you have one class that you want to have a custom static repr, the class-based approach above works great. But if you have several, you'd have to generate a metaclass similar to MC for each, and that can get tiresome. In that case, taking your metaprogramming one step further and creating a metaclass factory makes things a bit cleaner:

from __future__ import print_function
from six import with_metaclass

def custom_class_repr(name):
    """
    Factory that returns custom metaclass with a class ``__repr__`` that
    returns ``name``.
    """
    return type('whatever', (type,), {'__repr__': lambda self: name})

class C(with_metaclass(custom_class_repr('Wahaha!'))): pass

class D(with_metaclass(custom_class_repr('Booyah!'))): pass

class E(with_metaclass(custom_class_repr('Gotcha!'))): pass

print(C, D, E)

prints:

Wahaha! Booyah! Gotcha!

Metaprogramming isn't something you generally need everyday—but when you need it, it really hits the spot!

How can I install MacVim on OS X?

There is also a new option now in http://vimr.org/, which looks quite promising.

chrome undo the action of "prevent this page from creating additional dialogs"

So the correct answer is: YES, there is a better way.

Right click on the tab and select "Duplicate", then close the original tab if you wish.

Alerting is re-enabled in the duplicate.

The duplicate tab seems to recreate the running state of the original tab so you can just continue where you were.

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

How do I set the path to a DLL file in Visual Studio?

Go through project properties -> Reference Paths

Then add folder with DLL's

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

Find duplicate lines in a file and count how many time each line was duplicated?

In windows using "Windows PowerShell" I used the command mentioned below to achieve this

Get-Content .\file.txt | Group-Object | Select Name, Count

Also we can use the where-object Cmdlet to filter the result

Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

Float a DIV on top of another DIV

Just add position, right and top to your class .close-image

.close-image {
    cursor: pointer;
    display: block;
    float: right;  
    z-index: 3;
    position: absolute; /*newly added*/
    right: 5px; /*newly added*/
    top: 5px;/*newly added*/
}

How to parse a month name (string) to an integer for comparison in C#?

You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:

int month = DateTime.Parse("1." + monthName + " 2008").Month;

The trick is to build a valid date to create a DateTime object.

Naming returned columns in Pandas aggregate function?

For pandas >= 0.25

The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func'). Detailed example from the PR linked above:

In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
   ...:                    'height': [9.1, 6.0, 9.5, 34.0],
   ...:                    'weight': [7.9, 7.5, 9.9, 198.0]})
   ...:

In [3]: df
Out[3]:
  kind  height  weight
0  cat     9.1     7.9
1  dog     6.0     7.5
2  cat     9.5     9.9
3  dog    34.0   198.0

In [4]: df.groupby('kind').agg(min_height=('height', 'min'), 
                               max_weight=('weight', 'max'))
Out[4]:
      min_height  max_weight
kind
cat          9.1         9.9
dog          6.0       198.0

It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:

In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})

In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
         B
  <lambda> <lambda 1>
A
a        0          1

and then .rename(), or in one go:

In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
   b  c
A
a  0  0

For pandas < 0.25

The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.

Series:

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

DataFrames:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version

According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.

# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                   'B': range(5),
                   'C': range(5)})

# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})

# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
    .agg({'B': 'sum', 'C': 'min'})
    .rename(columns={'B': 'foo', 'C': 'bar'})
)

Please see the 0.20 changelog for additional details.

Update 2017-01-03 in response to @JunkMechanic's comment.

With the old style dictionary syntax, it was possible to pass multiple lambda functions to .agg, since these would be renamed with the key in the passed dictionary:

>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})

    B    
  max min
A        
1   2   0
2   4   3

Multiple functions can also be passed to a single column as a list:

>>> df.groupby('A').agg({'B': [np.min, np.max]})

     B     
  amin amax
A          
1    0    2
2    3    4

However, this does not work with lambda functions, since they are anonymous and all return <lambda>, which causes a name collision:

>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>

To avoid the SpecificationError, named functions can be defined a priori instead of using lambda. Suitable function names also avoid calling .rename on the data frame afterwards. These functions can be passed with the same list syntax as above:

>>> def my_min(x):
>>>     return x.min()

>>> def my_max(x):
>>>     return x.max()

>>> df.groupby('A').agg({'B': [my_min, my_max]})

       B       
  my_min my_max
A              
1      0      2
2      3      4

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

For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.

function getDataUrl(file, callback2) {
        var callback = function (srcOrientation) {
            var reader2 = new FileReader();
            reader2.onload = function (e) {
                var srcBase64 = e.target.result;
                var img = new Image();

                img.onload = function () {
                    var width = img.width,
                        height = img.height,
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext("2d");

                    // set proper canvas dimensions before transform & export
                    if (4 < srcOrientation && srcOrientation < 9) {
                        canvas.width = height;
                        canvas.height = width;
                    } else {
                        canvas.width = width;
                        canvas.height = height;
                    }

                    // transform context before drawing image
                    switch (srcOrientation) {
                        case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
                        case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
                        case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
                        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
                        case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
                        case 7: ctx.transform(0, -1, -1, 0, height, width); break;
                        case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
                        default: break;
                    }

                    // draw image
                    ctx.drawImage(img, 0, 0);

                    // export base64
                    callback2(canvas.toDataURL());
                };

                img.src = srcBase64;
            }

            reader2.readAsDataURL(file);
        }

        var reader = new FileReader();
        reader.onload = function (e) {

            var view = new DataView(e.target.result);
            if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
            var length = view.byteLength, offset = 2;
            while (offset < length) {
                var marker = view.getUint16(offset, false);
                offset += 2;
                if (marker == 0xFFE1) {
                    if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
                    var little = view.getUint16(offset += 6, false) == 0x4949;
                    offset += view.getUint32(offset + 4, little);
                    var tags = view.getUint16(offset, little);
                    offset += 2;
                    for (var i = 0; i < tags; i++)
                        if (view.getUint16(offset + (i * 12), little) == 0x0112)
                            return callback(view.getUint16(offset + (i * 12) + 8, little));
                }
                else if ((marker & 0xFF00) != 0xFF00) break;
                else offset += view.getUint16(offset, false);
            }
            return callback(-1);
        };
        reader.readAsArrayBuffer(file);
    }

which can easily be called like such

getDataUrl(input.files[0], function (imgBase64) {
      vm.user.BioPhoto = imgBase64;
});

Android - how to make a scrollable constraintlayout?

You can use HorizontalScrollView and it'll work as well!

Linux cmd to search for a class file among jars irrespective of jar path

Most of the solutions are directly using grep command to find the class. However, it would not give you the package name of the class. Also if the jar is compressed, grep will not work.

This solution is using jar command to list the contents of the file and grep the class you are looking for.

It will print out the class with package name and also the jar file name.

find . -type f -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep Hello.class &&  echo {}'

You can also search with your package name like below:

find . -type f -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep com/mypackage/Hello.class &&  echo {}'

Load jQuery with Javascript and use jQuery

You need to run your code AFTER jQuery finished loading

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
    // your jQuery code here
} 

or if you're running it in an async function you could use await in the above code

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here

If you want to check first if jQuery already exists in the page, try this

Extracting an attribute value with beautifulsoup

I am using this with Beautifulsoup 4.8.1 to get the value of all class attributes of certain elements:

from bs4 import BeautifulSoup

html = "<td class='val1'/><td col='1'/><td class='val2' />"

bsoup = BeautifulSoup(html, 'html.parser')

for td in bsoup.find_all('td'):
    if td.has_attr('class'):
        print(td['class'][0])

Its important to note that the attribute key retrieves a list even when the attribute has only a single value.

100% Min Height CSS layout

Here is another solution based on vh, or viewpoint height, for details visit CSS units. It is based on this solution, which uses flex instead.

_x000D_
_x000D_
* {_x000D_
    /* personal preference */_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
html {_x000D_
    /* make sure we use up the whole viewport */_x000D_
    width: 100%;_x000D_
    min-height: 100vh;_x000D_
    /* for debugging, a red background lets us see any seams */_x000D_
    background-color: red;_x000D_
}_x000D_
body {_x000D_
    /* make sure we use the full width but allow for more height */_x000D_
    width: 100%;_x000D_
    min-height: 100vh; /* this helps with the sticky footer */_x000D_
}_x000D_
main {_x000D_
    /* for debugging, a blue background lets us see the content */_x000D_
    background-color: skyblue;_x000D_
 min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */_x000D_
}_x000D_
footer {_x000D_
    /* for debugging, a gray background lets us see the footer */_x000D_
    background-color: gray;_x000D_
 min-height:2.5em;_x000D_
}
_x000D_
<main>_x000D_
    <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
</main>_x000D_
<footer>_x000D_
    <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>_x000D_
    <p>This is the footer.</p>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.

You may find more information here:

Specifically:

1vw (viewport width) = 1% of viewport width
1vh (viewport height) = 1% of viewport height
1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest
1vmax (viewport minimum) = 1vw or 1vh, whatever is largest

REST vs JSON-RPC?

REST is tightly coupled with HTTP, so if you only expose your API over HTTP then REST is more appropriate for most (but not all) situations. However, if you need to expose your API over other transports like messaging or web sockets then REST is just not applicable.

Submitting a form by pressing enter without a submit button

Try:

<input type="submit" style="position: absolute; left: -9999px"/>

That will push the button waaay to the left, out of the screen. The nice thing with this is, you'd get graceful degradation when CSS is disabled.

Update - Workaround for IE7

As suggested by Bryan Downing + with tabindex to prevent tab reach this button (by Ates Goral):

<input type="submit" 
       style="position: absolute; left: -9999px; width: 1px; height: 1px;"
       tabindex="-1" />

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

how to do file upload using jquery serialization

$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
    type: "POST",
    data: formData,
    dataType: "json",
    url: form.attr('action'),
    processData: false,
    contentType: false,
    success: function(data) {
         alert('Sucess! Form data posted with file type of input also!');
    }
)};});

By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me

Using above code I am able to submit form data with file field also through Ajax

File tree view in Notepad++

step-1) On Notepad++ Toolbar:

Plugins -> Plugin Manager -> Show Plugin Manager -> Available . Then select the Explorer. And click Install.

(Note: As in above comments some people like SherloXplorer. Pls, note that this requires .Net v2 )

step-2) Again on Notepad++ Toolbar:

Explorer->Explorer

Now you can view files with tree view.

Update: After adding Explorer, right click to edit a file in Notepad++ may stop working. To make it work again, restart Notepad++ afresh.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

What is the difference between a Docker image and a container?

The core concept of Docker is to make it easy to create "machines" which in this case can be considered containers. The container aids in reusability, allowing you to create and drop containers with ease.

Images depict the state of a container at every point in time. So the basic workflow is:

  1. create an image
  2. start a container
  3. make changes to the container
  4. save the container back as an image

Timer function to provide time in nano seconds using C++

In general, for timing how long it takes to call a function, you want to do it many more times than just once. If you call your function only once and it takes a very short time to run, you still have the overhead of actually calling the timer functions and you don't know how long that takes.

For example, if you estimate your function might take 800 ns to run, call it in a loop ten million times (which will then take about 8 seconds). Divide the total time by ten million to get the time per call.

Converting DateTime format using razor

For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })

How do I decompile a .NET EXE into readable C# source code?

Reflector is no longer free in general, but they do offer it for free to open source developers: http://reflectorblog.red-gate.com/2013/07/open-source/

But a few companies like DevExtras and JetBrains have created free alternatives:

DevExtras CodeReflect

JetBrains DotPeek

.NET - How do I retrieve specific items out of a Dataset?

I prefer to use something like this:

int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");

or

int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index

How do I change selected value of select2 dropdown with JqGrid?

this.$("#yourSelector").select2("data", { id: 1, text: "Some Text" });

this should be of help.

android lollipop toolbar: how to hide/show the toolbar while scrolling?

For hiding the toolbar you can just do :

getSupportActionBar().hide();

So you just have to had a scroll listener and hide the toolbar when the user scroll !

Make element fixed on scroll

You can do that with some easy jQuery:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

Why is lock(this) {...} bad?

Take a look at the MSDN Topic Thread Synchronization (C# Programming Guide)

Generally, it is best to avoid locking on a public type, or on object instances beyond the control of your application. For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. Locking on a public data type, as opposed to an object, can cause problems for the same reason. Locking on literal strings is especially risky because literal strings are interned by the common language runtime (CLR). This means that there is one instance of any given string literal for the entire program, the exact same object represents the literal in all running application domains, on all threads. As a result, a lock placed on a string with the same contents anywhere in the application process locks all instances of that string in the application. As a result, it is best to lock a private or protected member that is not interned. Some classes provide members specifically for locking. The Array type, for example, provides SyncRoot. Many collection types provide a SyncRoot member as well.

How to avoid using Select in Excel VBA

This is an example that will clear the contents of cell "A1" (or more if the selection type is xllastcell, etc.). All done without having to select the cells.

Application.GoTo Reference:=Workbook(WorkbookName).Worksheets(WorksheetName).Range("A1")
Range(Selection,selection(selectiontype)).clearcontents 

Creating an iframe with given HTML dynamically

The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.

const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);

What are the differences between a pointer variable and a reference variable in C++?

You can use the difference between references and pointers if you follow a convention for arguments passed to a function. Const references are for data passed into a function, and pointers are for data passed out of a function. In other languages, you can explicit notate this with keywords such as in and out. In C++, you can declare (by convention) the equivalent. For example,

void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput)
{
   if (thisIsAnOuput)
      *thisIsAnOutput = thisIsAnInput;
}

The use of references as inputs and pointers as outputs is part of the Google style guide.

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

What is the maximum length of a URL in different browsers?

On Apple platforms (iOS/macOS/tvOS/watchOS), the limit may be a 2 GB long URL scheme, as seen by this comment in the source code of Swift:

// Make sure the URL string isn't too long.
// We're limiting it to 2GB for backwards compatibility with 32-bit executables using NS/CFURL
if ( (urlStringLength > 0) && (urlStringLength <= INT_MAX) )
{
...

On iOS, I've tested and confirmed that even a 300+ MB long URL is accepted. You can try such a long URL like this in Objective-C:

NSString *path = [@"a:" stringByPaddingToLength:314572800 withString:@"a" startingAtIndex:0];
NSString *js = [NSString stringWithFormat:@"window.location.href = \"%@\";", path];
[self.webView stringByEvaluatingJavaScriptFromString:js];

And catch if it succeed with:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"length: %@", @(request.URL.absoluteString.length));
    return YES;
}

How can I run dos2unix on an entire directory?

If it's a large directory you may want to consider running with multiple processors:

find . -type f -print0 | xargs -0 -n 1 -P 4 dos2unix 

This will pass 1 file at a time, and use 4 processors.

jQuery bind to Paste Event, how to get the content of the paste

There is an onpaste event that works in modern day browsers. You can access the pasted data using the getData function on the clipboardData object.

$("#textareaid").bind("paste", function(e){
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    alert(pastedData);
} );

Note that bind and unbind are deprecated as of jQuery 3. The preferred call is to on.

All modern day browsers support the Clipboard API.

See also: In Jquery How to handle paste?

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

Remove all values within one list from another list?

a = range(1,10)
itemsToRemove = set([2, 3, 7])
b = filter(lambda x: x not in itemsToRemove, a)

or

b = [x for x in a if x not in itemsToRemove]

Don't create the set inside the lambda or inside the comprehension. If you do, it'll be recreated on every iteration, defeating the point of using a set at all.

How to concatenate string variables in Bash

If what you are trying to do is to split a string into several lines, you can use a backslash:

$ a="hello\
> world"
$ echo $a
helloworld

With one space in between:

$ a="hello \
> world"
$ echo $a
hello world

This one also adds only one space in between:

$ a="hello \
>      world"
$ echo $a
hello world

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Asp Net Web API 2.1 get client IP address

Following link might help you. Here's code from the following link.

reference : getting-the-client-ip-via-asp-net-web-api

using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;


namespace Trikks.Controllers.Api
{
    public class IpController : ApiController
    {
          public string GetIp()
          {
                return GetClientIp();
          }

          private string GetClientIp(HttpRequestMessage request = null)
          {
                request = request ?? Request;

                if (request.Properties.ContainsKey("MS_HttpContext"))
                {
                      return   ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
                }
                else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
                {
                     RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
                     return prop.Address;
                }
                else if (HttpContext.Current != null)
                {
                    return HttpContext.Current.Request.UserHostAddress;
                }
                else
                {
                      return null;
                }
           }
     }
}

Another way of doing this is below.

reference: how-to-access-the-client-s-ip-address

For web hosted version

string clientAddress = HttpContext.Current.Request.UserHostAddress;

For self hosted

object property;
        Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property);
        RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty;

C#: how to get first char of a string?

Just MyString[0]. This uses the String.Chars indexer.

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

this.dataStore.data.find((element, index, obj) => {
    // ...

    return true; // or false
});

or:

this.dataStore.data.find(element => {
    // ...

    return true; // or false
});

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

Because it's not.

Indexing is covered by IList. IEnumerable means "I have some of the powers of IList, but not all of them."

Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.

How can I create a carriage return in my C# string

<br /> works for me

So...

String body = String.Format(@"New user: 
 <br /> Name: {0}
 <br /> Email: {1}
 <br /> Phone: {2}", Name, Email, Phone);

Produces...

New user:
Name: Name
Email: Email
Phone: Phone

How to download dependencies in gradle

For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. enter image description here

React - Preventing Form Submission

function onTestClick(evt) {
  evt.stopPropagation();
}

Send Email Intent

This code is working in my device

Intent mIntent = new Intent(Intent.ACTION_SENDTO);
mIntent.setData(Uri.parse("mailto:"));
mIntent.putExtra(Intent.EXTRA_EMAIL  , new String[] {"[email protected]"});
mIntent.putExtra(Intent.EXTRA_SUBJECT, "");
startActivity(Intent.createChooser(mIntent, "Send Email Using..."));

How to add an element to Array and shift indexes?

Here is a quasi-oneliner that does it:

String[] prependedArray = new ArrayList<String>() {
  {
    add("newElement");
    addAll(Arrays.asList(originalArray));
  }
}.toArray(new String[0]);

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...