Programs & Examples On #Xmlconfigurator

How to use log4net in Asp.net core 2.0

I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net(). Here is a brief summary of how I added log4Net to my Asp.Net Core project.

  1. Add the nugget package Microsoft.Extensions.Logging.Log4Net.AspNetCore
  2. Add the log4net.config file in your root application folder

  3. Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net

First you have to import the package using Microsoft.Extensions.Logging; using the using statement

Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();
            ....
        }

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

You can use the following maven dependency in your pom file. Otherwise, you can download the following two jars from net and add it to your build path.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
</dependency>

This is copied from my working project. First make sure it is working in your project. Then you can change the versions to use any other(versions) compatible jars.

For AggCat, you can refer the POM file of the sample java application.

https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/CustomerAccountData/Java/AggCatSampleApplication/pom.xml

Thanks

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

How to tell if a <script> tag failed to load

I know this is an old thread but I got a nice solution to you (I think). It's copied from an class of mine, that handles all AJAX stuff.

When the script cannot be loaded, it set an error handler but when the error handler is not supported, it falls back to a timer that checks for errors for 15 seconds.

function jsLoader()
{
    var o = this;

    // simple unstopable repeat timer, when t=-1 means endless, when function f() returns true it can be stopped
    o.timer = function(t, i, d, f, fend, b)
    {
        if( t == -1 || t > 0 )
        {
            setTimeout(function() {
                b=(f()) ? 1 : 0;
                o.timer((b) ? 0 : (t>0) ? --t : t, i+((d) ? d : 0), d, f, fend,b );
            }, (b || i < 0) ? 0.1 : i);
        }
        else if(typeof fend == 'function')
        {
            setTimeout(fend, 1);
        }
    };

    o.addEvent = function(el, eventName, eventFunc)
    {
        if(typeof el != 'object')
        {
            return false;
        }

        if(el.addEventListener)
        {
            el.addEventListener (eventName, eventFunc, false);
            return true;
        }

        if(el.attachEvent)
        {
            el.attachEvent("on" + eventName, eventFunc);
            return true;
        }

        return false;
    };

    // add script to dom
    o.require = function(s, delay, baSync, fCallback, fErr)
    {
        var oo = document.createElement('script'),
        oHead = document.getElementsByTagName('head')[0];
        if(!oHead)
        {
            return false;
        }

        setTimeout( function() {
            var f = (typeof fCallback == 'function') ? fCallback : function(){};
            fErr = (typeof fErr == 'function') ? fErr : function(){
                alert('require: Cannot load resource -'+s);
            },
            fe = function(){
                if(!oo.__es)
                {
                    oo.__es = true;
                    oo.id = 'failed';
                    fErr(oo);
                }
            };
            oo.onload = function() {
                oo.id = 'loaded';
                f(oo);
            };
            oo.type = 'text/javascript';
            oo.async = (typeof baSync == 'boolean') ? baSync : false;
            oo.charset = 'utf-8';
            o.__es = false;
            o.addEvent( oo, 'error', fe ); // when supported

            // when error event is not supported fall back to timer
            o.timer(15, 1000, 0, function() {
                return (oo.id == 'loaded');
            }, function(){ 
                if(oo.id != 'loaded'){
                    fe();
                }
            });
            oo.src = s;
            setTimeout(function() {
                try{
                    oHead.appendChild(oo);
                }catch(e){
                    fe();
                }
            },1); 
        }, (typeof delay == 'number') ? delay : 1);  
        return true;
    };

}

$(document).ready( function()
{
    var ol = new jsLoader();
    ol.require('myscript.js', 800, true, function(){
        alert('loaded');
    }, function() {
        alert('NOT loaded');
    });
});

How do I change the android actionbar title and icon

In Android 5.0 material design guidelines discourage the use of icon in actionBar

to enable it add the following code

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);

credit goes to author of this article

How does Django's Meta class work?

You are asking a question about two different things:

  1. Meta inner class in Django models:

    This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.

    Short explanation is here: Django docs: Models: Meta options

    List of available meta options is here: Django docs: Model Meta options

    For latest version of Django: Django docs: Model Meta options

  2. Metaclass in Python:

    The best description is here: What are metaclasses in Python?

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

NSString * path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"jpg"];
UIImage * img = [[UIImage alloc]initWithContentsOfFile:path];
CGImageRef image = [img CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(image));
const unsigned char * buffer =  CFDataGetBytePtr(data);

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

Your branch is ahead of 'origin/master' by 3 commits

Came across this issue after I merged a pull request on Bitbucket.

Had to do

git fetch

and that was it.

Change button text from Xcode?

myapp.h

{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;

myapp.m

@synthesize myButton;

-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}

How do you configure an OpenFileDialog to select folders?

The Ookii Dialogs for WPF library has a class that provides an implementation of a folder browser dialog for WPF.

https://github.com/augustoproiete/ookii-dialogs-wpf

Ookii Folder Browser Dialog

There's also a version that works with Windows Forms.

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I would do it this this way:

  1. Stage all unstaged changes.

    git add .
    
  2. Stash the changes.

    git stash save
    
  3. Sync with remote.

    git pull -r
    
  4. Reapply the local changes.

    git stash pop
    

    or

    git stash apply
    

How to execute AngularJS controller function on page load?

I could never get $viewContentLoaded to work for me, and ng-init should really only be used in an ng-repeat (according to the documentation), and also calling a function directly in a controller can cause errors if the code relies on an element that hasn't been defined yet.

This is what I do and it works for me:

$scope.$on('$routeChangeSuccess', function () {
  // do something
});

Unless you're using ui-router. Then it's:

$scope.$on('$stateChangeSuccess', function () {
  // do something
});

Why doesn't margin:auto center an image?

I have found... margin: 0 auto; works for me. But I have also seen it NOT work due to the class being trumped by another specificity that had ... float:left; so watch for that you may need to add ... float:none; this worked in my case as I was coding a media query.

Is it possible to insert HTML content in XML document?

Just put the html tags with there content and add the xmlns attribute with quotes after the equals and in between the quotes is http://www.w3.org/1999/xhtml

Create a copy of a table within the same database DB2

Two steps works fine:

create table bu_x as (select a,b,c,d from x ) WITH no data;

insert into bu_x (a,b,c,d) select select a,b,c,d from x ;

Converting a String to DateTime

I just found an elegant way:

Convert.ChangeType("2020-12-31", typeof(DateTime));

Convert.ChangeType("2020/12/31", typeof(DateTime));

Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));

Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));

Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"

How to use SortedMap interface in Java?

tl;dr

Use either of the Map implementations bundled with Java 6 and later that implement NavigableMap (the successor to SortedMap):

  • Use TreeMap if running single-threaded, or if the map is to be read-only across threads after first being populated.
  • Use ConcurrentSkipListMap if manipulating the map across threads.

NavigableMap

FYI, the SortedMap interface was succeeded by the NavigableMap interface.

You would only need to use SortedMap if using 3rd-party implementations that have not yet declared their support of NavigableMap. Of the maps bundled with Java, both of the implementations that implement SortedMap also implement NavigableMap.

Interface versus concrete class

s SortedMap the best answer? TreeMap?

As others mentioned, SortedMap is an interface while TreeMap is one of multiple implementations of that interface (and of the more recent NavigableMap.

Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.

NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ; 
currentAssignments.put( bob , setUpNewVendorsProject ) ; 

This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:

NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;

…and the rest of your code using that map continues to work.

Choosing implementation

There are ten implementations of Map bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.

Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap remembers original insertion order.

Table of map implementations in Java 11, comparing their features

How do I set the default font size in Vim?

I cross over the same problem I put the following code in the folder ~/.gvimrc and it works.

set guifont=Monaco:h20

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

I had the same problem while trying to consume net.tcp wcf service endpoint in a http asmx service.

As I saw no one wrote specific answer WHY is this problem occurring, but only how to be handled properly.

I've been struggling with it several days in a row and finally I found out where the problem comes from in my case.

Initially I thought that when you make a reference to a service the config file will be configured regarding security tag the same way as it's in the source, but that was not the case and I should take care of it manually. In my case I had only

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService"
    </binding>
</netTcpBinding>`

Later I saw that the security part is missing and it should looks like this

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService" transferMode="Buffered">
      <security mode="None">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </netTcpBinding>

The second problem in my case was that I was using transferMode="Streamed" on my source WCF service and in the client I had nothing specific about it, which was bad, because the default transferMode is Buffered and it's important on both places source and client to be configured in the same way.

What are the benefits of using C# vs F# or F# vs C#?

To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)

First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.

However, there are a few cases where F# might not be the best choice:

  • Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.

    • Yes, interop is a pretty big net and can result in a bit of friction with some libraries.

    • I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.

  • Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.

    • This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.

    • Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)

  • Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.

  • But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.

I wrote about this a while ago: Why NOT F#?

How to move Jenkins from one PC to another

In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:

  1. Install ThinBackup on both the source and the target Jenkins servers

  2. Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)

  3. On the source Jenkins, go to ThinBackup ? Backup Now

  4. Copy from Jenkins source backup directory to the Jenkins target backup directory

  5. On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.

  6. If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.

  7. If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity> to false, and restart Jenkins.

Swift - how to make custom header for UITableView?

Did you set the section header height in the viewDidLoad?

self.tableView.sectionHeaderHeight = 70

Plus you should replace

self.view.addSubview(view)

by

view.addSubview(label)

Finally you have to check your frames

let view = UIView(frame: CGRect.zeroRect)

and eventually the desired text color as it seems to be currently white on white.

How to make a button redirect to another page using jQuery or just Javascript

You can use window.location

window.location="/newpage.php";

Or you can just make the form that the search button is in have a action of the page you want.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

Write Base64-encoded image to file

Other option using apache-commons:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

...
File file = new File( "path" );
byte[] bytes = Base64.decodeBase64( "base64" );
FileUtils.writeByteArrayToFile( file, bytes );

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

How to merge rows in a column into one cell in excel?

For Excel 2011 on Mac it's different. I did it as a three step process.

  1. Create a column of values in column A.
  2. In column B, to the right of the first cell, create a rule that uses the concatenate function on the column value and ",". For example, assuming A1 is the first row, the formula for B1 is =B1. For the next row to row N, the formula is =Concatenate(",",A2). You end up with:
QA
,Sekuli
,Testing
,Applitools
,Visual Testing
,Test Automation
,Selenium
  1. In column C create a formula that concatenates all previous values. Because it is additive you will get all at the end. The formula for cell C1 is =B1. For all other rows to N, the formula is =Concatenate(C1,B2). And you get:
QA,Sekuli
QA,Sekuli,Testing
QA,Sekuli,Testing,Applitools
QA,Sekuli,Testing,Applitools,Visual Testing
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium

The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.

Android Closing Activity Programmatically

What about the Activity.finish() method (quoting) :

Call this when your activity is done and should be closed.

How do I drop a foreign key in SQL Server?

I don't know MSSQL but would it not be:

alter table company drop **constraint** Company_CountryID_FK;

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

How can I configure Logback to log different levels for a logger to different destinations?

okay, here is my favorite xml way of doing it. I do this for the eclipse version so I can

  • click on stuff to take me to the log statements and
  • see info and below in black and warn/severe in red

and for some reason SO is not showing this all properly but most seems to be there...

<configuration scan="true" scanPeriod="30 seconds">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      
          <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator"> 
            <expression>
               e.level.toInt() &lt;= INFO.toInt()
            </expression>
          </evaluator>
          <OnMismatch>DENY</OnMismatch>
          <OnMatch>NEUTRAL</OnMatch>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> 
            <level>warn</level>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
        <target>System.err</target>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STDERR"/>
    </root>
</configuration>

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

just set position: fixed to the footer element (instead of relative)

Jsbin example

Note that you may need to also set a margin-bottom to the main element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer

How to change the sender's name or e-mail address in mutt?

For a one time change you can do this:

export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]

Is it ok to run docker from inside docker?

I answered a similar question before on how to run a Docker container inside Docker.

To run docker inside docker is definitely possible. The main thing is that you run the outer container with extra privileges (starting with --privileged=true) and then install docker in that container.

Check this blog post for more info: Docker-in-Docker.

One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.

However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post

So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.

Difference between "process.stdout.write" and "console.log" in node.js?


Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.

According to my puglin serverline : console = new Console(consoleOptions) you can rewrite Console class with your own readline system.

You can see code source of console.log:


See more :

How to make an inline element appear on new line, or block element not occupy the whole line?

You can give it a property display block; so it will behave like a div and have its own line

CSS:

.feature_desc {
   display: block;
   ....
}

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Another solution is the following:

ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)

Php $_POST method to get textarea value

//My Form
<form id="someform">
        <div class="input-group">
            <textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea> 
            <span class="input-group-addon">                                            
                <button type="submit" name="post_comment" class="btn btn-primary">
                    Post
                </button>
            </span>
        </div>
    </form>

//your text area get value to URL
<?php
        if(isset($_POST['post_comment']))
        {
            echo htmlspecialchars($_POST['post']);
        }

    ?>

//print the value using get
echo $_GET['post'];

//url must be like this
http://localhost/blog/home.php?post=asdasdsad&post_comment=

//post value has asdasdsad so it will print to your page

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

How can I specify a display?

Even i faced the same in CentOS 6.8.

yum reinstall xorg*

End your current session and open another session in tool like mobiXterm. Make sure session has X11 forwarding enabled in the tool.

Swift Set to Array

The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:

for item in myItemSet {
   ...
}

Or, to use the "sorted" method:

let itemsArray = myItemSet.sorted()

It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.

If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:

let itemsArray = myItemSet.map { $0 }

Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:

var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
 itemsArray = typedSet.map { $0 }
}

Passing data from controller to view in Laravel

try with this code :

Controller:
-----------------------------
 $fromdate=date('Y-m-d',strtotime(Input::get('fromdate'))); 
        $todate=date('Y-m-d',strtotime(Input::get('todate'))); 

 $datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To 
        return view('inventoryreport/inventoryreportview', compact('datas'));

View Page : 
@foreach($datas as $student)
   {{$student}}

@endforeach
[Link here]

How to call a php script/function on a html button click

Use jQuery.In the HTML page -

<button type="button">Click Me</button>

<script>
$(document).ready(function() {
$("button").click(function(){
  $.ajax({
    url:"php_page.php", //the page containing php script
    type: "POST", //request type
    success:function(result){
    alert(result);
    }
  });
});
})
</script>

Php page -

echo "Hello";

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Below code gives in hh:mm format.

select RIGHT(LEFT(job_end- job_start,17),5)

Sort array of objects by string property value

You can use a reusable sort function.

Array.prototype.order= function(prop, methods = {}) {
  let swipe = 1;
  if (prop?.constructor == Object) methods = prop;
  swipe = methods.reverse ? -1 : 1;
  function key(x) {
    if (typeof prop == "string")
      return methods.insensitive ? String(x[prop]).toLowerCase() : x[prop];
    if (methods.insensitive) return String(x).toLowerCase();
    return x;
  }
  this.sort((a, b) => {
    if (key(a) < key(b)) return -1 * swipe;
    if (key(b) < key(a)) return 1 * swipe;
    return 0;
  });
  return this;
};

Its can be use to sort both Array and Object in array
.

let arr = [6, 2, 4, 1, 5, 3];
let arr2 = [
  { name: "Bar", age: 12 },
  { name: "Nur", age: 18 },
  { name: "foo", age: 30 },
  { name: "bazz", age: 15 }
];
arr.order({ reverse: true }); //  [ 6, 5, 4, 3, 2, 1 ]
arr2.order("name", { reverse: 1, insensitive: 0});
let arr3 = [...arr2].order("age");  // new sorted array created from arr2 (But does not change original array)

1nd (optional) > to sort object contain in array.
2rd is method > { reverse: Boolean, insensitive: Boolean }

What is MVC and what are the advantages of it?

MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).

It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.

Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).

Can't bind to 'routerLink' since it isn't a known property

When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.

Convert string to date then format the date

Currently, i prefer using this methods:

String data = "Date from Register: ";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Verify that OS.Version is > API 26 (OREO)
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); 
// Origin format
            LocalDate localDate = LocalDate.parse(capitalModels.get(position).getDataServer(), formatter); // Parse String (from server) to LocalDate
            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd/MM/yyyy"); 
//Output format
            data = "Data de Registro: "+formatter1.format(localDate); // Output
            Toast.makeText(holder.itemView.getContext(), data, Toast.LENGTH_LONG).show();
        }else{ 
//Same resolutions, just use legacy methods to oldest android OS versions.
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd",Locale.getDefault());
            try {
                Date date = format.parse(capitalModels.get(position).getDataServer());
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
                data = "Date from Register: "+formatter.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

How to set border on jPanel?

Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:

public GoBoard(){
    this.linien = 9;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

public GoBoard(int pLinien){
    this.linien = pLinien;

}

If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:

// default constructor
public GoBoard(){
    this(9);  // calls other constructor
}

public GoBoard(int pLinien){
    this.linien = pLinien;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,

class GoTest {
   private static final int JB_WIDTH = 400;
   private static final int JB_HEIGHT = JB_WIDTH;

   private static void initGui() {
      JFrame frame = new JFrame("GoBoard");
      GoBoard jboard = new GoBoard();
      jboard.setLayout(new BorderLayout(10, 10));

      JPanel holdingPanel = new JPanel(new BorderLayout());
      int eb = 20;
      holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
      holdingPanel.add(jboard, BorderLayout.CENTER);
      frame.add(holdingPanel, BorderLayout.CENTER);
      jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //!! frame.setSize(400, 400);
      frame.pack();
      frame.setVisible(true);
   }

// .... etc....

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)

$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
    //Process your response
    $("#ajaxLoader").hide();
});

If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-

$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
               .ajaxStop(function() { $(this).hide(); });

Using blockUI is similar for example with mark up like:-

<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
    <p id="result"></p>
</div>

<div id="ajaxLoader" style="display:none">
    <h2>Please wait</h2>
    <p>I'm getting my AJAX on!</p>
</div>

And using jQuery:-

$(function() {
    $("#jsonLink").click(function(e) {
        $.post(this.href, function(result) {
            $("#resultContainer").fadeIn();
            $("#result").text(result.Answer);
        }, "json");
        return false;
    });
    $("#ajaxLoader").ajaxStart(function() {
                          $.blockUI({ message: $("#ajaxLoader") });
                     })
                    .ajaxStop(function() { 
                          $.unblockUI();
                     });
});

Getting the first index of an object

This will not give you the first one as javascript objects are unordered, however this is fine in some cases.

myObject[Object.keys(myObject)[0]]

How to clear cache of Eclipse Indigo

you can use -clean parameter while starting eclipse like

C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean

How do you stop tracking a remote branch in Git?

Here's a one-liner to remove all remote-tracking branches matching a pattern:

git branch -rd $(git branch -a | grep '{pattern}' | cut -d'/' -f2-10 | xargs)

jQuery get value of selected radio button

See below for working example with a collection of radio groups each associated with different sections. Your naming scheme is important, but ideally you should try and use a consistent naming scheme for inputs anyway (especially when they're in sections like here).

_x000D_
_x000D_
$('#submit').click(function(){_x000D_
  var section = $('input:radio[name="sec_num"]:checked').val();_x000D_
  var question = $('input:radio[name="qst_num"]:checked').val();_x000D_
  _x000D_
  var selectedVal = checkVal(section, question);_x000D_
  $('#show_val_div').text(selectedVal);_x000D_
  $('#show_val_div').show();_x000D_
});_x000D_
_x000D_
function checkVal(section, question) {_x000D_
  var value = $('input:radio[name="sec'+section+'_r'+question+'"]:checked').val() || "Selection Not Made";_x000D_
  return value;_x000D_
}
_x000D_
* { margin: 0; }_x000D_
div { margin-bottom: 20px; padding: 10px; }_x000D_
h5, label { display: inline-block; }_x000D_
.small { font-size: 12px; }_x000D_
.hide { display: none; }_x000D_
#formDiv { padding: 10px; border: 1px solid black; }_x000D_
.center { display:block; margin: 0 auto; text-align:center; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="center">_x000D_
  <div>_x000D_
    <h4>Section 1</h4>_x000D_
_x000D_
    <h5>First question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec1_r1" value="(1:1) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec1_r1" value="(1:1) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Second question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec1_r2" value="(1:2) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec1_r2" value="(1:2) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Third Question</h5>_x000D_
    <label class="small"><input type="radio" name="sec1_r3" value="(1:3) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec1_r3" value="(1:3) NO"> NO</label>_x000D_
  </div>_x000D_
_x000D_
  <div>_x000D_
    <h4>Section 2</h4>_x000D_
    <h5>First question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec2_r1" value="(2:1) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec2_r1" value="(2:1) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Second question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec2_r2" value="(2:2) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec2_r2" value="(2:2) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Third Question</h5>_x000D_
    <label class="small"><input type="radio" name="sec2_r3" value="(2:3) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec2_r3" value="(2:3) NO"> NO</label>_x000D_
  </div>_x000D_
_x000D_
  <div>_x000D_
    <h4>Section 3</h4>_x000D_
    <h5>First question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec3_r1" value="(3:1) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec3_r1" value="(3:1) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Second question text</h5>_x000D_
    <label class="small"><input type="radio" name="sec3_r2" value="(3:2) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec3_r2" value="(3:2) NO"> NO</label>_x000D_
    <br/>_x000D_
    <h5>Third Question</h5>_x000D_
    <label class="small"><input type="radio" name="sec3_r3" value="(3:3) YES"> YES</label>_x000D_
    <label class="small"><input type="radio" name="sec3_r3" value="(3:3) NO"> NO</label>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div id="formDiv" class="center">_x000D_
  <form target="#show_val_div" method="post">_x000D_
    <p>Choose Section Number</p>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="sec_num" value="1"> 1</label>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="sec_num" value="2"> 2</label>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="sec_num" value="3"> 3</label>_x000D_
    <br/><br/>_x000D_
    _x000D_
    <p>Choose Question Number</p>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="qst_num" value="1"> 1</label>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="qst_num" value="2"> 2</label>_x000D_
    <label class="small">_x000D_
      <input type="radio" name="qst_num" value="3"> 3</label>_x000D_
    <br/><br/>_x000D_
    _x000D_
    <input id="submit" type="submit" value="Show Value">_x000D_
    _x000D_
  </form>_x000D_
  <br/>_x000D_
  <p id="show_val_div"></p>_x000D_
</div>_x000D_
<br/><br/><br/>
_x000D_
_x000D_
_x000D_

SQL MERGE statement to update data

If you need just update your records in energydata based on data in temp_energydata, assuming that temp_enerydata doesn't contain any new records, then try this:

UPDATE e SET e.kWh = t.kWh
  FROM energydata e INNER JOIN 
       temp_energydata t ON e.webmeterID = t.webmeterID AND 
                            e.DateTime = t.DateTime

Here is working sqlfiddle

But if temp_energydata contains new records and you need to insert it to energydata preferably with one statement then you should definitely go with the answer that Bacon Bits gave.

Checking for empty result (php, pdo, mysql)

One more approach to consider:

When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.

$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
    // non-repetitive markup code here
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

Is there a pretty print for PHP?

I made this function to print an array for debugging:

    function print_a($arr) {
        print '<code><pre style="text-align:left; margin:10px;">'.print_r($arr, TRUE).'</pre></code>';
    }

Hope it helps, Tziuka S.

Best way to get application folder path

  1. Application.StartupPathand 7. System.IO.Path.GetDirectoryName(Application.ExecutablePath) - Is only going to work for Windows Forms application

  2. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)

    Is going to give you something like: "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\legal-services\\e84f415e\\96c98009\\assembly\\dl3\\42aaba80\\bcf9fd83_4b63d101" which is where the page that you are running is.

  3. AppDomain.CurrentDomain.BaseDirectory for web application could be useful and will return something like "C:\\hg\\Services\\Services\\Services.Website\\" which is base directory and is quite useful.

  4. System.IO.Directory.GetCurrentDirectory() and 5. Environment.CurrentDirectory

will get you location of where the process got fired from - so for web app running in debug mode from Visual Studio something like "C:\\Program Files (x86)\\IIS Express"

  1. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

will get you location where .dll that is running the code is, for web app that could be "file:\\C:\\hg\\Services\\Services\\Services.Website\\bin"

Now in case of for example console app points 2-6 will be directory where .exe file is.

Hope this saves you some time.

How to check if a date is in a given range?

Convert both dates to timestamps then do

pseudocode:

if date_from_user > start_date && date_from_user < end_date
    return true

What's the most concise way to read query parameters in AngularJS?

Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode.

You could simply use:

$location.search().target

to get access to the 'target' search param.

For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
function MyCtrl($scope, $location) {_x000D_
_x000D_
    $scope.location = $location;_x000D_
    $scope.$watch('location.search()', function() {_x000D_
        $scope.target = ($location.search()).target;_x000D_
    }, true);_x000D_
_x000D_
    $scope.changeTarget = function(name) {_x000D_
        $location.search('target', name);_x000D_
    }_x000D_
}
_x000D_
<div ng-controller="MyCtrl">_x000D_
_x000D_
    <a href="#!/test/?target=Bob">Bob</a>_x000D_
    <a href="#!/test/?target=Paul">Paul</a>_x000D_
    _x000D_
    <hr/>    _x000D_
    URL 'target' param getter: {{target}}<br>_x000D_
    Full url: {{location.absUrl()}}_x000D_
    <hr/>_x000D_
    _x000D_
    <button ng-click="changeTarget('Pawel')">target=Pawel</button>_x000D_
    _x000D_
</div>
_x000D_
_x000D_
_x000D_

What's alternative to angular.copy in Angular

As others have already pointed out, using lodash or underscore is probably the best solution. But if you do not need those libraries for anything else, you can probably use something like this:

  function deepClone(obj) {

    // return value is input is not an Object or Array.
    if (typeof(obj) !== 'object' || obj === null) {
      return obj;    
    }

    let clone;

    if(Array.isArray(obj)) {
      clone = obj.slice();  // unlink Array reference.
    } else {
      clone = Object.assign({}, obj); // Unlink Object reference.
    }

    let keys = Object.keys(clone);

    for (let i=0; i<keys.length; i++) {
      clone[keys[i]] = deepClone(clone[keys[i]]); // recursively unlink reference to nested objects.
    }

    return clone; // return unlinked clone.

  }

That's what we decided to do.

Difference between natural join and inner join

A Natural Join is where 2 tables are joined on the basis of all common columns.

common column : is a column which has same name in both tables + has compatible datatypes in both the tables. You can use only = operator

A Inner Join is where 2 tables are joined on the basis of common columns mentioned in the ON clause.

common column : is a column which has compatible datatypes in both the tables but need not have the same name. You can use only any comparision operator like =, <=, >=, <, >, <>

How to make an "alias" for a long path?

Maybe it's better to use links

Soft Link

Symbolic or soft link (files or directories, more flexible and self documenting)

#      Source                            Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard Link

Hard link (files only, less flexible and not self documenting)

#    Source                            Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

How to create a link to a directory

Hint: If you need not to see the link in your home you can start it with a dot . ; then it will be hidden by default then you can access it like

cd ~/.myHiddelLongDirLink

Copy/duplicate database without using mysqldump

I don't really know what you mean by "local access". But for that solution you need to be able to access over ssh the server to copy the files where is database is stored.

I cannot use mysqldump, because my database is big (7Go, mysqldump fail) If the version of the 2 mysql database is too different it might not work, you can check your mysql version using mysql -V.

1) Copy the data from your remote server to your local computer (vps is the alias to your remote server, can be replaced by [email protected])

ssh vps:/etc/init.d/mysql stop
scp -rC vps:/var/lib/mysql/ /tmp/var_lib_mysql
ssh vps:/etc/init.d/apache2 start

2) Import the data copied on your local computer

/etc/init.d/mysql stop
sudo chown -R mysql:mysql /tmp/var_lib_mysql
sudo nano /etc/mysql/my.cnf
-> [mysqld]
-> datadir=/tmp/var_lib_mysql
/etc/init.d/mysql start

If you have a different version, you may need to run

/etc/init.d/mysql stop
mysql_upgrade -u root -pPASSWORD --force #that step took almost 1hrs
/etc/init.d/mysql start

Difference between Hive internal tables and external tables?

Hive tables can be created as EXTERNAL or INTERNAL. This is a choice that affects how data is loaded, controlled, and managed.

Use EXTERNAL tables when:

  1. The data is also used outside of Hive. For example, the data files are read and processed by an existing program that doesn't lock the files.
  2. Data needs to remain in the underlying location even after a DROP TABLE. This can apply if you are pointing multiple schemas (tables or views) at a single data set or if you are iterating through various possible schemas.
  3. You want to use a custom location such as ASV.
  4. Hive should not own data and control settings, dirs, etc., you have another program or process that will do those things.
  5. You are not creating table based on existing table (AS SELECT).

Use INTERNAL tables when:

The data is temporary.

You want Hive to completely manage the lifecycle of the table and data.

Convert a number into a Roman Numeral in javaScript

I personally think the neatest way (not by any means the fastest) is with recursion.

function convert(num) { 
  if(num < 1){ return "";}
  if(num >= 40){ return "XL" + convert(num - 40);}
  if(num >= 10){ return "X" + convert(num - 10);}
  if(num >= 9){ return "IX" + convert(num - 9);}
  if(num >= 5){ return "V" + convert(num - 5);}
  if(num >= 4){ return "IV" + convert(num - 4);}
  if(num >= 1){ return "I" + convert(num - 1);}  
}
console.log(convert(39)); 
//Output: XXXIX

This will only support numbers 1-40, but it can easily be extended by following the pattern.

Collections.emptyList() vs. new instance

Use Collections.emptyList() if you want to make sure that the returned list is never modified.

This is what is returned on calling emptyList():

/**
 * The empty list (immutable). 
 */
public static final List EMPTY_LIST = new EmptyList();

Get content uri from file path in android

// This code works for images on 2.2, not sure if any other media types

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

How do I kill the process currently using a port on localhost in Windows?

Step 1 (same is in accepted answer written by KavinduWije):

netstat -ano | findstr :yourPortNumber

Change in Step 2 to:

tskill typeyourPIDhere 

Note: taskkill is not working in some git bash terminal

Using Bootstrap Modal window as PartialView

I do this with mustache.js and templates (you could use any JavaScript templating library).

In my view, I have something like this:

<script type="text/x-mustache-template" id="modalTemplate">
    <%Html.RenderPartial("Modal");%>
</script>

...which lets me keep my templates in a partial view called Modal.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <div>
        <div class="modal-header">
            <a class="close" data-dismiss="modal">&times;</a>
            <h3>{{Name}}</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped table-condensed">
                <tbody>
                    <tr><td>ID</td><td>{{Id}}</td></tr>
                    <tr><td>Name</td><td>{{Name}}</td></tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>
        </div>
    </div>

I create placeholders for each modal in my view:

<%foreach (var item in Model) {%>
    <div data-id="<%=Html.Encode(item.Id)%>"
         id="modelModal<%=Html.Encode(item.Id)%>" 
         class="modal hide fade">
    </div>
<%}%>

...and make ajax calls with jQuery:

<script type="text/javascript">
    var modalTemplate = $("#modalTemplate").html()
    $(".modal[data-id]").each(function() {
        var $this = $(this)
        var id = $this.attr("data-id")
        $this.on("show", function() {
            if ($this.html()) return
            $.ajax({
                type: "POST",
                url: "<%=Url.Action("SomeAction")%>",
                data: { id: id },
                success: function(data) {
                    $this.append(Mustache.to_html(modalTemplate, data))
                }
            })
        })
    })
</script>

Then, you just need a trigger somewhere:

<%foreach (var item in Model) {%>
    <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
        <%=Html.Encode(item.DutModel.Name)%>
    </a>
<%}%>

What is the advantage of using heredoc in PHP?

First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.

Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.

Formatting doesn't fit general indentation rules, but I don't think it's a big deal.

       //some code at it's proper level
       $this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
       $this->title = "Feedback";
       //and so on

As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them

$sql = "SELECT * FROM $tablename
        WHERE id in [$order_ids_list]
        AND product_name = 'widgets'";

$x = 'The point of the "argument" was to illustrate the use of here documents';

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Came here searching for best practices in abstracting code to submodules when working in Notebooks. I'm not sure that there is a best practice. I have been proposing this.

A project hierarchy as such:

+-- ipynb
¦   +-- 20170609-Examine_Database_Requirements.ipynb
¦   +-- 20170609-Initial_Database_Connection.ipynb
+-- lib
    +-- __init__.py
    +-- postgres.py

And from 20170609-Initial_Database_Connection.ipynb:

    In [1]: cd ..

    In [2]: from lib.postgres import database_connection

This works because by default the Jupyter Notebook can parse the cd command. Note that this does not make use of Python Notebook magic. It simply works without prepending %bash.

Considering that 99 times out of a 100 I am working in Docker using one of the Project Jupyter Docker images, the following modification is idempotent

    In [1]: cd /home/jovyan

    In [2]: from lib.postgres import database_connection

Chrome not rendering SVG referenced via <img> tag

I had a similar problem and the existing answers to this either weren't applicable, or worked but we couldn't use them for other reasons. So I had to figure out what Chrome disliked about our SVGs.

In our case in turned out to be that the id attribute of the symbol tag in the SVG file had a : in it, which Chrome didn't like. Soon as I removed the : it worked fine.

Bad:

<svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
    <defs>
        <symbol id="ThisIDHasAColon:AndChromeDoesNotLikeIt">
        ...
        </symbol>
    </defs>
    <use
        ....
        xlink:href="#ThisIDHasAColon:AndChromeDoesNotLikeIt"
    />
</svg>

Good:

<svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
    <defs>
        <symbol id="NoMoreColon">
        ...
        </symbol>
    </defs>
    <use
        ....
        xlink:href="#NoMoreColon"
    />
</svg>

jQuery: count number of rows in a table

var trLength = jQuery('#tablebodyID >tr').length;

How can I select all options of multi-select select box on click?

I'm able to make it in a native way @ jsfiddle. Hope it will help.

Post improved answer when it work, and help others.

$(function () { 

    $(".example").multiselect({
                checkAllText : 'Select All',
            uncheckAllText : 'Deselect All',
            selectedText: function(numChecked, numTotal, checkedItems){
              return numChecked + ' of ' + numTotal + ' checked';
            },
            minWidth: 325
    });
    $(".example").multiselect("checkAll");    

});

http://jsfiddle.net/shivasakthi18/25uvnyra/

Pandas: Return Hour from Datetime Column Directly

Here is a simple solution:

import pandas as pd
# convert the timestamp column to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])

# extract hour from the timestamp column to create an time_hour column
df['time_hour'] = df['timestamp'].dt.hour

Jquery: Checking to see if div contains text, then action

if( $("#field > div.field-item").text().indexOf('someText') >= 0)

Some browsers will include whitespace, others won't. >= is appropriate here. Otherwise equality is double equals ==

How to calculate the bounding box for a given lat/lng location?

I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:

http://www.richardpeacock.com/blog/2011/11/draw-box-around-coordinate-google-maps-based-miles-or-kilometers

Upload Image using POST form data in Python-requests

For Rest API to upload images from host to host:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

You can use option verify set to False to omit SSL verification for HTTPS requests.

Laravel 5 – Clear Cache in Shared Hosting Server

You can do it via router as well, similar to Francesco answer but with less clutter in router config

Route::get('/artisan/{cmd}', function($cmd) {
    $cmd = trim(str_replace("-",":", $cmd));
    $validCommands = ['cache:clear', 'optimize', 'route:cache', 'route:clear', 'view:clear', 'config:cache'];
    if (in_array($cmd, $validCommands)) {
        Artisan::call($cmd);
        return "<h1>Ran Artisan command: {$cmd}</h1>";
    } else {
        return "<h1>Not valid Artisan command</h1>";
    }
});

Then run them via visiting http://myapp.test/artisan/cache-clear etc If you need to add/edit valid Artisan commands just update the $validCommands array.

Programmatically go back to previous ViewController in Swift

Try this: for the previous view use this:

navigationController?.popViewController(animated: true)  

pop to root use this code:

navigationController?.popToRootViewController(animated: true) 

Combining the results of two SQL queries as separate columns

You can use a CROSS JOIN:

SELECT *
FROM (  SELECT SUM(Fdays) AS fDaysSum 
        FROM tblFieldDays 
        WHERE tblFieldDays.NameCode=35 
        AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum 
            FROM tblChargeHours 
            WHERE tblChargeHours.NameCode=35 
            AND tblChargeHours.WeekEnding=1) B -- use you real query here

Creating a segue programmatically

well , you can create and also can subclass the UIStoryBoardSegue . subclassing is mostly used for giving custom transition animation.

you can see video of wwdc 2011 introducing StoryBoard. its available in youtube also.

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIStoryboardSegue_Class/Reference/Reference.html#//apple_ref/occ/cl/UIStoryboardSegue

Initialising a multidimensional array in Java

I'll add that if you want to read the dimensions, you can do this:

int[][][] a = new int[4][3][2];

System.out.println(a.length);  // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2

You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

How do I install command line MySQL client on mac?

For installing mysql-shell with homebrew, run

brew cask install mysql-shell

you can then launch the mysql shell with

mysqlsh

if you want to enter SQL mode directly, run

mysqlsh --sql

Convert datetime object to a String of date only in Python

It is possible to convert a datetime object into a string by working directly with the components of the datetime object.

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

Output --> 5/23/2017

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

Encode string as unicode.

>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'

LaTeX: Prevent line break in a span of text

\mbox is the simplest answer. Regarding the update:

TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.

Use \sloppy or \begin{sloppypar}...\end{sloppypar} to adjust this behavior, at least a little. Another possibility is \raggedright (or \begin{raggedright}...\end{raggedright}).

Working with select using AngularJS's ng-options

For some reason AngularJS allows to get me confused. Their documentation is pretty horrible on this. More good examples of variations would be welcome.

Anyway, I have a slight variation on Ben Lesh's answer.

My data collections looks like this:

items =
[
   { key:"AD",value:"Andorra" }
,  { key:"AI",value:"Anguilla" }
,  { key:"AO",value:"Angola" }
 ...etc..
]

Now

<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>

still resulted in the options value to be the index (0, 1, 2, etc.).

Adding Track By fixed it for me:

<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>

I reckon it happens more often that you want to add an array of objects into an select list, so I am going to remember this one!

Be aware that from AngularJS 1.4 you can't use ng-options any more, but you need to use ng-repeat on your option tag:

<select name="test">
   <option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>

Add padding to HTML text input field

you can solve this, taking the input tag inside a div, then put the padding property on div tag. This work's for me...

Like this:

<div class="paded">
    <input type="text" />
</div>

and css:

.paded{
    padding-right: 20px;
}

How to format a numeric column as phone number in SQL

This should do it:

UPDATE TheTable
SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 4, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 7, 4)

Incorporated Kane's suggestion, you can compute the phone number's formatting at runtime. One possible approach would be to use scalar functions for this purpose (works in SQL Server):

CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10))
RETURNS VARCHAR(12)
BEGIN
    RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' + 
           SUBSTRING(@phoneNumber, 4, 3) + '-' + 
           SUBSTRING(@phoneNumber, 7, 4)
END

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

How can I get the data type of a variable in C#?

Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:

If you know the type you want to compare it with, use the is or as operators:

if( unknownObject is TypeIKnow ) { // run code here

The as operator performs a cast that returns null if it fails rather than an exception:

TypeIKnow typed = unknownObject as TypeIKnow;

If you don't know the type and just want runtime type information, use the .GetType() method:

Type typeInformation = unknownObject.GetType();

In newer versions of C#, you can use the is operator to declare a variable without needing to use as:

if( unknownObject is TypeIKnow knownObject ) {
    knownObject.SomeMember();
}

Previously you would have to do this:

TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
    knownObject.SomeMember();
}

Bootstrap 4 align navbar items to the right

I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.

_x000D_
_x000D_
.hidden {_x000D_
  display:none;_x000D_
  } _x000D_
  _x000D_
 #loginButton{_x000D_
 _x000D_
 margin-right:2px;_x000D_
 _x000D_
 }
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">NavBar</a>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active hidden">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item hidden">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item hidden">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton"><a href="#">Log In</a></button>_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit"><a href="#">Register</a></button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to save and load cookies using Python + Selenium WebDriver

Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:

$ cat work-auth.py
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Use sudo with password as parameter

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

Generate class from database table

I could not get Alex's answer to work on Sql Server 2008 R2. So, I rewrote it using the same basic principles. It now allows for schemas and several fixes have been made for column-property mappings (including mapping nullable date types to nullable C# value types). Here is the Sql:

   DECLARE @TableName VARCHAR(MAX) = 'NewsItem' -- Replace 'NewsItem' with your table name
    DECLARE @TableSchema VARCHAR(MAX) = 'Markets' -- Replace 'Markets' with your schema name
    DECLARE @result varchar(max) = ''

    SET @result = @result + 'using System;' + CHAR(13) + CHAR(13) 

    IF (@TableSchema IS NOT NULL) 
    BEGIN
        SET @result = @result + 'namespace ' + @TableSchema  + CHAR(13) + '{' + CHAR(13) 
    END

    SET @result = @result + 'public class ' + @TableName + CHAR(13) + '{' + CHAR(13) 

    SET @result = @result + '#region Instance Properties' + CHAR(13)  

   SELECT
      @result = @result + CHAR(13)
      + ' public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)
    FROM (SELECT
      c.COLUMN_NAME AS ColumnName,
      CASE c.DATA_TYPE
        WHEN 'bigint' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Int64?'
            ELSE 'Int64'
          END
        WHEN 'binary' THEN 'Byte[]'
        WHEN 'bit' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'bool?'
            ELSE 'bool'
          END
        WHEN 'char' THEN 'string'
        WHEN 'date' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'DateTime?'
            ELSE 'DateTime'
          END
        WHEN 'datetime' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'DateTime?'
            ELSE 'DateTime'
          END
        WHEN 'datetime2' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'DateTime?'
            ELSE 'DateTime'
          END
        WHEN 'datetimeoffset' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'DateTimeOffset?'
            ELSE 'DateTimeOffset'
          END
        WHEN 'decimal' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'decimal?'
            ELSE 'decimal'
          END
        WHEN 'float' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Single?'
            ELSE 'Single'
          END
        WHEN 'image' THEN 'Byte[]'
        WHEN 'int' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'int?'
            ELSE 'int'
          END
        WHEN 'money' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'decimal?'
            ELSE 'decimal'
          END
        WHEN 'nchar' THEN 'string'
        WHEN 'ntext' THEN 'string'
        WHEN 'numeric' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'decimal?'
            ELSE 'decimal'
          END
        WHEN 'nvarchar' THEN 'string'
        WHEN 'real' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Double?'
            ELSE 'Double'
          END
        WHEN 'smalldatetime' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'DateTime?'
            ELSE 'DateTime'
          END
        WHEN 'smallint' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Int16?'
            ELSE 'Int16'
          END
        WHEN 'smallmoney' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'decimal?'
            ELSE 'decimal'
          END
        WHEN 'text' THEN 'string'
        WHEN 'time' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'TimeSpan?'
            ELSE 'TimeSpan'
          END
        WHEN 'timestamp' THEN 'Byte[]'
        WHEN 'tinyint' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Byte?'
            ELSE 'Byte'
          END
        WHEN 'uniqueidentifier' THEN CASE C.IS_NULLABLE
            WHEN 'YES' THEN 'Guid?'
            ELSE 'Guid'
          END
        WHEN 'varbinary' THEN 'Byte[]'
        WHEN 'varchar' THEN 'string'
        ELSE 'Object'
      END AS ColumnType,
      c.ORDINAL_POSITION
    FROM INFORMATION_SCHEMA.COLUMNS c
    WHERE c.TABLE_NAME = @TableName
    AND ISNULL(@TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA) t
    ORDER BY t.ORDINAL_POSITION

    SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)  

    SET @result = @result  + '}' + CHAR(13)

    IF (@TableSchema IS NOT NULL) 
    BEGIN
        SET @result = @result + CHAR(13) + '}' 
    END

    PRINT @result

It produces C# like the following:

using System;

namespace Markets
{
    public class NewsItem        {
        #region Instance Properties

        public Int32 NewsItemID { get; set; }

        public Int32? TextID { get; set; }

        public String Description { get; set; }

        #endregion Instance Properties
    }

}

It may be an idea to use EF, Linq to Sql, or even Scaffolding; however, there are times when a piece of coding like this comes in handy. Frankly, I do not like using EF navigation properties where the code it generates made 19,200 separate database calls to populate a 1000 row grid. This could have been achieved in a single database call. Nonetheless, it could just be that your technical architect does not want you to use EF and the like. So, you have to revert to code like this... Incidentally, it may also be an idea to decorate each of the properties with attributes for DataAnnotations, etc., but I'm keeping this strictly POCO.

EDIT Fixed for TimeStamp and Guid?

What is the closest thing Windows has to fork()?

As other answers have mentioned, NT (the kernel underlying modern versions of Windows) has an equivalent of Unix fork(). That's not the problem.

The problem is that cloning a process's entire state is not generally a sane thing to do. This is as true in the Unix world as it is in Windows, but in the Unix world, fork() is used all the time, and libraries are designed to deal with it. Windows libraries aren't.

For example, the system DLLs kernel32.dll and user32.dll maintain a private connection to the Win32 server process csrss.exe. After a fork, there are two processes on the client end of that connection, which is going to cause problems. The child process should inform csrss.exe of its existence and make a new connection – but there's no interface to do that, because these libraries weren't designed with fork() in mind.

So you have two choices. One is to forbid the use of kernel32 and user32 and other libraries that aren't designed to be forked – including any libraries that link directly or indirectly to kernel32 or user32, which is virtually all of them. This means that you can't interact with the Windows desktop at all, and are stuck in your own separate Unixy world. This is the approach taken by the various Unix subsystems for NT.

The other option is to resort to some sort of horrible hack to try to get unaware libraries to work with fork(). That's what Cygwin does. It creates a new process, lets it initialize (including registering itself with csrss.exe), then copies most of the dynamic state over from the old process and hopes for the best. It amazes me that this ever works. It certainly doesn't work reliably – even if it doesn't randomly fail due to an address space conflict, any library you're using may be silently left in a broken state. The claim of the current accepted answer that Cygwin has a "fully-featured fork()" is... dubious.

Summary: In an Interix-like environment, you can fork by calling fork(). Otherwise, please try to wean yourself from the desire to do it. Even if you're targeting Cygwin, don't use fork() unless you absolutely have to.

How to declare empty list and then add string in scala?

Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.

How to send a html email with the bash command "sendmail"?

To follow up on the previous answer using mail :

Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF

This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]

You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

static files with express.js

In the newest version of express the "createServer" is deprecated. This example works for me:

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

app.listen(80);
console.log('Listening on port 80');

SQL query to get most recent row for each instance of a given key

Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):

SELECT username, ip, time_stamp FROM (
 SELECT username, ip, time_stamp, 
  ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
 FROM Users
) tmp WHERE rn = 1;

Easily measure elapsed time

They are they same because your doSomething function happens faster than the granularity of the timer. Try:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));

Simplest code for array intersection in javascript

.reduce to build a map, and .filter to find the intersection. delete within the .filter allows us to treat the second array as though it's a unique set.

function intersection (a, b) {
  var seen = a.reduce(function (h, k) {
    h[k] = true;
    return h;
  }, {});

  return b.filter(function (k) {
    var exists = seen[k];
    delete seen[k];
    return exists;
  });
}

I find this approach pretty easy to reason about. It performs in constant time.

How to get only the last part of a path in Python?

You could do

>>> import os
>>> os.path.basename('/folderA/folderB/folderC/folderD')

UPDATE1: This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this -

>>> import os
>>> path = "/folderA/folderB/folderC/folderD"
>>> if os.path.isdir(path):
        dirname = os.path.basename(path)

UPDATE2: As lars pointed out, making changes so as to accomodate trailing '/'.

>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'

How do I set bold and italic on UILabel of iPhone/iPad?

This is very simple. Here is the code.

[yourLabel setFont:[UIFont boldSystemFontOfSize:15.0];

This will help you.

React hooks useState Array

You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect for this.

The following version works:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const StateSelector = () => {
  const initialValue = [
    { id: 0, value: " --- Select a State ---" }];

  const allowedState = [
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
  ];

  const [stateOptions, setStateValues] = useState(initialValue);
  // initialValue.push(...allowedState);

  console.log(initialValue.length);
  // ****** BEGINNING OF CHANGE ******
  useEffect(() => {
    // Should not ever set state during rendering, so do this in useEffect instead.
    setStateValues(allowedState);
  }, []);
  // ****** END OF CHANGE ******

  return (<div>
    <label>Select a State:</label>
    <select>
      {stateOptions.map((localState, index) => (
        <option key={localState.id}>{localState.value}</option>
      ))}
    </select>
  </div>);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);

and here it is in a code sandbox.

I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState directly without using useState at all). If so, that api call to load the list could also go inside the useEffect block.

How to programmatically click a button in WPF?

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

Get the current time in C

Initialize your now variable.

time_t now = time(0); // Get the system time

The localtime function is used to convert the time value in the passed time_t to a struct tm, it doesn't actually retrieve the system time.

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

On a fresh Debian image, cloning https://github.com/python/cpython and running:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev

Now execute the configure file cloned above:

./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall

Got 3.7 installed and working for me.

SLIGHT UPDATE

Looks like I said I would update this answer with some more explanation and two years later I don't have much to add.

  • this SO post explains why certain libraries like python-dev might be necessary.
  • this SO post explains why one might use the altinstall as opposed to install argument in the make command.

Aside from that I guess the choice would be to either read through the cpython codebase looking for #include directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.

Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

In Python try until no error

Here is a short piece of code I use to capture the error as a string. Will retry till it succeeds. This catches all exceptions but you can change this as you wish.

start = 0
str_error = "Not executed yet."
while str_error:
    try:
        # replace line below with your logic , i.e. time out, max attempts
        start = raw_input("enter a number, 0 for fail, last was {0}: ".format(start))
        new_val = 5/int(start)
        str_error=None
    except Exception as str_error:
         pass

WARNING: This code will be stuck in a forever loop until no exception occurs. This is just a simple example and MIGHT require you to break out of the loop sooner or sleep between retries.

WCF error - There was no endpoint listening at

in my case

my service has function to Upload Files

and this error just shown up on trying to upload Big Files

so I found this answer to Increase maxRequestLength to needed value in web.config

and problem solved

if you don't make any upload or download operations maybe this answer will not help you

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

Resolve build errors due to circular dependency amongst classes

You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).

The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.

//A.h
#ifndef A_H
#define A_H
class B;
class A
{
    int _val;
    B* _b;
public:

    A(int val);
    void SetB(B *b);
    void Print();
};
#endif

//B.h
#ifndef B_H
#define B_H
class A;
class B
{
    double _val;
    A* _a;
public:

    B(double val);
    void SetA(A *a);
    void Print();
};
#endif

//A.cpp
#include "A.h"
#include "B.h"

#include <iostream>

using namespace std;

A::A(int val)
:_val(val)
{
}

void A::SetB(B *b)
{
    _b = b;
    cout<<"Inside SetB()"<<endl;
    _b->Print();
}

void A::Print()
{
    cout<<"Type:A val="<<_val<<endl;
}

//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>

using namespace std;

B::B(double val)
:_val(val)
{
}

void B::SetA(A *a)
{
    _a = a;
    cout<<"Inside SetA()"<<endl;
    _a->Print();
}

void B::Print()
{
    cout<<"Type:B val="<<_val<<endl;
}

//main.cpp
#include "A.h"
#include "B.h"

int main(int argc, char* argv[])
{
    A a(10);
    B b(3.14);
    a.Print();
    a.SetB(&b);
    b.Print();
    b.SetA(&a);
    return 0;
}

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

List of encodings that Node.js supports

If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:

npm install iconv

npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz

> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild

gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

Send cookies with curl

if you have Firebug installed on Firefox, just open the url. In the network panel, right-click and select Copy as cURL. You can see all curl parameters for this web call.

Why did my Git repo enter a detached HEAD state?

It can easily happen if you try to undo changes you've made by re-checking-out files and not quite getting the syntax right.

You can look at the output of git log - you could paste the tail of the log here since the last successful commit, and we could all see what you did. Or you could paste-bin it and ask nicely in #git on freenode IRC.

Can you have if-then-else logic in SQL?

You can make the following sql query

IF ((SELECT COUNT(*) FROM table1 WHERE project = 1) > 0) 
    SELECT product, price FROM table1 WHERE project = 1
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 2) > 0) 
    SELECT product, price FROM table1 WHERE project = 2
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 3) > 0)
    SELECT product, price FROM table1 WHERE project = 3

How to write PNG image to string with the PIL?

sth's solution didn't work for me
because in ...

Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension

It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case

You can bypass the format detection by setting the format yourself in a parameter

import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()

Assert equals between 2 Lists in Junit

List<Integer> figureTypes = new ArrayList<Integer>(
                           Arrays.asList(
                                 1,
                                 2
                            ));

List<Integer> figureTypes2 = new ArrayList<Integer>(
                           Arrays.asList(
                                 1,
                                 2));

assertTrue(figureTypes .equals(figureTypes2 ));

Printing HashMap In Java

Java 8 new feature forEach style

import java.util.HashMap;

public class PrintMap {
    public static void main(String[] args) {
        HashMap<String, Integer> example = new HashMap<>();
        example.put("a", 1);
        example.put("b", 2);
        example.put("c", 3);
        example.put("d", 5);

        example.forEach((key, value) -> System.out.println(key + " : " + value));

//      Output:
//      a : 1
//      b : 2
//      c : 3
//      d : 5

    }
}

Find records with a date field in the last 24 hours

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

If '<selector>' is an Angular component, then verify that it is part of this module

Your MyComponentComponent should be in MyComponentModule.

And in MyComponentModule, you should place the MyComponentComponent inside the "exports".

Something like this, see code below.

@NgModule({
   imports: [],
   exports: [MyComponentComponent],
   declarations: [MyComponentComponent],
   providers: [],
})

export class MyComponentModule {
}

and place the MyComponentModule in the imports in app.module.ts like this (see code below).

import { MyComponentModule } from 'your/file/path';

@NgModule({
   imports: [MyComponentModule]
   declarations: [AppComponent],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule {}

After doing so, the selector of your component can now be recognized by the app.

You can learn more about it here: https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html

Cheers!

Insert picture into Excel cell

You can do it in a less than a minute with Google Drive (and free, no hassles)

• Bulk Upload all your images on imgur.com

• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.

• Use http://TextMechanic.co to prepend and append each line with this: Prefix : =image(" AND Suffix : ", 1)

So that it looks like this =image("URL", 1)

• Copy All

• Paste it in Google Spreadsheet

• Voila!

References :

http://www.labnol.org/internet/images-in-google-spreadsheet/18167/

https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

Following are the steps that will definitely work:

  1. Open CMD : Press Windows+R from keyboard or just type "cmd" in windows search
  2. Type Following in cmd : netstat -aon | find ":8080" | find "LISTENING"
  3. See the last column : There will be some number like 2816 or similar.(It will differ from this)
  4. Now open Task Manager (Keyboard shortcut : Ctrl+Shift+Esc)
  5. In that, go to Details Tab and under PID Column, search for the number you found in step 3
  6. Right Click on it and select end process
  7. Now happily go to Netbeans and Run your program

NOTE : If you are running your program for the first time in Netbeans, it takes some time. So don't worry if it takes time.

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

How do I compile C++ with Clang?

Also, for posterity -- Clang (like GCC) accepts the -x switch to set the language of the input files, for example,

$ clang -x c++ some_random_file.txt

This mailing list thread explains the difference between clang and clang++ well: Difference between clang and clang++

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

You can delete all the documents from a collection in MongoDB, you can use the following:

db.users.remove({})

Alternatively, you could use the following method as well:

db.users.deleteMany({})

Follow the following MongoDB documentation, for further details.

To remove all documents from a collection, pass an empty filter document {} to either the db.collection.deleteMany() or the db.collection.remove() method.

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.

Using LIKE in an Oracle IN clause

Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)

SELECT * FROM employees em
    WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));

Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

Why is MySQL InnoDB insert so slow?

The default value for InnoDB is actually pretty bad. InnoDB is very RAM dependent, you might find better result if you tweak the settings. Here's a guide that I used InnoDB optimization basic

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

How to get cumulative sum

Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

VB.NET Empty String Array

try this Dim Arraystr() as String ={}

Populate a Drop down box from a mySQL table in PHP

After a while of research and disappointments....I was able to make this up

     <?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>

//insert the below code in the body


    <table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
    <th style="width:20%;">Email</th>
       <th style="width:10%;">City/ Region</th>
        <th style="width:30%;">Details</th>
  </tr>
  <?php
   while ($row = mysqli_fetch_array($result)) {

               echo "<tr>";
               echo "<td>".$row['username']."</td>";
               echo "<td>".$row['city']."</td>";
                echo "<td>".$row['details']."</td>";
               echo "</tr>";
           }

     ?>
</table>

Trust me it works :)

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

How to call a C# function from JavaScript?

Server-side functions are on the server-side, client-side functions reside on the client. What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.

More info can be found here and here

How to disable horizontal scrolling of UIScrollView?

Try This:

CGSize scrollSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, scrollHeight);
[scrollView setContentSize: scrollSize];

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

How do I convert an array object to a string in PowerShell?

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

android layout with visibility GONE

Kotlin Style way to do this more simple (example):

    isVisible = false

Complete example:

    if (some_data_array.details == null){
                holder.view.some_data_array.isVisible = false}

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

TextView bold via xml file?

just use

android:textStyle="bold"

@AspectJ pointcut for all methods of a class with specific annotation

Using annotations, as described in the question.

Annotation: @Monitor

Annotation on class, app/PagesController.java:

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:

<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

Prevent Default on Form Submit jQuery

DEPRECATED - this part is outdated so please don't use it.

You can also try this code, if you have for example later added dynamic forms. For example you loaded a window async with ajax and want to submit this form.

$('#cpa-form').live('submit' ,function(e){
    e.preventDefault();      
    // do something
});

UPDATE - you should use the jQuery on() method an try to listen to the document DOM if you want to handle dynamically added content.

Case 1, static version: If you have only a few listeners and your form to handle is hardcoded, then you can listen directly on "document level". I wouldn't use the listeners on document level but I would try to go deeper in the doom tree because it could lead to performance issues (depends on the size of your website and your content)

$('form#formToHandle').on('submit'... 

OR

$('form#formToHandle').submit(function(e) {
    e.preventDefault();      
    // do something
});

Case 2, dynamic version: If you already listen to the document in your code, then this way would be good for you. This will also work for code that was added later via DOM or dynamic with AJAX.

$(document).on('submit','form#formToHandle',function(){
   // do something like e.preventDefault(); 
});

OR

$(document).ready(function() {
    console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

OR

$(function() { // <- this is shorthand version
   console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

How to force HTTPS using a web.config file

A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>

<embed> vs. <object>

Some other options:

<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>

<object type="application/pdf" data="#request.localhost#_includes/filename.pdf" 
        width="100%" height="100%">
  <param name="src" value="#request.localhost#_includes/filename.pdf">
</object>

R - Concatenate two dataframes?

You want "rbind".

b$b <- NA
new <- rbind(a, b)

rbind requires the data frames to have the same columns.

The first line adds column b to data frame b.

Results

> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
  a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
   a  c
1  9 12
2 10 13
3 11 14
> b$b <- NA
> b
   a  c  b
1  9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
   a  b  c
1  0  3  6
2  1  4  7
3  2  5  8
4  9 NA 12
5 10 NA 13
6 11 NA 14

How to do what head, tail, more, less, sed do in Powershell?

Get-Content (alias: gc) is your usual option for reading a text file. You can then filter further:

gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt     # also head
gc log.txt | select -last 10  # tail
gc -Tail 10 log.txt           # also tail (since PSv3), also much faster than above option
gc log.txt | more             # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed

This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.

The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).

How can I check if a Perl array contains a particular value?

There are two ways you can do this. You can use the throw the values into a hash for a lookup table, as suggested by the other posts. ( I'll add just another idiom. )

my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;

But if it's data of mostly word characters and not too many meta, you can dump it into a regex alternation:

use English qw<$LIST_SEPARATOR>;

my $regex_str = do { 
    local $LIST_SEPARATOR = '|';
    "(?:@bad_params)";
 };

 # $front_delim and $back_delim being any characters that come before and after. 
 my $regex = qr/$front_delim$regex_str$back_delim/;

This solution would have to be tuned for the types of "bad values" you're looking for. And again, it might be totally inappropriate for certain types of strings, so caveat emptor.

Laravel - Eloquent or Fluent random row

For Laravel 5.2 >=

use the Eloquent method:

inRandomOrder()

The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

$randomUser = DB::table('users')
            ->inRandomOrder()
            ->first();

from docs: https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

Real-world examples of recursion

Since you don't seem to like computer science or mathy examples, here is a different one: wire puzzles.

Many wire puzzles involve removing a long closed loop of wire by working it in and out of wire rings. These puzzles are recursive. One of them is called "arrow dynamics". I am sue you could find it if you google for "arrow dynamics wire puzzle"

These puzzles are a lot like the towers of Hanoi.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

These days the location of the emulated SD card is at /storage/emulated/0

How to check if a string contains text from an array of substrings in JavaScript?

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}

create unique id with javascript

let transactionId =${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}

_x000D_
_x000D_
let transactionId =`${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}` 

console.log(transactionId)
_x000D_
_x000D_
_x000D_

Remove and Replace Printed items

Just use CR to go to beginning of the line.

import time
for x in range (0,5):  
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

How to count frequency of characters in a string?

You can use a CharAdapter and a CharBag from Eclipse Collections and avoid boxing to Character and Integer.

CharBag bag = Strings.asChars("aasjjikkk").toBag();

Assert.assertEquals(2, bag.occurrencesOf('a'));
Assert.assertEquals(1, bag.occurrencesOf('s'));
Assert.assertEquals(2, bag.occurrencesOf('j'));
Assert.assertEquals(1, bag.occurrencesOf('i'));
Assert.assertEquals(3, bag.occurrencesOf('k'));

Note: I am a committer for Eclipse Collections.

Remove 'standalone="yes"' from generated XML

In case you are getting property exception, add the following configuration:

jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders",
              "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);  

JPA EntityManager: Why use persist() over merge()?

Going through the answers there are some details missing regarding `Cascade' and id generation. See question

Also, it is worth mentioning that you can have separate Cascade annotations for merging and persisting: Cascade.MERGE and Cascade.PERSIST which will be treated according to the used method.

The spec is your friend ;)

How to implement Rate It feature in Android App

Kotlin version of Raghav Sood's answer

Rater.kt

    class Rater {
      companion object {
        private const val APP_TITLE = "App Name"
        private const val APP_NAME = "com.example.name"

        private const val RATER_KEY = "rater_key"
        private const val LAUNCH_COUNTER_KEY = "launch_counter_key"
        private const val DO_NOT_SHOW_AGAIN_KEY = "do_not_show_again_key"
        private const val FIRST_LAUNCH_KEY = "first_launch_key"

        private const val DAYS_UNTIL_PROMPT: Int = 3
        private const val LAUNCHES_UNTIL_PROMPT: Int = 3

        fun start(mContext: Context) {
            val prefs: SharedPreferences = mContext.getSharedPreferences(RATER_KEY, 0)
            if (prefs.getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
                return
            }

            val editor: Editor = prefs.edit()

            val launchesCounter: Long = prefs.getLong(LAUNCH_COUNTER_KEY, 0) + 1;
            editor.putLong(LAUNCH_COUNTER_KEY, launchesCounter)

            var firstLaunch: Long = prefs.getLong(FIRST_LAUNCH_KEY, 0)
            if (firstLaunch == 0L) {
                firstLaunch = System.currentTimeMillis()
                editor.putLong(FIRST_LAUNCH_KEY, firstLaunch)
            }

            if (launchesCounter >= LAUNCHES_UNTIL_PROMPT) {
                if (System.currentTimeMillis() >= firstLaunch +
                    (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)
                ) {
                    showRateDialog(mContext, editor)
                }
            }

            editor.apply()
        }

        fun showRateDialog(mContext: Context, editor: Editor) {
            Dialog(mContext).apply {
                setTitle("Rate $APP_TITLE")

                val ll = LinearLayout(mContext)
                ll.orientation = LinearLayout.VERTICAL

                TextView(mContext).apply {
                    text =
                        "If you enjoy using $APP_TITLE, please take a moment to rate it. Thanks for your support!"

                    width = 240
                    setPadding(4, 0, 4, 10)
                    ll.addView(this)
                }

                Button(mContext).apply {
                    text = "Rate $APP_TITLE"
                    setOnClickListener {
                        mContext.startActivity(
                            Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse("market://details?id=$APP_NAME")
                            )
                        );
                        dismiss()
                    }
                    ll.addView(this)
                }

                Button(mContext).apply {
                    text = "Remind me later"
                    setOnClickListener {
                        dismiss()
                    };
                    ll.addView(this)
                }

                Button(mContext).apply {
                    text = "No, thanks"
                    setOnClickListener {
                        editor.putBoolean(DO_NOT_SHOW_AGAIN_KEY, true);
                        editor.commit()
                        dismiss()
                    };
                    ll.addView(this)
                }

                setContentView(ll)
                show()
            }
        }
    }
}

Optimized answer

Rater.kt

class Rater {
    companion object {
        fun start(context: Context) {
            val prefs: SharedPreferences = context.getSharedPreferences(RATER_KEY, 0)
            if (prefs.getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
                return
            }

            val editor: Editor = prefs.edit()

            val launchesCounter: Long = prefs.getLong(LAUNCH_COUNTER_KEY, 0) + 1;
            editor.putLong(LAUNCH_COUNTER_KEY, launchesCounter)

            var firstLaunch: Long = prefs.getLong(FIRST_LAUNCH_KEY, 0)
            if (firstLaunch == 0L) {
                firstLaunch = System.currentTimeMillis()
                editor.putLong(FIRST_LAUNCH_KEY, firstLaunch)
            }

            if (launchesCounter >= LAUNCHES_UNTIL_PROMPT) {
                if (System.currentTimeMillis() >= firstLaunch +
                    (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)
                ) {
                    showRateDialog(context, editor)
                }
            }

            editor.apply()
        }

        fun showRateDialog(context: Context, editor: Editor) {
            Dialog(context).apply {
                setTitle("Rate $APP_TITLE")
                LinearLayout(context).let { layout ->
                    layout.orientation = LinearLayout.VERTICAL
                    setDescription(context, layout)
                    setPositiveAnswer(context, layout)
                    setNeutralAnswer(context, layout)
                    setNegativeAnswer(context, editor, layout)
                    setContentView(layout)
                    show()       
                }
            }
        }

        private fun setDescription(context: Context, layout: LinearLayout) {
            TextView(context).apply {
                text = context.getString(R.string.rate_description, APP_TITLE)
                width = 240
                setPadding(4, 0, 4, 10)
                layout.addView(this)
            }
        }

        private fun Dialog.setPositiveAnswer(
            context: Context,
            layout: LinearLayout
        ) {
            Button(context).apply {
                text = context.getString(R.string.rate_now)
                setOnClickListener {
                    context.startActivity(
                        Intent(
                            Intent.ACTION_VIEW,
                            Uri.parse(context.getString(R.string.market_uri, APP_NAME))
                        )
                    );
                    dismiss()
                }
                layout.addView(this)
            }
        }

        private fun Dialog.setNeutralAnswer(
            context: Context,
            layout: LinearLayout
        ) {
            Button(context).apply {
                text = context.getString(R.string.remind_later)
                setOnClickListener {
                    dismiss()
                };
                layout.addView(this)
            }
        }

        private fun Dialog.setNegativeAnswer(
            context: Context,
            editor: Editor,
            layout: LinearLayout
        ) {
            Button(context).apply {
                text = context.getString(R.string.no_thanks)
                setOnClickListener {
                    editor.putBoolean(DO_NOT_SHOW_AGAIN_KEY, true);
                    editor.commit()
                    dismiss()
                };
                layout.addView(this)
            }
        }
    }
}

Constants.kt

object Constants {

    const val APP_TITLE = "App Name"
    const val APP_NAME = "com.example.name"

    const val RATER_KEY = "rater_key"
    const val LAUNCH_COUNTER_KEY = "launch_counter_key"
    const val DO_NOT_SHOW_AGAIN_KEY = "do_not_show_again_key"
    const val FIRST_LAUNCH_KEY = "first_launch_key"

    const val DAYS_UNTIL_PROMPT: Int = 3
    const val LAUNCHES_UNTIL_PROMPT: Int = 3

}

strings.xml

<resources>
    <string name="rate_description">If you enjoy using %1$s, please take a moment to rate it. Thanks for your support!</string>
    <string name="rate_now">Rate now</string>
    <string name="no_thanks">No, thanks</string>
    <string name="remind_later">Remind me later</string>
    <string name="market_uri">market://details?id=%1$s</string>
</resources>

Is it good practice to make the constructor throw an exception?

I have never considered it to be a bad practice to throw an exception in the constructor. When the class is designed, you have a certain idea in mind of what the structure for that class should be. If someone else has a different idea and tries to execute that idea, then you should error accordingly, giving the user feedback on what the error is. In your case, you might consider something like

if (age < 0) throw new NegativeAgeException("The person you attempted " +
                       "to construct must be given a positive age.");

where NegativeAgeException is an exception class that you constructed yourself, possibly extending another exception like IndexOutOfBoundsException or something similar.

Assertions don't exactly seem to be the way to go, either, since you're not trying to discover bugs in your code. I would say terminating with an exception is absolutely the right thing to do here.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

addEventListener vs onclick

While onclick works in all browsers, addEventListener does not work in older versions of Internet Explorer, which uses attachEvent instead.

The downside of onclick is that there can only be one event handler, while the other two will fire all registered callbacks.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

What I did to solve was simply:

  1. Run docker ps -a
  2. Check for the command of the container (mine started with /bin/sh)
  3. Run docker-compose exec < name_of_service > /bin/sh (if that is what started your command

This is for solving when using docker compose

Get most recent row for given ID

Select [insert your fields here]
from tablename 
where signin = (select max(signin) from tablename where ID = 1)

Repeat String - Javascript

I came here randomly and never had a reason to repeat a char in javascript before.

I was impressed by artistoex's way of doing it and disfated's results. I noticed that the last string concat was unnecessary, as Dennis also pointed out.

I noticed a few more things when playing with the sampling disfated put together.

The results varied a fair amount often favoring the last run and similar algorithms would often jockey for position. One of the things I changed was instead of using the JSLitmus generated count as the seed for the calls; as count was generated different for the various methods, I put in an index. This made the thing much more reliable. I then looked at ensuring that varying sized strings were passed to the functions. This prevented some of the variations I saw, where some algorithms did better at the single chars or smaller strings. However the top 3 methods all did well regardless of the string size.

Forked test set

http://jsfiddle.net/schmide/fCqp3/134/

// repeated string
var string = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';
// count paremeter is changed on every test iteration, limit it's maximum value here
var maxCount = 200;

var n = 0;
$.each(tests, function (name) {
    var fn = tests[name];
    JSLitmus.test(++n + '. ' + name, function (count) {
        var index = 0;
        while (count--) {
            fn.call(string.slice(0, index % string.length), index % maxCount);
            index++;
        }
    });
    if (fn.call('>', 10).length !== 10) $('body').prepend('<h1>Error in "' + name + '"</h1>');
});

JSLitmus.runAll();

I then included Dennis' fix and decided to see if I could find a way to eek out a bit more.

Since javascript can't really optimize things, the best way to improve performance is to manually avoid things. If I took the first 4 trivial results out of the loop, I could avoid 2-4 string stores and write the final store directly to the result.

// final: growing pattern + prototypejs check (count < 1)
'final avoid': function (count) {
    if (!count) return '';
    if (count == 1) return this.valueOf();
    var pattern = this.valueOf();
    if (count == 2) return pattern + pattern;
    if (count == 3) return pattern + pattern + pattern;
    var result;
    if (count & 1) result = pattern;
    else result = '';
    count >>= 1;
    do {
        pattern += pattern;
        if (count & 1) result += pattern;
        count >>= 1;
    } while (count > 1);
    return result + pattern + pattern;
}

This resulted in a 1-2% improvement on average over Dennis' fix. However, different runs and different browsers would show a fair enough variance that this extra code probably isn't worth the effort over the 2 previous algorithms.

A chart

Edit: I did this mostly under chrome. Firefox and IE will often favor Dennis by a couple %.

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

Git Push ERROR: Repository not found

I had this issue and realized I was using a different account from the one whose repo it was. Logging in as the original user resolved the issue.

Is there a portable way to get the current username in Python?

You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).

I wrote a small module that can do this straight from Python, getuser.py. Usage:

import getuser
print(getuser.lookup_username())

It works on both Windows and *nix (the latter uses the pwd module as described in the other answers).

MySQL: What's the difference between float and double?

Perhaps this example could explain.

CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2)); 

We have a table like this:

+-------+-------------+
| Field | Type        |
+-------+-------------+
| fla   | float       |
| flb   | float       |
| dba   | double(10,2)|
| dbb   | double(10,2)|
+-------+-------------+

For first difference, we try to insert a record with '1.2' to each field:

INSERT INTO `test` values (1.2,1.2,1.2,1.2);

The table showing like this:

SELECT * FROM `test`;

+------+------+------+------+
| fla  | flb  | dba  | dbb  |
+------+------+------+------+
|  1.2 |  1.2 | 1.20 | 1.20 |
+------+------+------+------+

See the difference?

We try to next example:

SELECT fla+flb, dba+dbb FROM `test`;

Hola! We can find the difference like this:

+--------------------+---------+
| fla+flb            | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 |    2.40 |
+--------------------+---------+

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

Checking cin input stream produces an integer

If istream fails to insert, it will set the fail bit.

int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
    std::cout << "I failed, try again ..." << std::endl
    std::cin.clear(); // reset the failed state
}

You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.

For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly

How to get the full URL of a Drupal page?

This is what I found to be useful

global $base_root;
$base_root . request_uri();

Returns query strings and it's what's used in core: page_set_cache()

Easiest way to rotate by 90 degrees an image using OpenCV?

This is an example without the new C++ interface (works for 90, 180 and 270 degrees, using param = 1, 2 and 3). Remember to call cvReleaseImage on the returned image after using it.

IplImage *rotate_image(IplImage *image, int _90_degrees_steps_anti_clockwise)
{
    IplImage *rotated;

    if(_90_degrees_steps_anti_clockwise != 2)
        rotated = cvCreateImage(cvSize(image->height, image->width), image->depth, image->nChannels);
    else
        rotated = cvCloneImage(image);

    if(_90_degrees_steps_anti_clockwise != 2)
        cvTranspose(image, rotated);

    if(_90_degrees_steps_anti_clockwise == 3)
        cvFlip(rotated, NULL, 1);
    else if(_90_degrees_steps_anti_clockwise == 1)
        cvFlip(rotated, NULL, 0);
    else if(_90_degrees_steps_anti_clockwise == 2)
        cvFlip(rotated, NULL, -1);

    return rotated;
}

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

Running multiple commands in one line in shell

Note that cp A B; rm A is exactly mv A B. It'll be faster too, as you don't have to actually copy the bytes (assuming the destination is on the same filesystem), just rename the file. So you want cp A B; mv A C

Showing line numbers in IPython/Jupyter Notebooks

Was looking for this: Shift-L in JupyterLab 1.0.0

WPF: simple TextBox data binding

Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.

Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.

Implementing the necessary interfaces for using an object as a data source can be found here.

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

VB.net Need Text Box to Only Accept Numbers

You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar represents the key that's pressed. And the the built-in function Asc() converts it into its Ascii integer.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

jQuery UI " $("#datepicker").datepicker is not a function"

I just had this issue, and moving the JS references and code towards the bottom of the page before the </body> tag fixed it for me.

Core dumped, but core file is not in the current directory?

Read /usr/src/linux/Documentation/sysctl/kernel.txt.

[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.

  • If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.

Instead of writing the core dump to disk, your system is configured to send it to the abrt program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...

In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt, where abrt stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash, and so on.