Programs & Examples On #Capacity

How to clear form after submit in Angular 2?

Make a Call clearForm(); in your .ts file

Try like below example code snippet to clear your form data.

clearForm() {

this.addContactForm.reset({
      'first_name': '',
      'last_name': '',
      'mobile': '',
      'address': '',
      'city': '',
      'state': '',
      'country': '',
       'zip': ''
     });
}

Hadoop cluster setup - java.net.ConnectException: Connection refused

Check your firewall setting and set

  <property>
  <name>fs.default.name</name>
  <value>hdfs://MachineName:9000</value>
  </property>

replace localhost to machine name

How to stop INFO messages displaying on spark console?

Right after starting spark-shell type ;

sc.setLogLevel("ERROR")

In Spark 2.0 (Scala):

spark = SparkSession.builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

API Docs : https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.SparkSession

For Java:

spark = SparkSession.builder.getOrCreate();
spark.sparkContext().setLogLevel("ERROR");

Convert Swift string to array

For Swift version 5.3 its easy as:

let string = "Hello world"
let characters = Array(string)

print(characters)

// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

"int cannot be dereferenced" in Java

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :

id.equals

Try replacing this:

        if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"

with

        if (id == list[pos].getItemNumber()){ //Getting error on "equals"

C# Remove object from list of objects

You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.

for (int i = ChunkList.Count-1; i >=0; i--)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.RemoveAt(i);
    }
}

How do I get total physical memory size using PowerShell without WMI?

Let's not over complicate things...:

(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb

Creating a List of Lists in C#

public class ListOfLists<T> : List<List<T>>
{
}


var myList = new ListOfLists<string>();

How to get disk capacity and free space of remote computer

I remote into the computer using Enter-PSsession pcName then I type Get-PSDrive

That will list all drives and space used and remaining. If you need to see all the info formated, pipe it to FL like this: Get-PSdrive | FL *

Dealing with "Xerces hell" in Java/Maven?

Apparently xerces:xml-apis:1.4.01 is no longer in maven central, which is however what xerces:xercesImpl:2.11.0 references.

This works for me:

<dependency>
  <groupId>xerces</groupId>
  <artifactId>xercesImpl</artifactId>
  <version>2.11.0</version>
  <exclusions>
    <exclusion>
      <groupId>xerces</groupId>
      <artifactId>xml-apis</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>xml-apis</groupId>
  <artifactId>xml-apis</artifactId>
  <version>1.4.01</version>
</dependency>

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Firstly remove duplicates:

arrayList1.removeAll(arrayList2);

Then merge two arrayList:

arrayList1.addAll(arrayList2);

Lastly, sort your arrayList if you wish:

collections.sort(arrayList1);

In case you don't want to make any changes on the existing list, first create their backup lists:

arrayList1Backup = new ArrayList(arrayList1);

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

Service Temporarily Unavailable Magento?

If removing the flag shows service temporary unavailable. Go to "http://localhost.com/downloader" and unisntall slider banner,BusinessDecision_Interaktingslider,lightbox2 and anotherone that I dont remember.

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

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

Range of values in C Int and Long 32 - 64 bits

A 32-bit unsigned int has a range from 0 to 4,294,967,295. 0 to 65535 would be a 16-bit unsigned.

An unsigned long long (and, on a 64-bit implementation, possibly also ulong and possibly uint as well) have a range (at least) from 0 to 18,446,744,073,709,551,615 (264-1). In theory it could be greater than that, but at least for now that's rare to nonexistent.

Create the perfect JPA entity

I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.

Entity Class: implement Serializable?

Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.

Constructors: create a constructor with all required fields of the entity?

Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.

Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.

OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.

Constructors: also, package private default constructor?

Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.

Fields/Properties

Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.

As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.

Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.

Protected is better for (Hibernate) performance?

Unlikely.

Equals/HashCode?

This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.

A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.

The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!

So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.

You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.

Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized

Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.

Equals/HashCode -- never refer to related entities

"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"

Sounds like good advice.

Hope this helps!

Delete item from array and shrink array

Since an array has a fixed size that is allocated when created, your only option is to create a new array without the element you want to remove.

If the element you want to remove is the last array item, this becomes easy to implement using Arrays.copy:

int a[] = { 1, 2, 3};
a = Arrays.copyOf(a, 2);

After running the above code, a will now point to a new array containing only 1, 2.

Otherwise if the element you want to delete is not the last one, you need to create a new array at size-1 and copy all the items to it except the one you want to delete.

The approach above is not efficient. If you need to manage a mutable list of items in memory, better use a List. Specifically LinkedList will remove an item from the list in O(1) (fastest theoretically possible).

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

try using return 0;

if it keeps failing change your solution platform to 64x instead of 86x and go to configuration manager(that's were you change the 86x to 64x) and in platform set it to 64 bits

that works for me, hope it work to you

ArrayList: how does the size increase?

  1. Arraylist default capacity is 10.

  2. [1,2,3,4,5.....10]

  3. if you want to increase the size of Arraylist in java, you can apply this

  4. formula-

  5. int newcapacity, current capacity;

  6. newcapacity =((current capacity*3/2)+1)

  7. arralist will be [1,2,3,4,5.....10,11] and arraylist capacity is 16.

What's the reason I can't create generic array types in Java?

There surely must be a good way around it (maybe using reflection), because it seems to me that that's exactly what ArrayList.toArray(T[] a) does. I quote:

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

So one way around it would be to use this function i.e. create an ArrayList of the objects you want in the array, then use toArray(T[] a) to create the actual array. It wouldn't be speedy, but you didn't mention your requirements.

So does anyone know how toArray(T[] a) is implemented?

How do I increase the capacity of the Eclipse output console?

Alternative

If your console is not empty, right click on the Console area > Preferences... > change the value for the Console buffer size (characters) (recommended) or uncheck the Limit console output (not recommended):

enter image description here enter image description here

How to start a Process as administrator mode in C#

Try this:

//Vista or higher check
if (System.Environment.OSVersion.Version.Major >= 6)
{
   p.StartInfo.Verb = "runas";
}

Alternatively, go the manifest route for your application.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

If you just want to know how long it takes for the command to execute, you may consider using the time command. You for example use time ffmpeg -i myvideoofoneminute.aformat out.anotherformat

Using an HTML button to call a JavaScript function

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

Java HashMap performance optimization / alternative

The popular hashing methods used are not really very good for large sets and, as pointed out above, the hash used is particularly bad. Better is to use a hash algorithm with high mixing and coverage such as BuzHash (sample implementation at http://www.java2s.com/Code/Java/Development-Class/AveryefficientjavahashalgorithmbasedontheBuzHashalgoritm.htm)

Multidimensional Lists in C#

You should use List<Person> or a HashSet<Person>.

Try/catch does not seem to have an effect

This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.

try {
    Set-Location "$YourPath" -ErrorAction Stop;
} catch {
    Write-Host "Exception has been caught";
}

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

What are the performance characteristics of sqlite with very large database files?

Much of the reason that it took > 48 hours to do your inserts is because of your indexes. It is incredibly faster to:

1 - Drop all indexes 2 - Do all inserts 3 - Create indexes again

What is a practical, real world example of the Linked List?

Some example of single linked list.

  1. Undo button of any application like Microsoft Word, Paint, etc: A linked list of states.
  2. GPS Navigation: A linked list of map data. Travelling from origin to destination is example of traversing through all nodes. Rerouting by a GPS is an example of Add and Remove operations of map data.

Some example of double linked list.

  1. Browser's Next and Previous Button: a linked list of URLs
  2. Microsoft Image Viewer's Next and Previous Button: a linked list of images
  3. Undo and Redo button of Photoshop, a linked list of states.

Plotting with C#

See Samples Environment for Microsoft Chart Controls:

The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.

Seems to be more business oriented, but may be of some value to science students and scientists.

How to create a generic array in Java?

I made this code snippet to reflectively instantiate a class which is passed for a simple automated test utility.

Object attributeValue = null;
try {
    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }
    else if(!clazz.isInterface()){
        attributeValue = BeanUtils.instantiateClass(clazz);
    }
} catch (Exception e) {
    logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}

Note this segment:

    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }

for array initiating where Array.newInstance(class of array, size of array). Class can be both primitive (int.class) and object (Integer.class).

BeanUtils is part of Spring.

How to initialize a List<T> to a given size (as opposed to capacity)?

You can use Linq to cleverly initialize your list with a default value. (Similar to David B's answer.)

var defaultStrings = (new int[10]).Select(x => "my value").ToList();

Go one step farther and initialize each string with distinct values "string 1", "string 2", "string 3", etc:

int x = 1;
var numberedStrings = (new int[10]).Select(x => "string " + x++).ToList();

How to convert a string of bytes into an int?

You can also use the struct module to do this:

>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

Reading the selected value from asp:RadioButtonList using jQuery

following is the code we eventually created. A breif explanation first. We used a "q_" for the div name wrapped around the radio button question list. Then we had "s_" for any sections. The following code loops through the questions to find the checked value, and then performs a slide action on the relevant section.

var shows_6 = function() {
  var selected = $("#q_7 input:radio:checked").val();
  if (selected == 'Groom') {
    $("#s_6").slideDown();
  } else {
    $("#s_6").slideUp();
  }
};
$('#q_7 input').ready(shows_6);
var shows_7 = function() {
  var selected = $("#q_7 input:radio:checked").val();
  if (selected == 'Bride') {
    $("#s_7").slideDown();
  } else {
    $("#s_7").slideUp();
  }
};
$('#q_7 input').ready(shows_7);
$(document).ready(function() {
  $('#q_7 input:radio').click(shows_6);
  $('#q_7 input:radio').click(shows_7);
});

<div id="q_7" class='question '><label>Who are you?</label> 
  <p>
    <label for="ctl00_ctl00_ContentMainPane_Body_ctl00_ctl00_chk_0">Bride</label>
    <input id="ctl00_ctl00_ContentMainPane_Body_ctl00_ctl00_chk_0" type="radio" name="ctl00$ctl00$ContentMainPane$Body$ctl00$ctl00$chk" value="Bride" />
  </p> 
  <p>
    <label for="ctl00_ctl00_ContentMainPane_Body_ctl00_ctl00_chk_1">Groom</label>
    <input id="ctl00_ctl00_ContentMainPane_Body_ctl00_ctl00_chk_1" type="radio" name="ctl00$ctl00$ContentMainPane$Body$ctl00$ctl00$chk" value="Groom" />
  </p> 

</div> 

The following allows us to make the question mandatory...

<script type="text/javascript"> 
var mandatory_q_7 = function() {
  var selected = $("#q_7 input:radio:checked").val();
  if (selected != '') {
    $("#q_7").removeClass('error');
  }
};
$(document).ready(function() {
    $('#q_7 input:radio').click(function(){mandatory_q_7();});
});
</script> 

Here's an example of the actual show / hide layer

<div class="section" id="s_6"> 
    <h2>Attire</h2> 
    ...
</div>

is it possible to evenly distribute buttons across the width of an android linearlayout

Expanding on fedj's answer, if you set layout_width to 0dp and set the layout_weight for each of the buttons to 1, the available width will be shared equally between the buttons.

What is "runtime"?

If my understanding from reading the above answers is correct, Runtime is basically 'background processes' such as garbage collection, memory-allocation, basically any processes that are invoked indirectly, by the libraries / frameworks that your code is written in, and specifically those processes that occur after compilation, while the application is running.

Cannot delete directory with Directory.Delete(path, true)

I had the very same problem under Delphi. And the end result was that my own application was locking the directory I wanted to delete. Somehow the directory got locked when I was writing to it (some temporary files).

The catch 22 was, I made a simple change directory to it's parent before deleting it.

Link a photo with the cell in excel

Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

Format the picture and in the Properties tab select "Move but don't size with cells"

Now you can sort the data table by any column and the pictures will stay with the respective data.

This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

What is the difference between JavaScript and ECMAScript?

ECMAScript = ES:

  • ECMAScript is a Standard for scripting languages.

  • Languages like Javascript are based on the ECMAScript standard.

  • ECMA Standard is based on several originating technologies, the most well known being JavaScript (Netscape) and JScript (Microsoft).

  • ECMA means European Computer Manufacturer’s Association

JavaScript = JS:

  • JavaScript is the most popular implementation of the ECMAScript Standard.

  • The core features of Javascript are based on the ECMAScript standard,  but Javascript also has other additional features that are not in the ECMA specifications/standard.

  • ActionScript and JScript are other languages that implement the ECMAScript.

  • JavaScript was submitted to ECMA for standardization but due to trademark issues with the name Javascript the standard became called ECMAScript.

  • Every browser has a JavaScript interpreter.

ES5 = ECMAScript 5:

  • ES5 is a version of the ECMAScript (old/current one).

  • ES5 is the JavaScript you know and use in the browser today.

  • ES5 does not require a build step (transpilers) to transform it into something that will run in today's browsers.

  • ECMAScript version 5 was finished in December 2009,  the latest versions of all major browsers (Chrome, Safari, Firefox, and IE)  have implemented version 5.

  • Version 5.1 was finished in June, 2011.

ES6 = ECMAScript 6 = ES2015 = ECMAScript 2015:

  • ES2015 is a version of the ECMAScript (new/future one).

  • Officially the name ES2015 should be used instead of ES6.

  • ES6 will tackle many of the core language shortcomings addressed in  TypeScript and CoffeeScript.

  • ES6 is the next iteration of JavaScript, but it does not run in today's browsers.

  • There are quite a few transpilers that will export ES5 for running in browsers.

BabelJS:

  • BabelJS is the most popular transpiler that transforms new JavaScript ES6 to Old JavaScript ES5.

  • BabelJS makes it possible for writing the next generation of JavaScript today (means ES2015).

  • BabelJS simply takes ES2015 file and transform it into ES5 file.

  • Current browsers versions can now understand the new JavaScript code (ES2015), even if they don't yet support it.

TypeScript and CoffeeScript:

  • Both provides syntactic sugar on top of ES5  and then are transcompiled into ES5 compliant JavaScript. 

  • You write TypeScript or CoffeeScript then the transpiler transforms it into ES5 JavaScript.

What is middleware exactly?

There are (at least) three different definitions I'm aware of

  • in business computing, middleware is messaging and integration software between applications and services

  • in gaming, middleware is pretty well anything that is provided by a third-party

  • in (some) embedded software systems, middleware provides services that applications use, which are composed out of the functions provided by the hardware abstraction layer - it sits between the application layer and the hardware abstraction layer.

Search and replace a line in a file in Python

If you're wanting a generic function that replaces any text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:

import re
def replace( filePath, text, subs, flags=0 ):
    with open( filePath, "r+" ) as file:
        fileContents = file.read()
        textPattern = re.compile( re.escape( text ), flags )
        fileContents = textPattern.sub( subs, fileContents )
        file.seek( 0 )
        file.truncate()
        file.write( fileContents )

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

How can I pass a list as a command-line argument with argparse?

In add_argument(), type is just a callable object that receives string and returns option value.

import ast

def arg_as_list(s):                                                            
    v = ast.literal_eval(s)                                                    
    if type(v) is not list:                                                    
        raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
    return v                                                                   


def foo():
    parser.add_argument("--list", type=arg_as_list, default=[],
                        help="List of values")

This will allow to:

$ ./tool --list "[1,2,3,4]"

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

Set Culture in an ASP.Net MVC app

I would do it in the Initialize event of the controller like this...

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        const string culture = "en-US";
        CultureInfo ci = CultureInfo.GetCultureInfo(culture);

        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

 WebElement p= driver.findElement(By.id("your id name"));
 p.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

what's the correct way to send a file from REST web service to client?

If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:

@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
            //you can use the key parameter to indentify your file
            //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
                object.getDataInputStream());
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            outStream.write(bbuf, 0, length);
        }
        in.close();
        outStream.flush();
    } catch (S3ServiceException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
    return Response.ok().build();
}

Understanding the main method of python

The Python approach to "main" is almost unique to the language(*).

The semantics are a bit subtle. The __name__ identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__ is set to "__main__" (the literal string: __main__).

This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.

It's important to understand that all of the code above the if __name__ line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print statement before the if __name__ line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__" to isolate a block of code which calls a suite of unit tests that apply to this module.

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

Summary: if __name__ == '__main__': has two primary use cases:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.

It's fairly common to def main(*args) and have if __name__ == '__main__': simply call main(*sys.argv[1:]) if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module() and calling test_module() in your if __name__ == '__main__:' suite.

  • (Ruby also implements a similar feature if __file__ == $0).

What is a Memory Heap?

Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

  1. The memory is free'd
  2. The program terminates

If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.

Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).

You can find more information about the heap in this article.

What is the "right" JSON date format?

"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT- 
    1000 (Hawaiian Standard Time) 
        
    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);  
console.log(dateStr); // 2014-01-01T23:28:56.782Z

What is Ad Hoc Query?

In Sql Server "Ad Hoc Query" is also used for Ad Hoc Distributed Queries. These are ad hoc queries on an other server via OpenRowset or OpenDatasource. Ad Hoc Distributed Queries are only allowed after configuring so. This is a Server configuration option.

JavaScript chop/slice/trim off last character in string

Here is an alternative that i don't think i've seen in the other answers, just for fun.

_x000D_
_x000D_
var strArr = "hello i'm a string".split("");_x000D_
strArr.pop();_x000D_
document.write(strArr.join(""));
_x000D_
_x000D_
_x000D_

Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.

Temporarily switch working copy to a specific Git commit

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

How to deep copy a list?

If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.

you can also use shortest way for deep copy a list like this.

a = [0,1,2,3,4,5,6,7,8,9,10]
b = a[:] #deep copying the list a and assigning it to b
print id(a)
20983280
print id(b)
12967208

a[2] = 20
print a
[0, 1, 20, 3, 4, 5, 6, 7, 8, 9,10]
print b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]

Not able to pip install pickle in python 3.6

Pickle is a module installed for both Python 2 and Python 3 by default. See the standard library for 3.6.4 and 2.7.

Also to prove what I am saying is correct try running this script:

import pickle
print(pickle.__doc__)

This will print out the Pickle documentation showing you all the functions (and a bit more) it provides.

Or you can start the integrated Python 3.6 Module Docs and check there.

As a rule of thumb: if you can import the module without an error being produced then it is installed

The reason for the No matching distribution found for pickle is because libraries for included packages are not available via pip because you already have them (I found this out yesterday when I tried to install an integrated package).

If it's running without errors but it doesn't work as expected I would think that you made a mistake somewhere (perhaps quickly check the functions you are using in the docs). Python is very informative with it's errors so we generally know if something is wrong.

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

The JWT aud (Audience) Claim

According to RFC 7519:

The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

The Audience (aud) claim as defined by the spec is generic, and is application specific. The intended use is to identify intended recipients of the token. What a recipient means is application specific. An audience value is either a list of strings, or it can be a single string if there is only one aud claim. The creator of the token does not enforce that aud is validated correctly, the responsibility is the recipient's to determine whether the token should be used.

Whatever the value is, when a recipient is validating the JWT and it wishes to validate that the token was intended to be used for its purposes, it MUST determine what value in aud identifies itself, and the token should only validate if the recipient's declared ID is present in the aud claim. It does not matter if this is a URL or some other application specific string. For example, if my system decides to identify itself in aud with the string: api3.app.com, then it should only accept the JWT if the aud claim contains api3.app.com in its list of audience values.

Of course, recipients may choose to disregard aud, so this is only useful if a recipient would like positive validation that the token was created for it specifically.

My interpretation based on the specification is that the aud claim is useful to create purpose-built JWTs that are only valid for certain purposes. For one system, this may mean you would like a token to be valid for some features but not for others. You could issue tokens that are restricted to only a certain "audience", while still using the same keys and validation algorithm.

Since in the typical case a JWT is generated by a trusted service, and used by other trusted systems (systems which do not want to use invalid tokens), these systems simply need to coordinate the values they will be using.

Of course, aud is completely optional and can be ignored if your use case doesn't warrant it. If you don't want to restrict tokens to being used by specific audiences, or none of your systems actually will validate the aud token, then it is useless.

Example: Access vs. Refresh Tokens

One contrived (yet simple) example I can think of is perhaps we want to use JWTs for access and refresh tokens without having to implement separate encryption keys and algorithms, but simply want to ensure that access tokens will not validate as refresh tokens, or vice-versa.

By using aud, we can specify a claim of refresh for refresh tokens and a claim of access for access tokens upon creating these tokens. When a request is made to get a new access token from a refresh token, we need to validate that the refresh token was a genuine refresh token. The aud validation as described above will tell us whether the token was actually a valid refresh token by looking specifically for a claim of refresh in aud.

OAuth Client ID vs. JWT aud Claim

The OAuth Client ID is completely unrelated, and has no direct correlation to JWT aud claims. From the perspective of OAuth, the tokens are opaque objects.

The application which accepts these tokens is responsible for parsing and validating the meaning of these tokens. I don't see much value in specifying OAuth Client ID within a JWT aud claim.

Convert date to datetime in Python

One way to convert from date to datetime that hasn't been mentioned yet:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')

How to uninstall mini conda? python

your have to comment that line in ~/.bashrc:

#export PATH=/home/jolth/miniconda3/bin:$PATH

and run:

source ~/.bashrc

Choosing the default value of an Enum type without having to change values

The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).

enum Orientation
{
    None = 0, //default value since it has the value '0'
    North = 1,
    East = 2,
    South = 3,
    West = 4
}

Orientation o; // initialized to 'None'

If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." (C# reference)

enum Orientation
{
    None, //default value since it is the first enumerator
    North,
    East,
    South,
    West
}

Orientation o; // initialized to 'None'

Send email using the GMail SMTP server from a PHP page

I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to replace an entire line in a text file by line number

Not the greatest, but this should work:

sed -i 'Ns/.*/replacement-line/' file.txt

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

sed 'Ns/.*/replacement-line/' file.txt > new_file.txt

How to completely uninstall kubernetes

The guide you linked now has a Tear Down section:

Talking to the master with the appropriate credentials, run:

kubectl drain <node name> --delete-local-data --force --ignore-daemonsets
kubectl delete node <node name>

Then, on the node being removed, reset all kubeadm installed state:

kubeadm reset

What does the @ symbol before a variable name mean in C#?

An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.

So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.

It is not that useful in practice, but not having it would prevent C# from some forms of language interop.

I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.

private void Foo(){
   int @this = 2;
}

but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

Sending email in .NET through Gmail

Here is one method to send mail and getting credentials from web.config:

public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
    try
    {
        System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
        newMsg.BodyEncoding = System.Text.Encoding.UTF8;
        newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
        newMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
        if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
            System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
            disposition.FileName = AttachmentFileName;
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

            newMsg.Attachments.Add(attachment);
        }
        if (test)
        {
            smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
        }
        else
        {
            //smtpClient.EnableSsl = true;
        }

        newMsg.IsBodyHtml = bodyHtml;
        smtpClient.Send(newMsg);
        return SENT_OK;
    }
    catch (Exception ex)
    {

        return "Error: " + ex.Message
             + "<br/><br/>Inner Exception: "
             + ex.InnerException;
    }

}

And the corresponding section in web.config:

<appSettings>
    <add key="mailCfg" value="[email protected]"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="[email protected]">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="[email protected]" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

How do you run a crontab in Cygwin on Windows?

hat tip http://linux.subogero.com/894/cron-on-cygwin/

Start the cygwin-setup and add the “cron” package from the “Admin” category.

We’ll run cron as a service by user SYSTEM. Poor SYSTEM therefore needs a home directory and a shell. The “/etc/passwd” file will define them.

$ mkdir /root
$ chown SYSTEM:root /root
$ mcedit /etc/passwd
SYSTEM:*:......:/root:/bin/bash

The start the service:

$ cron-config
Do you want to remove or reinstall it (yes/no) yes
Do you want to install the cron daemon as a service? (yes/no) yes
Enter the value of CYGWIN for the daemon: [ ] ntsec
Do you want the cron daemon to run as yourself? (yes/no) no
Do you want to start the cron daemon as a service now? (yes/no) yes

Local users can now define their scheduled tasks like this (crontab will start your favourite editor):

$ crontab -e  # edit your user specific cron-table HOME=/home/foo
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
# testing - one per line
* * * * *   touch ~/cron
@reboot     ~/foo.sh
45 11 * * * ~/lunch_message_to_mates.sh

Domain users: it does not work. Poor cron is unable to run scheduled tasks on behalf of domain users on the machine. But there is another way: cron also runs stuff found in the system level cron table in “/etc/crontab”. So insert your suff there, so that SYSTEM does it on its own behalf:

$ touch /etc/crontab
$ chown SYSTEM /etc/crontab
$ mcedit /etc/crontab
HOME=/root
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
* * * * *   SYSTEM touch ~/cron
@reboot     SYSTEM rm -f /tmp/.ssh*

Finally a few words about crontab entries. They are either environment settings or scheduled commands. As seen above, on Cygwin it’s best to create a usable PATH. Home dir and shell are normally taken from “/etc/passwd”.

As to the columns of scheduled commands see the manual page.

If certain crontab entries do not run, the best diagnostic tool is this:

$ cronevents

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

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

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

How to declare a global variable in php?

You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
    echo "$foo $bar";
})("York");

demo | info

Reverse engineering from an APK file to a project

Yes, you can get your project back. Just rename the yourproject.apk file to yourproject.zip, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex file and decompile it by following way.

First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.

Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

Write single CSV file using spark-csv

A solution that works for S3 modified from Minkymorgan.

Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath and single final csv/txt as destPath Specify also deleteSource if you want to remove the original directory.

/**
* Merges multiple partitions of spark text file output into single file. 
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit =  {
  import org.apache.hadoop.fs.FileUtil
  import java.net.URI
  val config = spark.sparkContext.hadoopConfiguration
  val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
  FileUtil.copyMerge(
    fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
  )
}

How do I create a file AND any folders, if the folders don't exist?

You will need to check both parts of the path (directory and filename) and create each if it does not exist.

Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.

How do I push amended commit to the remote Git repository?

You are getting this error because the Git remote already has these commit files. You have to force push the branch for this to work:

git push -f origin branch_name

Also make sure you pull the code from remote as someone else on your team might have pushed to the same branch.

git pull origin branch_name

This is one of the cases where we have to force push the commit to remote.

MySQL select where column is not empty

you can use like operator wildcard to achieve this:

SELECT t.phone, 
       t.phone2 
FROM jewishyellow.users t
WHERE t.phone LIKE '813%' 
  AND t.phone2 like '[0-9]';

in this way, you could get all phone2 that have a number prefix.

How do I dynamically change the content in an iframe using jquery?

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

Read only file system on Android

In my case I was using the command adb push ~/Desktop/file.txt ~/sdcard/

I changed it to ~/Desktop/file.txt /sdcard/ and then it worked.

Make sure to disconnect and reconnect the phone.

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

Change a Rails application to production

As others have posted: rails server -e production

Or, my personal fave: RAILS_ENV=production rails s

No server in Eclipse; trying to install Tomcat

Eclipse IDE for Java Developers 'Servers' doesn't exist. Therefore download correct Eclipse IDE. It is Eclipse IDE for Enterprise Java Developers(Eclipse IDE for Java EE Developers). This way is easy.

No internet on Android emulator - why and how to fix?

If you run into this problem and are working with a non-Windows/Mac OS (Ubuntu in my case), try starting the emulator by itself in Android SDK and AVD Manager then running your application.

gcc/g++: "No such file or directory"

Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds:

#include "bar"

or

#include <bar>

The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.

How to tell the compiler where to find it

g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to foo.cc (assume you are compiling from the directory where foo.cc is located):

g++ -Ifrobnicate foo.cc

You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.

Now imagine you have multiple version of bar in different folders, given:


// A/bar
#include<string>
std::string which() { return "A/bar"; }

// B/bar
#include<string>
std::string which() { return "B/bar"; }

// C/bar
#include<string>
std::string which() { return "C/bar"; }

// foo.cc
#include "bar"
#include <iostream>

int main () {
    std::cout << which() << std::endl;
}

The priority with #include "bar" is leftmost:

$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar

As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.

This is true of both forms, include <> and incude "".

Difference between #include <bar> and #include "bar"

Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.

E.g.:

Imagine you have the following files in your project folder:

list
main.cc

with main.cc:

#include "list"
....

For this, your compiler will #include the file list in your project folder, because it currently compiles main.cc and there is that file list in the current folder.

But with main.cc:

#include <list>
....

and then g++ main.cc, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.

This is all a bit simplified, but should give you the basic idea.

Details on <>/""-priorities and -I

According to the gcc-documentation, the priority for include <> is, on a "normal Unix system", as follows:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].

The documentation also states:

You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.

To continue our #include<list> / #include"list" example (same code):

g++ -I. main.cc

and

#include<list>
int main () { std::list<int> l; }

and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

Text vertical alignment in WPF TextBlock

You can see my blog post. You can set custom height of Textblock from codebehind. For setting custom height you need to set it inside in a border or stackpanel

http://ciintelligence.blogspot.com/2011/02/wpf-textblock-vertical-alignment-with.html

What is a magic number, and why is it bad?

In programming, a "magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.

It's bad for the same reason SPOT (Single Point of Truth) is good: If you wanted to change this constant later, you would have to hunt through your code to find every instance. It is also bad because it might not be clear to other programmers what this number represents, hence the "magic".

People sometimes take magic number elimination further, by moving these constants into separate files to act as configuration. This is sometimes helpful, but can also create more complexity than it's worth.

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

It wasn't working for me. I run crontab with sudo, so I switched to root, did the above suggestions, and crontab would open in vim, but it still wouldn't from my user account. Finally I ran sudo select-editor from the user account and that did the trick.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

What does a just-in-time (JIT) compiler do?

A non-JIT compiler takes source code and transforms it into machine specific byte code at compile time. A JIT compiler takes machine agnostic byte code that was generated at compile time and transforms it into machine specific byte code at run time. The JIT compiler that Java uses is what allows a single binary to run on a multitude of platforms without modification.

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

Explain the different tiers of 2 tier & 3 tier architecture?

Wikipedia explains it better then I could

From the article - Top is 1st Tier: alt text

Android TextView Justify Text

The @CommonsWare answer is correct. Android 8.0+ does support "Full Justification" (or simply "Justification", as it is sometimes ambiguously referred to).

Android also supports "Flush Left/Right Text Alignment". See the wikipedia article on Justification for the distinction. Many people consider the concept of 'justification' to encompass full-justification as well as left/right text alignment, which is what they end up searching for when they want to do left/right text alignment. This answer explains how to achieve the left/right text alignment.

It is possible to achieve Flush Left/Right Text Alignment (as opposed to Full Justification, as the question is asking about). To demonstrate I will be using a basic 2-column form (labels in the left column and text fields in the right column) as an example. In this example the text in the labels in the left column will be right-aligned so they appear flush up against their text fields in the right column.

In the XML layout you can get the TextView elements themselves (the left column) to align to the right by adding the following attribute inside all of the TextViews:

<TextView
   ...
   android:layout_gravity="center_vertical|end">
   ...
</TextView>

However, if the text wraps to multiple lines, the text would still be flush left aligned inside the TextView. Adding the following attribute makes the actual text flush right aligned (ragged left) inside the TextView:

<TextView
   ...
   android:gravity="end">
   ...
</TextView>

So the gravity attribute specifies how to align the text inside the TextView layout_gravity specifies how to align/layout the TextView element itself.

Sending data back to the Main Activity in Android

Sending Data Back

It helps me to see things in context. Here is a complete simple project for sending data back. Rather than providing the xml layout files, here is an image.

enter image description here

Main Activity

  • Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
  • Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the request code. (This is useful when you are starting multiple different activities from the same main activity.)
  • Extract the data you got from the return Intent. The data is extracted using a key-value pair.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // Set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

Second Activity

  • Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair.
  • Set the result to RESULT_OK and add the intent holding your data.
  • Call finish() to close the Second Activity.

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // Get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // Put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

Other notes

  • If you are in a Fragment it won't know the meaning of RESULT_OK. Just use the full name: Activity.RESULT_OK.

See also

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

How to see if an object is an array without using reflection?

You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

Compiler error "archive for required library could not be read" - Spring Tool Suite

In my case I had to manually delete all the files in .m2\repository folder and then open command prompt and run mvn -install command in my project directory.

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Why is it not advisable to have the database and web server on the same machine?

It depends on the application and the purpose. When high availability and performance is not critical, it's not bad to not to separate the DB and web server. Especially considering the performance gains - if the appliation makes a large amount of database queries, a considerable amount of network load can be removed by keeping it all on the same system, keeping the response times low.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

How to change an input button image using CSS?

Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.

"UnboundLocalError: local variable referenced before assignment" after an if statement

To Solve this Error just initialize that variable above that loop or statement. For Example var a =""

How can I show current location on a Google Map on Android Marshmallow?

Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.

import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {


    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    private double latitudeVillageApartmets= 53.385952001750184;
    private double longitudeVillageApartments= -6.599087119102478;


    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
 }
    /*These methods all have to do with the map and wht happens if the activity is paused etc*/
    //contains lat and lon of another marker
    private void setUpMap() {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
    }

    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

}

There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.

The transaction log for the database is full

I met the error: "The transaction log for database '...' is full due to 'ACTIVE_TRANSACTION' while deleting old rows from tables of my database for freeing disk space. I realized that this error would occur if the number of rows to be deleted was bigger than 1000000 in my case. So instead of using 1 DELETE statement, i divided the delete task by using DELETE TOP (1000000).... statement.

For example:

instead of using this statement:

DELETE FROM Vt30 WHERE Rt < DATEADD(YEAR, -1, GETDATE())

using following statement repeatedly:

DELETE TOP(1000000) FROM Vt30 WHERE Rt < DATEADD(YEAR, -1, GETDATE())

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

To truly force maven to only use your local repo, you can run with mvn <goals> -o. The -o tells maven to let you work "offline", and it will stay off the network.

Efficient way to rotate a list in python

This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list. Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists:

def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l

In fact, even adding a l = l[:] to the top of that to operate on a copy of the list passed in is still twice as fast.

Various implementations with some timing at http://gist.github.com/288272

Setting an image for a UIButton in code

In case of Swift User

// case of normal image
let image1 = UIImage(named: "your_image_file_name_without_extension")!
button1.setImage(image1, forState: UIControlState.Normal) 

// in case you don't want image to change when "clicked", you can leave code below
// case of when button is clicked
let image2 = UIImage(named: "image_clicked")!
button1.setImage(image2, forState: UIControlState.Highlight) 

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.

How to strip HTML tags from string in JavaScript?

var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World

That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.


Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:

alert($("<p>Hello, <b>World</b></p>").text());

Check out the text method.

dynamic_cast and static_cast in C++

A dynamic_cast performs a type checking using RTTI. If it fails it'll throw you an exception (if you gave it a reference) or NULL if you gave it a pointer.

Structs in Javascript

I always use object literals

{id: 1, speaker:"john", country: "au"}

Android view pager with page indicator

Just an improvement to the nice answer given by @vuhung3990. I implemented the solution and works great but if I touch one radio button it will be selected and nothing happens.

I suggest to also change page when a radio button is tapped. To do this, simply add a listener to the radioGroup:

mPager = (ViewPager) findViewById(R.id.pager);
final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);    
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton :
                        mPager.setCurrentItem(0, true);
                        break;
                    case R.id.radioButton2 :
                        mPager.setCurrentItem(1, true);
                        break;
                    case R.id.radioButton3 :
                        mPager.setCurrentItem(2, true);
                        break;
                }
            }
        });

How to create a DOM node as an object?

There are three reasons why your example fails.

  1. The original 'template' variable is not a jQuery/DOM object and cannot be parsed, it is a string. Make it a jQuery object by wrapping it in $(), such as: template = $(template)

  2. Once the 'template' variable is a jQuery object you need to realize that <li> is the root object. Therefore you cannot search for the LI root node and get any results. Simply apply the ID to the jQuery object.

  3. When you assign an ID to an HTML element it cannot begin with a number character with any HTML version before HTML5. It must begin with an alphabetic character. With HTML5 this can be any non-whitespace character. For details refer to: What are valid values for the id attribute in HTML?

PS: A final issue with the sample code is an LI cannot be applied to the BODY. According to HTML requirements it must always be contained within a list, i.e. UL or OL.

Creating default object from empty value in PHP?

Try this if you have array and add objects to it.

$product_details = array();

foreach ($products_in_store as $key => $objects) {
  $product_details[$key] = new stdClass(); //the magic
  $product_details[$key]->product_id = $objects->id; 
   //see new object member created on the fly without warning.
}

This sends ARRAY of Objects for later use~!

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

Path of currently executing powershell script

In powershell 2.0

split-path $pwd

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

Split function in oracle to comma separated values with automatic sequence

Oracle Setup:

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

Query

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

Output:

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

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

ImportError: no module named win32api

After installing pywin32

Steps to correctly install your module (pywin32)

  1. First search where is your python pip is present

    1a. For Example in my case location of pip - C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts

  2. Then open your command prompt and change directory to your pip folder location.

    cd C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
    
    C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts>pip install 
    pypiwin32
    

Restart your IDE

All done now you can use the module .

How can I get browser to prompt to save password?

I have been struggling with this myself, and I finally was able to track down the issue and what was causing it to fail.

It all stemmed from the fact that my login form was being dynamically injected into the page (using backbone.js). As soon as I embed my login form directly into my index.html file, everything worked like a charm.

I think this is because the browser has to be aware that there is an existing login form, but since mine was being dynamically injected into the page, it didn't know that a "real" login form ever existed.

Is there a way to specify how many characters of a string to print out using printf()?

Print first four characters:

printf("%.4s\n", "A string that is more than 8 chars");

See this link for more information (check .precision -section)

Find kth smallest element in a binary search tree in Optimum way

Solution for complete BST case :-

Node kSmallest(Node root, int k) {
  int i = root.size(); // 2^height - 1, single node is height = 1;
  Node result = root;
  while (i - 1 > k) {
    i = (i-1)/2;  // size of left subtree
    if (k < i) {
      result = result.left;
    } else {
      result = result.right;
      k -= i;
    }  
  }
  return i-1==k ? result: null;
}

Countdown timer using Moment js

The following also requires the moment-duration-format plugin:

$.fn.countdown = function ( options ) {
    var $target = $(this);
    var defaults = {
        seconds: 0,
        format: 'hh:mm:ss',
        stopAtZero: true
    };
    var settings = $.extend(defaults, options);
    var eventTime = Date.now() + ( settings.seconds * 1000 );
    var diffTime = eventTime - Date.now();
    var duration = moment.duration( diffTime, 'milliseconds' );
    var interval = 0;
    $target.text( duration.format( settings.format, { trim: false }) );
    var counter = setInterval(function () {
        $target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
        if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
    }, 1000);
};

Usage example:

$('#someDiv').countdown({
    seconds: 30*60,
    format: 'mm:ss'
});

Sort array of objects by single key with date value

You can create a closure and pass it that way here is my example working

$.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)', 
  function(responce) {

    var filter = 'event_clearance_group', //sort by key group name
    data = responce; 

    var compare = function (filter) {
        return function (a,b) {
            var a = a[filter],
                b = b[filter];

            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        };
    };

    filter = compare(filter); //set filter

    console.log(data.sort(filter));
});

How Do I Uninstall Yarn

I couldn't uninstall yarn on windows and I tried every single answer here, but every time I ran yarn -v, the command worked. But then I realized that there is another thing that can affect this.

If you on windows (not sure if this also happens in mac) and using nvm, one problem that can happen is that you have installed nvm without uninstalling npm, and the working yarn command is from your old yarn version from the old npm.

So what you need to do is follow this step from the nvm docs

You should also delete the existing npm install location (e.g. "C:\Users<user>\AppData\Roaming\npm"), so that the nvm install location will be correctly used instead. Backup the global npmrc config (e.g. C:\Users&lt;user>\AppData\Roaming\npm\etc\npmrc), if you have some important settings there, or copy the settings to the user config C:\Users&lt;user>.npmrc.

And to confirm that you problem is with the old npm, you will probably see the yarn.cmd file inside the C:\Users\<user>\AppData\Roaming\npm folder.

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Is it possible to CONTINUE a loop from an exception?

Notice you can use WHEN exception THEN NULL the same way as you would use WHEN exception THEN continue. Example:

    DECLARE
        extension_already_exists  EXCEPTION;
        PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
        l_hidden_col_name  varchar2(32);
    BEGIN
        FOR t IN (  SELECT table_name, cast(extension as varchar2(200)) ext
                    FROM all_stat_extensions
                    WHERE owner='{{ prev_schema }}'
                      and droppable='YES'
                    ORDER BY 1
                 )
        LOOP
            BEGIN
                l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
            EXCEPTION
                WHEN extension_already_exists THEN NULL;   -- ignore exception and go to next loop iteration
            END;
        END LOOP;
    END;

How to repeat a string a variable number of times in C++?

There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:

std::string(5, '.')

This is a contrived example of how you might use an ostringstream to repeat a string n times:

#include <sstream>

std::string repeat(int n) {
    std::ostringstream os;
    for(int i = 0; i < n; i++)
        os << "repeat";
    return os.str();
}

Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, so now we can simply write

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">

If you are using an earlier version of Angular, your two choices are:

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

E.g.,

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values.

An example of 1) was given above. Here is an example of 3, which I think reads much better:

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

Spring Boot - Cannot determine embedded database driver class for database type NONE

I don't if it is too late to answer. I could solve this issue by excluding DataSourceAutoConfiguration from spring boot.

How to increase the Java stack size?

Hmm... it works for me and with far less than 999MB of stack:

> java -Xss4m Test
0

(Windows JDK 7, build 17.0-b05 client VM, and Linux JDK 6 - same version information as you posted)

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

XmlSerializer: remove unnecessary xsi and xsd namespaces

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

Simple pthread! C++

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

The function passed to pthread_create must have a prototype of

void* name(void *arg)

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

Add element to a JSON file?

You can do this.

data[0]['f'] = var

PHP float with 2 decimal places: .00

You can use this simple function. number_format ()

    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

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

@mcbjam already gave this answer but here's a bit more explanation.

You can easily make the change using a media query in your CSS file without downloading BS. I just did this and it works beautifully.

The media query's "min-width" value will tell CSS to change the width of your container to 1000px only on screens larger than 1200px (or whatever width you choose to include there). This preserves the responsiveness of your site, so when the screen size jumps below that value (smaller monitor, tablet, smartphone, etc.), your site will still adjust to fit the smaller screens.

@media (min-width: 1200px) {
  .container {
    width: 1000px;
  }
}

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

How to select the Date Picker In Selenium WebDriver

You can try this, see if it works for you.

Rather than choosing date from date picker, you can enable the date box using javascript & enter the required date, this would avoid excessive time required to traverse through all date elements till you reach one you require to select.

Code for from date

((JavascriptExecutor)driver).executeScript ("document.getElementById('fromDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement fromDateBox= driver.findElement(By.id("fromDate"));
fromDateBox.clear();
fromDateBox.sendKeys("8-Dec-2014"); //Enter date in required format

Code for to date

((JavascriptExecutor)driver).executeScript ("document.getElementById('toDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement toDateBox= driver.findElement(By.id("toDate"));
toDateBox.clear();
toDateBox.sendKeys("15-Dec-2014"); //Enter date in required format

Android: Align button to bottom-right of screen using FrameLayout?

You can't do it with FrameLayout.

From spec:

http://developer.android.com/reference/android/widget/FrameLayout.html

"FrameLayout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen."

Why not to use RelativeLayout?

How to solve privileges issues when restore PostgreSQL Database

For people who have narrowed down the issue to the COMMENT ON statements (as per various answers below) and who have superuser access to the source database from which the dump file is created, the simplest solution might be to prevent the comments from being included to the dump file in the first place, by removing them from the source database being dumped...

COMMENT ON EXTENSION postgis IS NULL;
COMMENT ON EXTENSION plpgsql IS NULL;
COMMENT ON SCHEMA public IS NULL;

Future dumps then won't include the COMMENT ON statements.

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

How to manually set an authenticated user in Spring Security / SpringMVC

I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.

public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
                           RequestContext requestContext,
                           ExternalContext externalContext) {

    try {
        Locale userLocale = requestContext.getExternalContext().getLocale();
        this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
        String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
        String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
        doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
        return "success";

    } catch (EmailAddressNotUniqueException e) {
        MessageResolver messageResolvable 
                = new MessageBuilder().error()
                                      .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
                                      .code("userRegistration.emailAddress.not.unique")
                                      .build();
        requestContext.getMessageContext().addMessage(messageResolvable);
        return "error";
    }

}


private void doAutoLogin(String username, String password, HttpServletRequest request) {

    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationProvider.authenticate(token);
        logger.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        logger.error("Failure in autoLogin", e);
    }

}

Difference between CR LF, LF and CR line break types?

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)

Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.

How to disable Google Chrome auto update?

If you are using Mac OS. Keep the version that you need and then following step help you stop updating chrome permanently.

To Disable auto update:-

Empty these directories:

~/Library/Google/GoogleSoftwareUpdate/

Then change the permissions on these folders named 'GoogleSoftwareUpdate' so that there's no owner and no read/write/execute permissions. In terminal:

cd /Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate

cd ~/Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate                                                                        

Then do the same for the folder Google one level up.

cd /Library/
sudo chown nobody:nogroup Google
sudo chmod 000 Google
cd ~/Library/                                                                                                                    
sudo chown nobody:nogroup Google
sudo chmod 000 Google

Hope this help!

Installing PHP Zip Extension

1 Step - Install a required extension

sudo apt-get install libz-dev -y

2 Step - Install the PHP extension

pecl install zlib zip

3 Step - Restart your Apache

sudo /etc/init.d/apache2 restart

Enable PHP ZIP Extension

If does not work you can check if the zip.ini is called in your phpinfo, to check if the zip.so was included.

get unique machine id

Check out this article. It is very exhaustive and you will find how to extract various hardware information.

Quote from the article:

To get hardware information, you need to create an object of ManagementObjectSearcher class.

using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
    // Some Codes ...
}

The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.

How to get the selected radio button value using js

you can use this

$('input[name="field_value"]:checked').val(); 

or, for older version of jquery

$('input[@name="field_value"]:checked').val();

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

Setting Camera Parameters in OpenCV/Python

Not all parameters are supported by all cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to USB cameras to professional ones offer a different interface to modify its parameters. There are many branches in OpenCV code to support as many of them, but of course not all possibilities are covered.

What you can do is to investigate your camera driver, write a patch for OpenCV and send it to code.opencv.org. This way others will enjoy your work, the same way you enjoy others'.

There is also a possibility that your camera does not support your request - most USB cams are cheap and simple. Maybe that parameter is just not available for modifications.

If you are sure the camera supports a given param (you say the camera manufacturer provides some code) and do not want to mess with OpenCV, you can wrap that sample code in C++ with boost::python, to make it available in Python. Then, enjoy using it.

Creating JSON on the fly with JObject

Sooner or later you will have property with special character. You can either use index or combination of index and property.

dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use

HTML5 textarea placeholder not appearing

Well, technically it does not have to be on the same line as long as there is no character between the ending ">" from start tag and the starting "<" from the closing tag. That is you need to end with ...></textarea> as in the example below:

<p><label>Comments:<br>
       <textarea id = "comments" rows = "4" cols = "36" 
            placeholder = "Enter comments here"
            class = "valid"></textarea>
    </label>
</p>

Egit rejected non-fast-forward

Applicable for Eclipse Luna + Eclipse Git 3.6.1

I,

  1. cloned git repository
  2. made some changes in source code
  3. staged changes from Git Staging View
  4. finally, commit and Push!

And I faced this issue with EGit and here is how I fixed it..

Yes, someone committed the changes before I commit my changes. So the changes are rejected. After this error, the changes gets actually committed to local repository. I did not want to just Pull the changes because I wanted to maintain linear history as pointed out in - In what cases could `git pull` be harmful?

So, I executed following steps

  1. from Git Repository perspective, right click on the concerned Git
    project
  2. select Fetch from Upstream - it fetches remote updates (refs and objects) but no updates are made locally. for more info refer What is the difference between 'git pull' and 'git fetch'?
  3. select Rebase... - this open a popup, click on Preserve merges during rebase see why
    What exactly does git's "rebase --preserve-merges" do (and why?)
  4. click on Rebase button
  5. if there is/are a conflict(s), go to step 6 else step 11
  6. a Rebase Result popup would appear, just click on OK
  7. file comparator would open up, you need to modify left side file.
  8. once you are done with merging changes correctly, goto Git Staging view
  9. stage the changes. i.e. add to index
  10. on the same view, click on Rebase-> Continue. repeat 7 to 10 until all conflicts are resolved.
  11. from History view, select your commit row and select Push Commit
  12. select Rebase Commits of local....... checkbox and click next. refer why - Git: rebase onto development branch from upstream
  13. click on Finish

Note: if you have multiple local repository commits, you need to squash them in one commit to avoid multiple merges.

Linking a qtDesigner .ui file to python/pyqt?

Combining Max's answer and Shriramana Sharma's mailing list post, I built a small working example for loading a mywindow.ui file containing a QMainWindow (so just choose to create a Main Window in Qt Designer's File-New dialog).

This is the code that loads it:

import sys
from PyQt4 import QtGui, uic

class MyWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('mywindow.ui', self)
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MyWindow()
    sys.exit(app.exec_())

Switching users inside Docker image to a non-root user

You should also be able to do:

apt install sudo

sudo -i -u tomcat

Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.

Unrecognized SSL message, plaintext connection? Exception

It worked for me now, I have change the setting of my google account as below:

        System.out.println("Start");
        final String username = "[email protected]";
        final String password = "************";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

         Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                  });


        try {
            Transport transport=session.getTransport();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));//formBean.getString("fromEmail")
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
            message.setSubject("subject");//formBean.getString(
            message.setText("mailBody");
            transport.connect();
            transport.send(message, InternetAddress.parse("[email protected]"));//(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            System.out.println("e="+e);
            e.printStackTrace();
            throw new RuntimeException(e);

        }

Though I have enabled SSL and TSL while running program in this link of same post. I spend a lot of time but than I realized and found this link. And done 2 following steps and setting control in google. :

  • Disable the 2-step verification (password and OTP)

  • Enabling to allow to access less secure app(Allow less secure apps: ON.)

Now I am able to send mail using above program.

Reload activity in Android

for those who don't want to see that blink after recreate() method simply use

 finish();
 overridePendingTransition(0, 0);
 startActivity(getIntent());
 overridePendingTransition(0, 0);

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

GridView sorting: SortDirection always Ascending

Automatic bidirectional sorting only works with the SQL data source. Unfortunately, all the documentation in MSDN assumes you are using that, so GridView can get a bit frustrating.

The way I do it is by keeping track of the order on my own. For example:

    protected void OnSortingResults(object sender, GridViewSortEventArgs e)
    {
        // If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
        // e.SortDirection is useless and unreliable (only works with SQL data source).
        if (_sortBy == e.SortExpression)
            _sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        else
            _sortDirection = SortDirection.Ascending;

        _sortBy = e.SortExpression;

        BindResults();
    }

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

Android: remove left margin from actionbar's custom layout

You need to add this line app2:contentInsetStart="0dp" in your toolbar

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app2="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    app2:contentInsetStart="0dp"/>

How to set delay in android?

Using the Thread.sleep(millis) method.

using extern template (C++11)

Wikipedia has the best description

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

  template class std::vector<MyClass>;

C++11 now provides this syntax:

  extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.

The warning: nonstandard extension used...

Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.

Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.

Elegant solution for line-breaks (PHP)

Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

Interface naming in Java

Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:

public void doSomething(Collection someStuff) {
    ...
}

than this:

public void doSomething(Vector someStuff) {
    ...
}

If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.

The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.

If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.

Load resources from relative path using local html in uiwebview

This is how to load/use a local html with relative references.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

Function to check if a string is a date

I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically

$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
    //it's a proper date!
}
else {
    //it's not a proper date
}

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I was experiencing this same error, and spent forever adding the suggested startup statements to various config files in my solution, attempting to isolate the framework mismatch. Nothing worked. I also added startup information to my XML schemas. That didn't help either. Looking at the actual file that was causing the problem (which would only say it was "moved or deleted") revealed it was actually the License Compiler (LC).

Deleting the offending licenses.licx file seems to have fixed the problem.

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

C++ convert from 1 char to string?

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

Getting "cannot find Symbol" in Java project in Intellij

For my case, the issue was with using Lombok's experimental feature @UtilityClass in my java project in Intellij Idea, to annotate a class methods as "static". When I explicitly made each method of the class as "static" instead of using the annotation, all the compilation issues disappeared.

SQL Client for Mac OS X that works with MS SQL Server

I've been using Oracle SQL Developer since the Microsoft software for SQL Server is not currently available on Mac OS X. It works wonders. I would also recommend RazorSQL or SQLGrinder.

How to create the pom.xml for a Java project with Eclipse

Right click on Project -> Add FrameWork Support -> Maven

Array String Declaration

use:

String[] mStrings = new String[title.length];

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Twitter bootstrap modal-backdrop doesn't disappear

updatepanel issue.

My issue was due to the updatepanel placement. I had the entire modal in the updatepanel. If you declare the modal outside the updatepanel and just have say, the modal body, in the update panel, then the $('#myModalID').modal('hide'); worked.

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

node.js require all files in a folder?

Another option is to use the package require-dir which let's you do the following. It supports recursion as well.

var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           
R> 

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

How to insert logo with the title of a HTML page?

Yes you right and I just want to make it understandable for complete beginners.

  1. Create favicon.ico file you want to be shown next to your url in browsers tab. You can do that online. I used http://www.prodraw.net/favicon/generator.php it worked juts fine.
  2. Save generated ico file in your web site root directory /images (yourwebsite/images) under the name favicon.ico.
  3. Copy this tag <link rel="shortcut icon" href="images/favicon.ico" /> and past it without any changes in between <head> opening and </head> closing tag.
  4. Save changes in your html file and reload your browser.

Android device does not show up in adb list

While many of these solutions have worked for me in the past, they all failed me today on a Mac with a Samsung S7. After trying a few cables, someone suggested that the ADB connection requires an official Samsung cable to work. Indeed, when I used the Samsung cable, ADB worked just fine. I hope this helps someone else!

How to populate/instantiate a C# array with a single value?

Well after a little more googling and reading I found this:

bool[] bPrimes = new bool[1000000];
bPrimes = Array.ConvertAll<bool, bool>(bPrimes, b=> b=true);

Which is certainly closer to what I'm looking for. But I'm not sure if that's better than iterating through the original array in a for-loop and just changing the values. After a quick test in fact, it appears slower by about a factor of 5. So not really a good solution then!

Put quotes around a variable string in JavaScript

var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";

Using escape sequence of " (quote), you can achieve this

You can place singe quote (') inside double quotes without any issues Like this

var text = "'http://www.ex.com';'http://www.ex2.com'"

How to deal with a slow SecureRandom generator?

It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.

If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with Dan Dyer's response about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.

I would think that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's eStream project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.

Edit: here's some cryptographic course notes on RNG I found on the 'net that look very relevant to this topic.

Reading an Excel file in python using pandas

This is much simple and easy way.

import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)

check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html

FutureWarning: The sheetname keyword is deprecated for newer Pandas versions, use sheet_name instead.

How can I see an the output of my C programs using Dev-C++?

When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.

PHP function to generate v4 UUID

Having searched for the exact same thing and almost implementing a version of this myself, I thought it was worth mentioning that, if you're doing this within a WordPress framework, WP has its own super-handy function for exactly this:

$myUUID = wp_generate_uuid4();

You can read the description and the source here.

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

Java error: Implicit super constructor is undefined for default constructor

Short answer: Add a constructor with no argument in base/parent/super class. i.e for example,

        class Parent{
    
    String name;
    int age;
    String occupation;
            //empty constructor
            public Parent(){
            
        }
    
    public Parent(String name, int age, String employment){
    this.name = name;
    this.age = age;
    this.occupation = employment;
    }
}

// You can have any additional constructors as you wish aka constructor overloading here in parent class.

If a super class does not have the no-argument constructor then you will get the compile-time error. Object does have such the constructor, so if Object is a only super class then there is no problem.

// then let's inherit

    class Child extends Parent{
              Child(String name, int age){
this.name = name;
this.age = age;
    }
    
    }

With super(), a super class no-argument constructor is called and with super(parameter list), a super class constructor with the matching parameter list is called.

node.js shell command execution

I used this more concisely :

var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);

it works perfectly. :)

How to sum all column values in multi-dimensional array?

Another version, with some benefits below.

$sum = ArrayHelper::copyKeys($arr[0]);

foreach ($arr as $item) {
    ArrayHelper::addArrays($sum, $item);
}


class ArrayHelper {

    public function addArrays(Array &$to, Array $from) {
        foreach ($from as $key=>$value) {
            $to[$key] += $value;
        }
    }

    public function copyKeys(Array $from, $init=0) {
        return array_fill_keys(array_keys($from), $init);
    }

}

I wanted to combine the best of Gumbo's, Graviton's, and Chris J's answer with the following goals so I could use this in my app:

a) Initialize the 'sum' array keys outside of the loop (Gumbo). Should help with performance on very large arrays (not tested yet!). Eliminates notices.

b) Main logic is easy to understand without hitting the manuals. (Graviton, Chris J).

c) Solve the more general problem of adding the values of any two arrays with the same keys and make it less dependent on the sub-array structure.

Unlike Gumbo's solution, you could reuse this in cases where the values are not in sub arrays. Imagine in the example below that $arr1 and $arr2 are not hard-coded, but are being returned as the result of calling a function inside a loop.

$arr1 = array(
    'gozhi' => 2,
    'uzorong' => 1,
    'ngangla' => 4,
    'langthel' => 5
);

$arr2 = array(
   'gozhi' => 5,
   'uzorong' => 0,
   'ngangla' => 3,
   'langthel' => 2
);

$sum = ArrayHelper::copyKeys($arr1);

ArrayHelper::addArrays($sum, $arr1);
ArrayHelper::addArrays($sum, $arr2);

How do I set the figure title and axes labels font size in Matplotlib?

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m
    
def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()

Return a string method in C#

You forgot the () at the end. It is not a variable, but a function and when there are not parameters, you still need the () at the end.

For future coding practices, I would highly recommend reforming the code a little bit as this can become frustrating to read:

 public string LastName
 { get { return lastName; } set { lastName = value; } }

If there is any kind of processing which happens in here (thankfully doesn't happen here), it will become very confusing. If you're going to pass your code onto someone else, I would recommend:

public string LastName
{
  get
  {
     return lastName;
  }
  set
  {
     lastName = value;
  }
}

It's a lot longer, but it's much easier to read when glancing at a huge section of code.

Callback when DOM is loaded in react.js

The below is what I came up with to wait for when the DOM is ready before trying to get a class using document.getElementsByClassName. I called this function from the componentDidMount() lifecycle method.

     changeIcon() {
            if (
                document.getElementsByClassName('YOURCLASSNAME')
                    .length > 0 &&
                document.getElementsByClassName('YOURCLASSNAME').length > 0
            ) {
                document.getElementsByClassName(
                    'YOURCLASSNAME'
                )[0].className = 'YOUR-NEW-CLASSNAME';
                document.getElementsByClassName(
                    'YOUR-OTHER-EXISTING-CLASSNAME'
                )[0].style.display = 'block';
            } else {
                setTimeout(this.changeIcon, 500);
            }
     }

SQL Server error on update command - "A severe error occurred on the current command"

In my case,I was using SubQuery and had a same problem. I realized that the problem is from memory leakage.

Restarting MSSQL service cause to flush tempDb resource and free huge amount of memory. so this was solve the problem.

How do I move an existing Git submodule within a Git repository?

Note: As mentioned in the comments this answer refers to the steps needed with older versions of git. Git now has native support for moving submodules:

Since git 1.8.5, git mv old/submod new/submod works as expected and does all the plumbing for you. You might want to use git 1.9.3 or newer, because it includes fixes for submodule moving.


The process is similar to how you'd remove a submodule (see How do I remove a submodule?):

  1. Edit .gitmodules and change the path of the submodule appropriately, and put it in the index with git add .gitmodules.
  2. If needed, create the parent directory of the new location of the submodule (mkdir -p new/parent).
  3. Move all content from the old to the new directory (mv -vi old/parent/submodule new/parent/submodule).
  4. Make sure Git tracks this directory (git add new/parent).
  5. Remove the old directory with git rm --cached old/parent/submodule.
  6. Move the directory .git/modules/old/parent/submodule with all its content to .git/modules/new/parent/submodule.
  7. Edit the .git/modules/new/parent/config file, make sure that worktree item points to the new locations, so in this example it should be worktree = ../../../../../new/parent/module. Typically there should be two more .. than directories in the direct path in that place.
  8. Edit the file new/parent/module/.git, make sure that the path in it points to the correct new location inside the main project .git folder, so in this example gitdir: ../../../.git/modules/new/parent/submodule.

    git status output looks like this for me afterwards:

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #       modified:   .gitmodules
    #       renamed:    old/parent/submodule -> new/parent/submodule
    #
    
  9. Finally, commit the changes.

Convert string to Boolean in javascript

Depends on what you see as false in a string.

Empty string, the word false, 0, should all those be false or is only empty false or only the word false.

You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.

Write a file in external storage in Android

To write into external storage in Lollipop+ devices we need:

  1. Add the following permission into Manifest:

           <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
  2. Request an approval from the user:

           public static final int REQUEST_WRITE_STORAGE = 112; 
    
           private requestPermission(Activity context) {
               boolean hasPermission = (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
               if (!hasPermission) {
                  ActivityCompat.requestPermissions(context,
                     new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                   REQUEST_WRITE_STORAGE);
               } else {
                 // You are allowed to write external storage:
                 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/new_folder";
                 File storageDir = new File(path);
                 if (!storageDir.exists() && !storageDir.mkdirs()) {
                   // This should never happen - log handled exception!
                 }
               }
    
  3. Handle the user response inside Activity:

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
         switch (requestCode)
         {
          case Preferences.REQUEST_WRITE_STORAGE: {
             if (grantResults.length > 0 && grantResults[0] ==  PackageManager.PERMISSION_GRANTED) {
               Toast.makeText(this, "The app was allowed to write to your storage!", Toast.LENGTH_LONG).show();
               // Reload the activity with permission granted or use the features what required the permission
             } else {
               Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
         }
     }
    

Merge DLL into EXE?

Download

ILMerge

Call

ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

How does `scp` differ from `rsync`?

it's better to think in a practical context. In our team, we use rsync -aP to replace a bad cassandra host in our cluster. We can't do this with scp (slow and no progress preservation).

Strip off URL parameter with PHP

This should do it:

public function removeQueryParam(string $url, string $param): string
{
    $parsedUrl = parse_url($url);

    if (isset($parsedUrl[$param])) {
        $baseUrl = strtok($url, '?');
        parse_str(parse_url($url)['query'], $query);
        unset($query[$param]);
        return sprintf('%s?%s',
            $baseUrl,
            http_build_query($query)
        );
    }

    return $url;
}

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

How to grep recursively, but only in files with certain extensions?

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

that should do what you want.

To take the explanation from HoldOffHunger's answer below:

  • grep: command

  • -r: recursively

  • -i: ignore-case

  • -n: each output line is preceded by its relative line number in the file

  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

  • ./: Start at current directory.

how to change the dist-folder path in angular-cli after 'ng build'

You can update the output folder in .angular-cli.json:

"outDir": "./location/toYour/dist"

Check if datetime instance falls in between other two datetime objects

Do simple compare > and <.

if (dateA>dateB && dateA<dateC)
    //do something

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something

Android: Clear the back stack

In manifest

android:launchMode="singleTask"

and

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:

ENV MY_ENV_VAR $MY_ENV_VAR

I guess there might be a problem with some special characters, but this works for most cases at least.

Convert JSON array to an HTML table in jQuery

You could use a jQuery plugin that accepts JSON data to fill a table. jsonTable

Setting the User-Agent header for a WebClient request

As a supplement to the other answers, here is Microsoft's guidance for user agent strings for its browsers. The user agent strings differ by browser (Internet Explorer and Edge) and operating system (Windows 7, 8, 10 and Windows Phone).

For example, here is the user agent string for Internet Explorer 11 on Windows 10:

Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko 

and for Internet Explorer for Windows Phone 8.1 Update:

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

Templates are given for the user agent strings for the Edge browser for Desktop, Mobile and WebView. See this answer for some Edge user agent string examples.

Finally, another page on MSDN provides guidance for IE11 on older desktop operating systems.

IE11 on Windows 8.1:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

and IE11 on Windows 7:

Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

gitbash command quick reference

Git command Quick Reference

git [command] -help

Git command Manual Pages

git help [command]
git [command] --help

Autocomplete

git <tab>

Cheat Sheets

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]