Programs & Examples On #Web parts

A Web Part, also called a Web Widget, is an ASP.NET server control which is added to a Web Part Zone on Web Part Pages by users at run time. The controls enable end users to modify the content, appearance, and behavior of Web pages directly from a browser. It can be put into certain places in a web page by end users, after developing by programmer.

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

JPA eager fetch does not join

If you use EclipseLink instead of Hibernate you can optimize your queries by "query hints". See this article from the Eclipse Wiki: EclipseLink/Examples/JPA/QueryOptimization.

There is a chapter about "Joined Reading".

How to change UINavigationBar background color from the AppDelegate

You can use [[UINavigationBar appearance] setTintColor:myColor];

Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor]; and also [[UINavigationBar appearance] setTranslucent:NO].

[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];

Collection was modified; enumeration operation may not execute in ArrayList

One way is to add the item(s) to be deleted to a new list. Then go through and delete those items.

Why does the arrow (->) operator in C exist?

Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:

(*(*(*a).b).c).d

a->b->c->d

But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.

AngularJS ng-repeat handle empty list case

i usually use ng-show

<li ng-show="variable.length"></li>

where variable you define for example

<div class="list-group-item" ng-repeat="product in store.products">
   <li ng-show="product.length">show something</li>
</div>

no default constructor exists for class

You declared the constructor blowfish as this:

Blowfish(BlowfishAlgorithm algorithm);

So this line cannot exist (without further initialization later):

Blowfish _blowfish;

since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.

How to get text from each cell of an HTML table?

$content = '';
    for($rowth=0; $rowth<=100; $rowth++){
        $content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
        //$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
        $content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";

    }

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

How can I enable MySQL's slow query log without restarting MySQL?

Try SET GLOBAL slow_query_log = 'ON'; and perhaps FLUSH LOGS;

This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.

String Concatenation in EL

With EL 2 you can do the following:

#{'this'.concat(' is').concat(' a').concat(' test!')}

I have created a table in hive, I would like to know which directory my table is created in?

If you use Hue, you can browse the table in the Metastore App and then click on 'View file location': that will open the HDFS File Browser in its directory.

iterating and filtering two lists using java 8

this can be achieved using below...

 List<String> unavailable = list1.stream()
                            .filter(e -> !list2.contains(e))
                            .collect(Collectors.toList());

How can I make a menubar fixed on the top while scrolling

 #header {
        top:0;
        width:100%;
        position:fixed;
        background-color:#FFF;
    }

    #content {
        position:static;
        margin-top:100px;
    }

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

pandas three-way joining multiple dataframes on columns

This can also be done as follows for a list of dataframes df_list:

df = df_list[0]
for df_ in df_list[1:]:
    df = df.merge(df_, on='join_col_name')

or if the dataframes are in a generator object (e.g. to reduce memory consumption):

df = next(df_list)
for df_ in df_list:
    df = df.merge(df_, on='join_col_name')

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).

You can either get around this problem by

  • using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances

  • otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool

  • or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.

The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

How to pass command line arguments to a rake task

You can specify formal arguments in rake by adding symbol arguments to the task call. For example:

require 'rake'

task :my_task, [:arg1, :arg2] do |t, args|
  puts "Args were: #{args} of class #{args.class}"
  puts "arg1 was: '#{args[:arg1]}' of class #{args[:arg1].class}"
  puts "arg2 was: '#{args[:arg2]}' of class #{args[:arg2].class}"
end

task :invoke_my_task do
  Rake.application.invoke_task("my_task[1, 2]")
end

# or if you prefer this syntax...
task :invoke_my_task_2 do
  Rake::Task[:my_task].invoke(3, 4)
end

# a task with prerequisites passes its 
# arguments to it prerequisites
task :with_prerequisite, [:arg1, :arg2] => :my_task #<- name of prerequisite task

# to specify default values, 
# we take advantage of args being a Rake::TaskArguments object
task :with_defaults, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => :default_1, :arg2 => :default_2)
  puts "Args with defaults were: #{args}"
end

Then, from the command line:

> rake my_task[1,false]
Args were: {:arg1=>"1", :arg2=>"false"} of class Rake::TaskArguments
arg1 was: '1' of class String
arg2 was: 'false' of class String

> rake "my_task[1, 2]"
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task_2
Args were: {:arg1=>3, :arg2=>4}

> rake with_prerequisite[5,6]
Args were: {:arg1=>"5", :arg2=>"6"}

> rake with_defaults
Args with defaults were: {:arg1=>:default_1, :arg2=>:default_2}

> rake with_defaults['x','y']
Args with defaults were: {:arg1=>"x", :arg2=>"y"}

As demonstrated in the second example, if you want to use spaces, the quotes around the target name are necessary to keep the shell from splitting up the arguments at the space.

Looking at the code in rake.rb, it appears that rake does not parse task strings to extract arguments for prerequisites, so you can't do task :t1 => "dep[1,2]". The only way to specify different arguments for a prerequisite would be to invoke it explicitly within the dependent task action, as in :invoke_my_task and :invoke_my_task_2.

Note that some shells (like zsh) require you to escape the brackets: rake my_task\['arg1'\]

What does hash do in python?

The hash is used by dictionaries and sets to quickly look up the object. A good starting point is Wikipedia's article on hash tables.

How to convert an ASCII character into an int in C

I agree to Ashot and Cwan, but maybe you like to convert an ascii-cipher like '7' into an int like 7?

Then I recoomend:

char seven = '7';
int i = seven - '0'; 

or, maybe you get a warning,

int i = (int) (seven - '0'); 

corrected after comments, thanks.

Controlling a USB power supply (on/off) with Linux

According to the docs, there were several changes to the USB power management from kernels 2.6.32, which seem to settle in 2.6.38. Now you'll need to wait for the device to become idle, which is governed by the particular device driver. The driver needs to support it, otherwise the device will never reach this state. Unluckily, now the user has no chance to force this. However, if you're lucky and your device can become idle, then to turn this off you need to:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend"
echo "auto" > "/sys/bus/usb/devices/usbX/power/level"

or, for kernels around 2.6.38 and above:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms"
echo "auto" > "/sys/bus/usb/devices/usbX/power/control"

This literally means, go suspend at the moment the device becomes idle.

So unless your fan is something "intelligent" that can be seen as a device and controlled by a driver, you probably won't have much luck on current kernels.

How to call a method defined in an AngularJS directive?

Just use scope.$parent to associate function called to directive function

angular.module('myApp', [])
.controller('MyCtrl',['$scope',function($scope) {

}])
.directive('mydirective',function(){
 function link(scope, el, attr){
   //use scope.$parent to associate the function called to directive function
   scope.$parent.myfunction = function directivefunction(parameter){
     //do something
}
}
return {
        link: link,
        restrict: 'E'   
      };
});

in HTML

<div ng-controller="MyCtrl">
    <mydirective></mydirective>
    <button ng-click="myfunction(parameter)">call()</button>
</div>

Make HTML5 video poster be same size as video itself

I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!

Passing arguments to C# generic new() of templated type

Since nobody bothered to post the 'Reflection' answer (which I personally think is the best answer), here goes:

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       Type classType = typeof(T);
       ConstructorInfo classConstructor = classType.GetConstructor(new Type[] { listItem.GetType() });
       T classInstance = (T)classConstructor.Invoke(new object[] { listItem });

       tabListItems.Add(classInstance);
   } 
   ...
}

Edit: This answer is deprecated due to .NET 3.5's Activator.CreateInstance, however it is still useful in older .NET versions.

Git refusing to merge unrelated histories on rebase

Try the following command:

git pull origin master --allow-unrelated-histories

This should solve your problem.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Uncaught SyntaxError: Unexpected token < On Chrome

The only place it worked for me is when I place the scripts in public folder where my index.html resides and then placing these <script type="text/javascript" src="test/test.js"></script> inside <body> tag.

Does C# have extension properties?

No, they don't exist.

I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.


EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.

Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:

'Conda' is not recognized as internal or external command

I found the solution. Variable value should be C:\Users\dipanwita.neogy\Anaconda3\Scripts

What is output buffering?

Output Buffering for Web Developers, a Beginner’s Guide:

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.

belongs_to through associations

It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.

Is this what you are after?

I would model something like that along these lines:

class User
  has_many :questions
end

class Question
  belongs_to :user
  has_many   :answers
  has_one    :choice, :class_name => "Answer"

  validates_inclusion_of :choice, :in => lambda { answers }
end

class Answer
  belongs_to :question
end

Javascript event handler with parameters

It is an old question but a common one. So let me add this one here.

With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

const event_handler = (event, arg) => console.log(event, arg);
el.addEventListener('click', (event) => event_handler(event, 'An argument'));

If you need to clean up the event listener:

// Let's use use good old function sytax
function event_handler(event, arg) {
  console.log(event, arg);
}

// Assign the listener callback to a variable
var doClick = (event) => event_handler(event, 'An argument'); 

el.addEventListener('click', doClick);

// Do some work...

// Then later in the code, clean up
el.removeEventListener('click', doClick);

Here is crazy one-liner:

// You can replace console.log with some other callback function
el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument'));

More docile version: More appropriate for any sane work.

el.addEventListener('click', (event) => ((arg) => {
  console.log(event, arg);
})('An argument'));

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

How to use log levels in java

Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):

  • ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message"); )

  • WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message"); )

  • INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message"); )

  • DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message"); )

The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).

Why can't I use a list as a dict key in python?

Because lists are mutable, dict keys (and set members) need to be hashable, and hashing mutable objects is a bad idea because hash values should be computed on the basis of instance attributes.

In this answer, I will give some concrete examples, hopefully adding value on top of the existing answers. Every insight applies to the elements of the set datastructure as well.

Example 1: hashing a mutable object where the hash value is based on a mutable characteristic of the object.

>>> class stupidlist(list):
...     def __hash__(self):
...         return len(self)
... 
>>> stupid = stupidlist([1, 2, 3])
>>> d = {stupid: 0}
>>> stupid.append(4)
>>> stupid
[1, 2, 3, 4]
>>> d
{[1, 2, 3, 4]: 0}
>>> stupid in d
False
>>> stupid in d.keys()
False
>>> stupid in list(d.keys())
True

After mutating stupid, it cannot be found in the dict any longer because the hash changed. Only a linear scan over the list of the dict's keys finds stupid.

Example 2: ... but why not just a constant hash value?

>>> class stupidlist2(list):
...     def __hash__(self):
...         return id(self)
... 
>>> stupidA = stupidlist2([1, 2, 3])
>>> stupidB = stupidlist2([1, 2, 3])
>>> 
>>> stupidA == stupidB
True
>>> stupidA in {stupidB: 0}
False

That's not a good idea as well because equal objects should hash identically such that you can find them in a dict or set.

Example 3: ... ok, what about constant hashes across all instances?!

>>> class stupidlist3(list):
...     def __hash__(self):
...         return 1
... 
>>> stupidC = stupidlist3([1, 2, 3])
>>> stupidD = stupidlist3([1, 2, 3])
>>> stupidE = stupidlist3([1, 2, 3, 4])
>>> 
>>> stupidC in {stupidD: 0}
True
>>> stupidC in {stupidE: 0}
False
>>> d = {stupidC: 0}
>>> stupidC.append(5)
>>> stupidC in d
True

Things seem to work as expected, but think about what's happening: when all instances of your class produce the same hash value, you will have a hash collision whenever there are more than two instances as keys in a dict or present in a set.

Finding the right instance with my_dict[key] or key in my_dict (or item in my_set) needs to perform as many equality checks as there are instances of stupidlist3 in the dict's keys (in the worst case). At this point, the purpose of the dictionary - O(1) lookup - is completely defeated. This is demonstrated in the following timings (done with IPython).

Some Timings for Example 3

>>> lists_list = [[i]  for i in range(1000)]
>>> stupidlists_set = {stupidlist3([i]) for i in range(1000)}
>>> tuples_set = {(i,) for i in range(1000)}
>>> l = [999]
>>> s = stupidlist3([999])
>>> t = (999,)
>>> 
>>> %timeit l in lists_list
25.5 µs ± 442 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit s in stupidlists_set
38.5 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit t in tuples_set
77.6 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As you can see, the membership test in our stupidlists_set is even slower than a linear scan over the whole lists_list, while you have the expected super fast lookup time (factor 500) in a set without loads of hash collisions.


TL; DR: you can use tuple(yourlist) as dict keys, because tuples are immutable and hashable.

mysql extract year from date format

try this code:

SELECT DATE_FORMAT(FROM_UNIXTIME(field), '%Y') FROM table

What's the difference between TRUNCATE and DELETE in SQL

Yes, DELETE is slower, TRUNCATE is faster. Why?

DELETE must read the records, check constraints, update the block, update indexes, and generate redo/undo. All of that takes time.

TRUNCATE simply adjusts a pointer in the database for the table (the High Water Mark) and poof! the data is gone.

This is Oracle specific, AFAIK.

How to add elements of a string array to a string array list?

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List<String>

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
    arr[0] = "rohit";
    List<String> newList = Arrays.asList(arr);

    // Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.

    ArrayList<String> updatableList = new ArrayList<String>();

    updatableList.addAll(newList); 

    updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
    System.out.println(updatableList); //Prints [rohit, jain]

Artificially create a connection timeout error

You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

How to Save Console.WriteLine Output to Text File

do you want to write code for that or just use command-line feature 'command redirection' as follows:

app.exe >> output.txt

as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)

EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

Delayed function calls

This will work either on older versions of .NET
Cons: will execute in its own thread

class CancelableDelay
    {
        Thread delayTh;
        Action action;
        int ms;

        public static CancelableDelay StartAfter(int milliseconds, Action action)
        {
            CancelableDelay result = new CancelableDelay() { ms = milliseconds };
            result.action = action;
            result.delayTh = new Thread(result.Delay);
            result.delayTh.Start();
            return result;
        }

        private CancelableDelay() { }

        void Delay()
        {
            try
            {
                Thread.Sleep(ms);
                action.Invoke();
            }
            catch (ThreadAbortException)
            { }
        }

        public void Cancel() => delayTh.Abort();

    }

Usage:

var job = CancelableDelay.StartAfter(1000, () => { WorkAfter1sec(); });  
job.Cancel(); //to cancel the delayed job

Check if an image is loaded (no errors) with jQuery

I tried many different ways and this way is the only one worked for me

//check all images on the page
$('img').each(function(){
    var img = new Image();
    img.onload = function() {
        console.log($(this).attr('src') + ' - done!');
    }
    img.src = $(this).attr('src');
});

You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

Diff files present in two different directories

Here is a script to show differences between files in two folders. It works recursively. Change dir1 and dir2.

(search() { for i in $1/*; do [ -f "$i" ] && (diff "$1/${i##*/}" "$2/${i##*/}" || echo "files: $1/${i##*/}   $2/${i##*/}"); [ -d "$i" ] && search "$1/${i##*/}" "$2/${i##*/}"; done }; search "dir1" "dir2" )

How do I search for names with apostrophe in SQL Server?

SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0 

When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.

While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.

Reference SO post for comparative view.

MySQL JOIN ON vs USING?

Thought I would chip in here with when I have found ON to be more useful than USING. It is when OUTER joins are introduced into queries.

ON benefits from allowing the results set of the table that a query is OUTER joining onto to be restricted while maintaining the OUTER join. Attempting to restrict the results set through specifying a WHERE clause will, effectively, change the OUTER join into an INNER join.

Granted this may be a relative corner case. Worth putting out there though.....

For example:

CREATE TABLE country (
   countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
   country varchar(50) not null,
  UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;

insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");


CREATE TABLE city (
  cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
  countryId int(10) unsigned not null,
  city varchar(50) not null,
  hasAirport boolean not null default true,
  UNIQUE KEY cityUIdx1 (countryId,city),
  CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;


insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);

-- Gah. Left outer join is now effectively an inner join 
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
; 

-- Hooray! I can see Monaco again thanks to 
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
; 

How to remove border of drop down list : CSS

You could simply use:

select {
    border: none;
    outline: none;
    scroll-behavior: smooth;
}

As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.

How to sum columns in a dataTable?

 for (int i=0;i<=dtB.Columns.Count-1;i++)
 {
   array(0, i) = dtB.Compute("SUM([" & dtB.Columns(i).ColumnName & "])", "")                   
 }

Hidden TextArea

<textarea name="hide" style="display:none;"></textarea>

This sets the css display property to none, which prevents the browser from rendering the textarea.

How to wait for async method to complete?

Best Solution to wait AsynMethod till complete the task is

var result = Task.Run(async() => await yourAsyncMethod()).Result;

to_string not declared in scope

you must compile the file with c++11 support

g++ -std=c++0x  -o test example.cpp

How can I display a tooltip on an HTML "option" tag?

Why use a dropdown at all? The only way the user will see your explanatory text is by blindly hovering over one of the options.

I think it would be preferable to use a radio button group, and next to each item, put a tooltip icon indicating additional information, as well as displaying it after selection (like you currently have it).

I realize this doesn't exactly solve your problem, but I don't see the point in struggling with an html element that's notorious for its inflexibility when you could just use one that's better suited in the first place.

How to get IP address of the device from code?

This is a rework of this answer which strips out irrelevant information, adds helpful comments, names variables more clearly, and improves the logic.

Don't forget to include the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

InternetHelper.java:

public class InternetHelper {

    /**
     * Get IP address from first non-localhost interface
     *
     * @param useIPv4 true=return ipv4, false=return ipv6
     * @return address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces =
                    Collections.list(NetworkInterface.getNetworkInterfaces());

            for (NetworkInterface interface_ : interfaces) {

                for (InetAddress inetAddress :
                        Collections.list(interface_.getInetAddresses())) {

                    /* a loopback address would be something like 127.0.0.1 (the device
                       itself). we want to return the first non-loopback address. */
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddr = inetAddress.getHostAddress();
                        boolean isIPv4 = ipAddr.indexOf(':') < 0;

                        if (isIPv4 && !useIPv4) {
                            continue;
                        }
                        if (useIPv4 && !isIPv4) {
                            int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
                            ipAddr = delim < 0 ? ipAddr.toUpperCase() :
                                    ipAddr.substring(0, delim).toUpperCase();
                        }
                        return ipAddr;
                    }
                }

            }
        } catch (Exception ignored) { } // if we can't connect, just return empty string
        return "";
    }

    /**
     * Get IPv4 address from first non-localhost interface
     *
     * @return address or empty string
     */
    public static String getIPAddress() {
        return getIPAddress(true);
    }

}

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

How does one represent the empty char?

It might be useful to assign a null in a string rather than explicitly making some index the null char '\0'. I've used this for testing functions that handle strings ensuring they stay within their appropriate bounds.

With:

char test_src[] = "fuu\0foo";

This creates an array of size 8 with values:

{'f', 'u', 'u', '\0', 'f', 'o', 'o', '\0'}

How to Deep clone in javascript

The JSON.parse(JSON.stringify()) combination to deep copy Javascript objects is an ineffective hack, as it was meant for JSON data. It does not support values of undefined or function () {}, and will simply ignore them (or null them) when "stringifying" (marshalling) the Javascript object into JSON.

A better solution is to use a deep copy function. The function below deep copies objects, and does not require a 3rd party library (jQuery, LoDash, etc).

function copy(aObject) {
  if (!aObject) {
    return aObject;
  }

  let v;
  let bObject = Array.isArray(aObject) ? [] : {};
  for (const k in aObject) {
    v = aObject[k];
    bObject[k] = (typeof v === "object") ? copy(v) : v;
  }

  return bObject;
}

C++ correct way to return pointer to array from function

A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

#include <assert.h>

int main() {
  int a[] = {1, 2, 3, 4, 5}; 

  int* pArr = a;
  int* pFirstElem = &(a[0]);

  assert(a == pArr);
  assert(a == pFirstElem);

  return 0;
}

This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

int* test(int* in, int len) {
    int* out = in;
    return out;
}

That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

#include <iostream>

using namespace std;

int main() {
  int* pArr = 0;
  {
    int a[] = {1, 2, 3, 4, 5};
    pArr = a; // or test(a) if you wish
  }
  // a[] went out of scope here, but pArr holds a pointer to it

  // all bets are off, this can output "1", output 1st chapter
  // of "Romeo and Juliet", crash the program or destroy the
  // universe
  cout << pArr[0] << endl; // WRONG!

  return 0;
}

So if you don't feel competent enough, just use std::vector.

[answer to the updated question]

The correct way to write your test function is either this:

void test(int* a, int* b, int* c, int len) {
  for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
   int a[5] = {...}, b[5] = {...}, c[5] = {};
   test(a, b, c, 5);
   // c now holds the result
}

Or this (using std::vector):

#include <vector>

vector<int> test(const vector<int>& a, const vector<int>& b) {
  vector<int> result(a.size());
  for (int i = 0; i < a.size(); ++i) {
    result[i] = a[i] + b[i];
  }
  return result; // copy will be elided
}

Vertical line using XML drawable

To make a vertical line, just use a rectangle with width of 1dp:

<shape>
    <size
        android:width="1dp"
        android:height="16dp" />
    <solid
        android:color="#c8cdd2" />
</shape>

Don't use stroke, use solid (which is the "fill" color) to specify the color of the line.

How do I specify new lines on Python, when writing on files?

Simplest solution

If you only call print without any arguments, it will output a blank line.

print

You can pipe the output to a file like this (considering your example):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

Not only is it OS-agnostic (without even having to use the os package), it's also more readable than putting \n within strings.

Explanation

The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS's newline character, for eg. \n. So, when you're calling print('hello'), Python is actually printing 'hello' + '\n'. Which means that when you're calling just print without any arguments, it's actually printing '' + '\n', which results in a newline.

Alternative

Use multi-line strings.

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()

Special characters like @ and & in cURL POST data

Try this:

export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

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

I have done a quick test:

import sys

str = e = "a xxxxxxxxxx very xxxxxxxxxx long xxxxxxxxxx string xxxxxxxxxx\n"

for i in range(int(sys.argv[1])):
    str = str + e

and timed it:

mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  8000000
8000000 times

real    0m2.165s
user    0m1.620s
sys     0m0.540s
mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  16000000
16000000 times

real    0m4.360s
user    0m3.480s
sys     0m0.870s

There is apparently an optimisation for the a = a + b case. It does not exhibit O(n^2) time as one might suspect.

So at least in terms of performance, using + is fine.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

(Basically what @user3464070 already said)

For Mac:

cd ~/Library/Android/sdk
# download latest tools
curl -O https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
# overwrite existing tools folder without prompting
unzip -o tools_r25.2.3-macosx.zip
# clean up
rm tools_r25.2.3-macosx.zip

Responsive iframe using Bootstrap

Working during August 2020

use this

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

use one aspect ratio

<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

within iframe use options

 <iframe class="embed-responsive-item" src="..."
  frameborder="0"
    style="
      overflow: hidden;
      overflow-x: hidden;
      overflow-y: hidden;
      height: 100%;
      width: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
    "
    height="100%"
    width="100%"
  ></iframe>

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

Find out free space on tablespace

There are many ways to check the size, but as a developer we dont have much access to query meta tables, I find this solution very easy (Note: if you are getting error message ORA-01653 ‘The ORA-01653 error is caused because you need to add space to a tablespace.’)

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

Thanks

How to delete cookies on an ASP.NET website

You have to set the expiration date to delete cookies

Request.Cookies[yourCookie]?.Expires.Equals(DateTime.Now.AddYears(-1));

This won't throw an exception if the cookie doesn't exist.

Shell Script Syntax Error: Unexpected End of File

Helpful post, I found that my error was using else if instead of elif like so:

if [ -z "$VARIABLE1" ]; then
    # do stuff
else if [ -z "$VARIABLE2" ]; then
    # do other stuff
fi

Fixed it by changing to this:

if [ -z "$VARIABLE1" ]; then
    # do stuff
elif [ -z "$VARIABLE2" ]; then
    # do other stuff
fi

How do I check if string contains substring?

ECMAScript 6 introduces String.prototype.includes, previously named contains.

It can be used like this:

'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false

It also accepts an optional second argument which specifies the position at which to begin searching:

'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true

It can be polyfilled to make it work on old browsers.

How to know if an object has an attribute in Python

Hope you expecting hasattr(), but try to avoid hasattr() and please prefer getattr(). getattr() is faster than hasattr()

using hasattr():

 if hasattr(a, 'property'):
     print a.property

same here i am using getattr to get property if there is no property it return none

   property = getattr(a,"property",None)
    if property:
        print property

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

I am not for throwing Exceptions in the constructor since I am considering this as non-clean. There are several reasons for my opinion.

  1. As Richard mentioned you cannot initialize an instance in an easy manner. Especially in tests it is really annoying to build a test-wide object only by surrounding it in a try-catch during initialization.

  2. Constructors should be logic-free. There is no reason at all to encapsulate logic in a constructor, since you are always aiming for the Separation of Concerns and Single Responsibility Principle. Since the concern of the constructor is to "construct an object" it should not encapsulate any exception handling if following this approach.

  3. It smells like bad design. Imho if I am forced to do exception handling in the constructor I am at first asking myself if I have any design frauds in my class. It is necessary sometimes, but then I outsource this to a builder or factory to keep the constructor as simple as possible.

So if it is necessary to do some exception handling in the constructor, why would you not outsource this logic to a Builder of Factory? It might be a few more lines of code but gives you the freedom to implement a far more robust and well suited exception handling since you can outsource the logic for the exception handling even more and are not sticked to the constructor, which will encapsulate too much logic. And the client does not need to know anything about your constructing logic if you delegate the exception handling properly.

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE

Align image in center and middle within div

Daaawx's answer works, but I think it would be cleaner if we eliminate the inline css.

_x000D_
_x000D_
body {_x000D_
 margin: 0;_x000D_
}_x000D_
_x000D_
#over img {_x000D_
 margin-left: auto;_x000D_
 margin-right: auto;_x000D_
 display: block;_x000D_
}_x000D_
div.example {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="example" id="over">_x000D_
 <img src="http://www.garcard.com/images/garcard_symbol.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

'module' has no attribute 'urlencode'

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

How to find the php.ini file used by the command line?

Somtimes things aren't always as they seem when in comes to config files in general. So here I'm applying my usual methods for exploring what files are opened by a process.

I use a very powerful and useful command-line program called strace to show me what's really going on behind my back!

$ strace -o strace.log php --version
$ grep php.ini strace.log

Strace digs out kernel (system) calls that your program makes and dumps the output into the file specified by -o

It's easy to use grep to search for occurrences of php.ini in this log. It's pretty obvious looking at the following typical response to see what is going on.

open("/usr/bin/php.ini", O_RDONLY)      = -1 ENOENT (No such file or directory)
open("/etc/php.ini", O_RDONLY)          = 3
lstat("/etc/php.ini", {st_mode=S_IFREG|0644, st_size=69105, ...}) = 0

Only variables should be passed by reference

PHP offical Manual : end()

Parameters

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

ArrayList: how does the size increase?

(oldSize * 3)/2 + 1

If you are using default constructor then initial size of ArrayList will be 10 else you can pass the initial size of array while creating the object of ArrayList.

Example: In case default constructor

List<String> list = new ArrayList<>();
list.size()

Example: In case parameterized constructor

List<String> list = new ArrayList<>(5);
list.size()

How to format numbers?

This will get you your comma seperated values as well as add the fixed notation to the end.

    nStr="1000";
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    commaSeperated = x1 + x2 + ".00";
    alert(commaSeperated);

Source

What is the purpose of Node.js module.exports and how do you use it?

There are some default or existing modules in node.js when you download and install node.js like http, sys etc.

Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.

Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.

Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo

Huh, so that's the reason, we do like

exports.additionTwo = function(x)
{return x+2;};

Be careful with the path

Lets say you have created an addition.js module,

exports.additionTwo = function(x){
return x + 2;
};

When you run this on your NODE.JS command prompt:

node
var run = require('addition.js');

This will error out saying

Error: Cannot find module addition.js

This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH

set NODE_PATH = path/to/your/additon.js

Now, this should run successfully without any errors!!

One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:

node
var run = require('./addition.js');

Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.

How to solve a pair of nonlinear equations using Python?

You can use nsolve of sympy, meaning numerical solver.

Example snippet:

from sympy import *

L = 4.11 * 10 ** 5
nu = 1
rho = 0.8175
mu = 2.88 * 10 ** -6
dP = 20000
eps = 4.6 * 10 ** -5

Re, D, f = symbols('Re, D, f')

nsolve((Eq(Re, rho * nu * D / mu),
       Eq(dP, f * L / D * rho * nu ** 2 / 2),
       Eq(1 / sqrt(f), -1.8 * log ( (eps / D / 3.) ** 1.11 + 6.9 / Re))),
      (Re, D, f), (1123, -1231, -1000))

where (1123, -1231, -1000) is the initial vector to find the root. And it gives out:

enter image description here

The imaginary part are very small, both at 10^(-20), so we can consider them zero, which means the roots are all real. Re ~ 13602.938, D ~ 0.047922 and f~0.0057.

Stop a gif animation onload, on mouseover start the activation

A more elegant version of Mark Kramer's would be to do the following:

function animateImg(id, gifSrc){
  var $el = $(id),
    staticSrc = $el.attr('src');
  $el.hover(
    function(){
      $(this).attr("src", gifSrc);
    },
    function(){
      $(this).attr("src", staticSrc);
    });
}

$(document).ready(function(){
  animateImg('#id1', 'gif/gif1.gif');
  animateImg('#id2', 'gif/gif2.gif');
});

Or even better would be to use data attributes:

$(document).ready(function(){
  $('.animated-img').each(function(){
    var $el = $(this),
      staticSrc = $el.attr('src'),
      gifSrc = $el.data('gifSrc');
    $el.hover(
      function(){
        $(this).attr("src", gifSrc);
      },
      function(){
        $(this).attr("src", staticSrc);
      });
  });
});

And the img el would look something like:

<img class="animated-img" src=".../img.jpg" data-gif-src=".../gif.gif" />

Note: This code is untested but should work fine.

function declaration isn't a prototype

In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.

If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.

I suggest removing the extern, it is extraneous and is usually omitted.

CSS3 transition events

If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:

function once = function(object,event,callback){
    var handle={};

    var eventNames=event.split(" ");

    var cbWrapper=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
        callback.apply(this,arguments);
    };

    eventNames.forEach(function(e){
        object.addEventListener(e,cbWrapper,false);
    });

    handle.cancel=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
    };

    return handle;
};

Usage:

var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
   //do something
});

then if you wish to cancel at some point you can still do it with

handler.cancel();

It's good for other event usages as well :)

set gvim font in .vimrc file

When I try:

set guifont=Consolas:h16

I get: Warning: Font "Consolas" reports bad fixed pitch metrics

and the following is work, and don't show the waring.

autocmd vimenter * GuiFont! Consolas:h16

by the way, if you want to use the mouse wheel to control the font-size, then you can add:

function! AdjustFontSize(amount)
    let s:font_size = s:font_size + a:amount
    :execute "GuiFont! Consolas:h" . s:font_size
endfunction

noremap <C-ScrollWheelUp> :call AdjustFontSize(1)<CR>
noremap <C-ScrollWheelDown> :call AdjustFontSize(-1)<CR>

and if you want to pick the font, you can set

set guifont=*

will bring up a font requester, where you can pick the font you want.

enter image description here

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

Angular 2: How to call a function after get a response from subscribe http.post

Update your get_categories() method to return the total (wrapped in an observable):

// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
  return this.http.post( url, body, {headers: headers, withCredentials:true})
    .map(response => response.json());
}

In search_categories(), you can subscribe the observable returned by get_categories() (or you could keep transforming it by chaining more RxJS operators):

// send_categories() is now called after get_categories().
search_categories() {
  this.get_categories(1)
    // The .subscribe() method accepts 3 callbacks
    .subscribe(
      // The 1st callback handles the data emitted by the observable.
      // In your case, it's the JSON data extracted from the response.
      // That's where you'll find your total property.
      (jsonData) => {
        this.send_categories(jsonData.total);
      },
      // The 2nd callback handles errors.
      (err) => console.error(err),
      // The 3rd callback handles the "complete" event.
      () => console.log("observable complete")
    );
}

Note that you only subscribe ONCE, at the end.

Like I said in the comments, the .subscribe() method of any observable accepts 3 callbacks like this:

obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

They must be passed in this order. You don't have to pass all three. Many times only the nextCallback is implemented:

obs.subscribe(nextCallback);

optional parameters in SQL Server stored proc?

2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine

exec getlist 47,1,0

create procedure getlist
   @convId int,
   @SortOrder int,
   @contestantsOnly bit = 0
as

How do I change JPanel inside a JFrame on the fly?

Hope this piece of code give you an idea of changing jPanels inside a JFrame.

public class PanelTest extends JFrame {

        Container contentPane;

        public PanelTest()  {
           super("Changing JPanel inside a JFrame");
           contentPane=getContentPane();
        }

        public void createChangePanel() {
           contentPane.removeAll();
           JPanel newPanel=new JPanel();
           contentPane.add(newPanel);
           System.out.println("new panel created");//for debugging purposes
           validate();
           setVisible(true);
        }
}

How do I run a batch script from within a batch script?

Here is example:

You have a.bat:

@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END

and b.bat called conditionally from a.bat:

@echo off 
echo "This is b.bat"

Android: how do I check if activity is running?

Have you tried..

    if (getActivity() instanceof NameOfYourActivity){
        //Do something
    }

How to open a page in a new window or tab from code-behind

Use:

Target= "_blank" property of anchor tag

How do I remove  from the beginning of a file?

Open the PHP file under question, in Notepad++.

Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.

ffmpeg usage to encode a video to H264 codec format

"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"

The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53

Note that -an defines that audio should be skipped.

C# HttpClient 4.5 multipart/form-data upload

This is an example of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Type need to be specified for each HTTPContent:

Here's my example. Hope it helps:

private static void Upload()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");

        using (var content = new MultipartFormDataContent())
        {
            var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";

            string assetName = Path.GetFileName(path);

            var request = new HTTPBrightCoveRequest()
                {
                    Method = "create_video",
                    Parameters = new Params()
                        {
                            CreateMultipleRenditions = "true",
                            EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                            Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                            Video = new Video()
                                {
                                    Name = assetName,
                                    ReferenceId = Guid.NewGuid().ToString(),
                                    ShortDescription = assetName
                                }
                        }
                };

            //Content-Disposition: form-data; name="json"
            var stringContent = new StringContent(JsonConvert.SerializeObject(request));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
            content.Add(stringContent, "json");

            FileStream fs = File.OpenRead(path);

            var streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
            streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
            content.Add(streamContent, "file", Path.GetFileName(path));

            //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);

            var input = message.Result.Content.ReadAsStringAsync();
            Console.WriteLine(input.Result);
            Console.Read();
        }
    }
}

Bootstrap table without stripe / borders

In my CSS:

.borderless tr td {
    border: none !important;
    padding: 0px !important;
}

In my directive:

<table class='table borderless'>
    <tr class='borderless' ....>

I didn't put the 'borderless' for the td element.

Tested and it worked! All the borders and paddings are completely stripped off.

Export a graph to .eps file with R

Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to setEPS()

cairo_ps("image.eps")
plot(1, 10)
dev.off()

How to make a background 20% transparent on Android

Use a color with an alpha value like #33------, and set it as background of your editText using the XML attribute android:background=" ".

  1. 0% (transparent) -> #00 in hex
  2. 20% -> #33
  3. 50% -> #80
  4. 75% -> #C0
  5. 100% (opaque) -> #FF

255 * 0.2 = 51 ? in hex 33

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

how to select rows based on distinct values of A COLUMN only

use this(assume that your table name is emails):

select * from emails as a 
inner join  
(select EmailAddress, min(Id) as id from emails 
group by EmailAddress ) as b 
on a.EmailAddress = b.EmailAddress 
and a.Id = b.id

hope this help..

What's the difference between unit tests and integration tests?

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.

How to combine GROUP BY and ROW_NUMBER?

Undoubtly this can be simplified but the results match your expectations.

The gist of this is to

  • Calculate the maximum price in a seperate CTE for each t2ID
  • Calculate the total price in a seperate CTE for each t2ID
  • Combine the results of both CTE's

SQL Statement

;WITH MaxPrice AS ( 
    SELECT  t2ID
            , t1ID
    FROM    (       
                SELECT  t2.ID AS t2ID
                        , t1.ID AS t1ID
                        , rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
                FROM    @t1 t1
                        INNER JOIN @relation r ON r.t1ID = t1.ID        
                        INNER JOIN @t2 t2 ON t2.ID = r.t2ID
            ) maxt1
    WHERE   maxt1.rn = 1                            
)
, SumPrice AS (
    SELECT  t2ID = t2.ID
            , Price = SUM(Price)
    FROM    @t1 t1
            INNER JOIN @relation r ON r.t1ID = t1.ID
            INNER JOIN @t2 t2 ON t2.ID = r.t2ID
    GROUP BY
            t2.ID           
)           
SELECT  t2.ID
        , t2.Name
        , t2.Orders
        , mp.t1ID
        , t1.ID
        , t1.Name
        , sp.Price
FROM    @t2 t2
        INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
        INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
        INNER JOIN @t1 t1 ON t1.ID = mp.t1ID

Move cursor to end of file in vim

If you want to paste some clipboard content at the end of the file type:

:$ put +

$ ............ last line
put .......... paste 
+ ............ clipboard

How to get my activity context?

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

I'd suggest reading this article about context to better figure it out what context you need.

class method generates "TypeError: ... got multiple values for keyword argument ..."

Also this can happen in Django if you are using jquery ajax to url that reverses to a function that doesn't contain 'request' parameter

$.ajax({
  url: '{{ url_to_myfunc }}',
});


def myfunc(foo, bar):
    ...

How to echo in PHP, HTML tags

Here I have added code, the way you want line by line.

The .= helps you to echo multiple lines of code.

$html = '<div>';
$html .= '<h3><a href="#">First</a></h3>';
$html .= '<div>Lorem ipsum dolor sit amet.</div>';
$html .= '</div>';
$html .= '<div>';
echo $html;

Equivalent of explode() to work with strings in MySQL

MYSQL has no explode() like function built in. But you can easily add similar function to your DB and then use it from php queries. That function will look like:

CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
       CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
       delim, '');

Usage:

SELECT SPLIT_STRING('apple, pear, melon', ',', 1)

The example above will return apple. I think that it will be impossible to return array in MySQL so you must specify which occurrence to return explicitly in pos. Let me know if you succeed using it.

How to print React component on click of a button?

On 6/19/2017 This worked perfect for me.

import React, { Component } from 'react'

class PrintThisComponent extends Component {
  render() {
    return (
      <div>
        <button onClick={() => window.print()}>PRINT</button>
        <p>Click above button opens print preview with these words on page</p>
      </div>
    )
  }
}

export default PrintThisComponent

Accessing elements of Python dictionary by index

You can't rely on order of dictionaries, but you may try this:

mydict['Apple'].items()[0][0]

If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api

Pandas count(distinct) equivalent

Interestingly enough, very often len(unique()) is a few times (3x-15x) faster than nunique().

Combining (concatenating) date and time into a datetime

The simple solution

SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field

How can I return to a parent activity correctly?

Updated Answer: Up Navigation Design

You have to declare which activity is the appropriate parent for each activity. Doing so allows the system to facilitate navigation patterns such as Up because the system can determine the logical parent activity from the manifest file.

So for that you have to declare your parent Activity in tag Activity with attribute

android:parentActivityName

Like,

<!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.app_name.A" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name=".B"
        android:label="B"
        android:parentActivityName="com.example.app_name.A" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.app_name.A" />
    </activity>

With the parent activity declared this way, you can navigate Up to the appropriate parent like below,

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

So When you call NavUtils.navigateUpFromSameTask(this); this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward as defined by FLAG_ACTIVITY_CLEAR_TOP.

And to display Up button you have to declare setDisplayHomeAsUpEnabled():

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Old Answer: (Without Up Navigation, default Back Navigation)

It happen only if you are starting Activity A again from Activity B.

Using startActivity().

Instead of this from Activity A start Activity B using startActivityForResult() and override onActivtyResult() in Activity A.

Now in Activity B just call finish() on button Up. So now you directed to Activity A's onActivityResult() without creating of Activity A again..

Stopping Excel Macro executution when pressing Esc won't work

I forgot to comment out a line with a MsgBox before executing my macro. Meaning I'd have to click OK over a hundred thousand times. The ESC key was just escaping the message box but not stopping the execution of the macro. Holding the ESC key continuously for a few seconds helped me stop the execution of the code.

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

PHPMailer AddAddress()

You need to call the AddAddress function once for each E-Mail address you want to send to. There are only two arguments for this function: recipient_email_address and recipient_name. The recipient name is optional and will not be used if not present.

$mailer->AddAddress('[email protected]', 'First Name');
$mailer->AddAddress('[email protected]', 'Second Name');
$mailer->AddAddress('[email protected]', 'Third Name');

You could use an array to store the recipients and then use a for loop. I hope it helps.

Cropping an UIImage

- (UIImage *)getSubImage:(CGRect) rect{
    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));

    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();

    return smallImg;
}

C++ Array Of Pointers

If you don't use the STL, then the code looks a lot bit like C.

#include <cstdlib>
#include <new>

template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
    T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
    if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
       // assign things now that there is no exception
    arr = tmp;
    new( &arr[ n ] ) T( obj ); // placement new
    ++ n;
}

T can be any POD type, including pointers.

Note that arr must be allocated by malloc, not new[].

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

C99 stdint.h header and MS Visual Studio

Update: Visual Studio 2010 and Visual C++ 2010 Express both have stdint.h. It can be found in C:\Program Files\Microsoft Visual Studio 10.0\VC\include

Change priorityQueue to max priorityqueue

In Java 8+ you can create a max priority queue via one of these methods:

Method 1:

PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder()); 

Method 2:

PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b - a); 

Method 3:

PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b.compareTo(a)); 

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Bootstrap: align input with button

Take an input float as left. Then take the button and float it right. You can clearfix class when you take more than one to distance.

<input style="width:65%;float:left"class="btn btn-primary" type="text" name="name"> 
<div style="width:8%;float:left">&nbsp;</div>
<button class="btn btn-default" type="button">Go!</button>
<div class="clearfix" style="margin-bottom:10px"> </div>

How to determine if OpenSSL and mod_ssl are installed on Apache2

Enable mod_ssl in httpd.conf and restart the apache. You will see the openssl information in error.log as below

_x000D_
_x000D_
[Fri Mar 23 15:13:38.448268 2018] [mpm_worker:notice] [pid 8891:tid 1] AH00292: Apache/2.4.29 (Unix) OpenSSL/1.0.2n configured -- resuming normal operations_x000D_
[Fri Mar 23 15:13:38.448502 2018] [core:notice] [pid 8891:tid 1] AH00094: Command line: '/opt/apps/apache64/2.4.29/bin/httpd'
_x000D_
_x000D_
_x000D_

How can I create a temp file with a specific extension with .NET?

How about:

Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")

It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.

How to convert XML to java.util.Map and vice versa

XStream!

Updated: I added unmarshal part as requested in comments..

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) {

        Map<String,String> map = new HashMap<String,String>();
        map.put("name","chris");
        map.put("island","faranga");

        XStream magicApi = new XStream();
        magicApi.registerConverter(new MapEntryConverter());
        magicApi.alias("root", Map.class);

        String xml = magicApi.toXML(map);
        System.out.println("Result of tweaked XStream toXml()");
        System.out.println(xml);

        Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
        assert extractedMap.get("name").equals("chris");
        assert extractedMap.get("island").equals("faranga");

    }

    public static class MapEntryConverter implements Converter {

        public boolean canConvert(Class clazz) {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                writer.startNode(entry.getKey().toString());
                Object val = entry.getValue();
                if ( null != val ) {
                    writer.setValue(val.toString());
                }
                writer.endNode();
            }

        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

            Map<String, String> map = new HashMap<String, String>();

            while(reader.hasMoreChildren()) {
                reader.moveDown();

                String key = reader.getNodeName(); // nodeName aka element's name
                String value = reader.getValue();
                map.put(key, value);

                reader.moveUp();
            }

            return map;
        }

    }

}

How to create the most compact mapping n ? isprime(n) up to a limit N?

The fastest algorithm for general prime testing is AKS. The Wikipedia article describes it at lengths and links to the original paper.

If you want to find big numbers, look into primes that have special forms like Mersenne primes.

The algorithm I usually implement (easy to understand and code) is as follows (in Python):

def isprime(n):
    """Returns True if n is prime."""
    if n == 2:
        return True
    if n == 3:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False

    i = 5
    w = 2

    while i * i <= n:
        if n % i == 0:
            return False

        i += w
        w = 6 - w

    return True

It's a variant of the classic O(sqrt(N)) algorithm. It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.

Sometimes, If I really want speed and the range is limited, I implement a pseudo-prime test based on Fermat's little theorem. If I really want more speed (i.e. avoid O(sqrt(N)) algorithm altogether), I precompute the false positives (see Carmichael numbers) and do a binary search. This is by far the fastest test I've ever implemented, the only drawback is that the range is limited.

Javascript to check whether a checkbox is being checked or unchecked

To toggle a checkbox or you can use

element.checked = !element.checked;

so you could use

if (attribute == elementName)
{
    arrChecks[i].checked = !arrChecks[i].checked;
} else {
    arrChecks[i].checked = false;
}

What does "export default" do in JSX?

Export like export default HelloWorld; and import, such as import React from 'react' are part of the ES6 modules system.

A module is a self contained unit that can expose assets to other modules using export, and acquire assets from other modules using import.

In your code:

import React from 'react'; // get the React object from the react module

class HelloWorld extends React.Component {
  render() {
    return <p>Hello, world!</p>;
  }
}

export default HelloWorld; // expose the HelloWorld component to other modules

In ES6 there are two kinds of exports:

Named exports - for example export function func() {} is a named export with the name of func. Named modules can be imported using import { exportName } from 'module';. In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';. There can be multiple named exports in one module.

Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.

A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';.

How to find out when a particular table was created in Oracle?

SELECT created
  FROM dba_objects
 WHERE object_name = <<your table name>>
   AND owner = <<owner of the table>>
   AND object_type = 'TABLE'

will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).

The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well). There are various special cases, however. If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query. If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows. If you build the table with ROWDEPENDENCIES enabled (not the default), you can use

SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
       ora_rowscn last_modified_scn,
       <<other columns>>
  FROM <<your table>>

to get the last modification date and SCN (system change number) for the row. By default, though, without ROWDEPENDENCIES, the SCN is only at the block level. The SCN_TO_TIMESTAMP function also isn't going to be able to map SCN's to timestamps forever.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Command to get time in milliseconds

A Python script like this:

import time
cur_time = int(time.time()*1000)

Why does Oracle not find oci.dll?

if you use 64-bit pc, oracle doesn't compatible with it. Oracle doesn't find oci.dll file in 64-bit.

Therefore, you can try to change oracle home on the top. As a result of that, home path will change.

At least, I solved that error with changing path.

How to get parameters from the URL with JSP

String accountID = request.getParameter("accountID");

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

Convert Data URI to File then append to FormData

make it simple :D

function dataURItoBlob(dataURI,mime) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs

    var byteString = window.atob(dataURI);

    // separate out the mime component


    // write the bytes of the string to an ArrayBuffer
    //var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ia], { type: mime });

    return blob;
}

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current environment (not permanently):

set FOOBAR=

To permanently remove the variable from the user environment (which is the default place setx puts it):

REG delete HKCU\Environment /F /V FOOBAR

If the variable is set in the system environment (e.g. if you originally set it with setx /M), as an administrator run:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

Note: The REG commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.

How to save image in database using C#

You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:

http://www.eggheadcafe.com/articles/20020929.asp

Dilemma: when to use Fragments vs Activities:

Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.

source

How do I convert date/time from 24-hour format to 12-hour AM/PM?

You can use date function to format it by using the code below:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:

function warextract { jar xf $1 $2 && mv $2 $3 }

which you could then call from python like so:

warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/

If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with

warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war

I'll leave that as an excercise to the reader, though.

Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.

Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.

UL list style not applying

I had this problem and it turned out I didn't have any padding on the ul, which was stopping the discs from being visible.

How to print HTML content on click of a button, but not the page?

If you add and remove the innerHTML, all javascript, css and more will be loaded twice, and the events will fire twice (happened to me), is better hide content, using jQuery and css like this:

function printDiv(selector) {
    $('body .site-container').css({display:'none'});
    var content = $(selector).clone();
    $('body .site-container').before(content);
    window.print();
    $(selector).first().remove();
    $('body .site-container').css({display:''});
}

The div "site-container" contain all site, so you can call the function like:

printDiv('.someDiv');

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

Make .gitignore ignore everything except a few files

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

# Ignore everything
*

# But not these files...
!.gitignore
!script.pl
!template.latex
# etc...

# ...even if they are in subdirectories
!*/

# if the files to be tracked are in subdirectories
!*/a/b/file1.txt
!*/a/b/c/*

How to create a foreign key in phpmyadmin

The key must be indexed to apply foreign key constraint. To do that follow the steps.

  1. Open table structure. (2nd tab)
  2. See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
  3. Open relation view and add foreign key constraint.

You will be able to assign DOCTOR_ID as foreign now.

Angular: Can't find Promise, Map, Set and Iterator

Updated as of angular-2.0.0-rc.4

TLDR;

  1. Transpile to es6

    • error goes away (w/ some gotchas).
  2. Transpile to es5

    • install typings
    • install the es6 shim
    • make sure it compiles with your code.
    • error goes away.

For the readers:

Option 1: Transpile to es6 or es2015

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "system",
    "moduleResolution": "node",
     ...
  },
"exclude": [
    "node_modules",
    "jspm_packages"
  ]
}

Keep in mind uglifyjs does not support es6 at the moment. This could affect you making production bundles.

Option 2: Transpile to es5, install typings, and then install the es6-shim:

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
     ...
  },
  "exclude": [
    "node_modules",
    "jspm_packages"
  ]
}

Install typings, then install es6-shim:

npm install typings --saveDev
typings install dt~es6-shim --global --save

If you go this route, you need to make sure that the typescript compiler can find the .d.ts file.

You have two options:

a. Make sure your tsconfig.json is at the same level as the typings folder.

b. Include a reference in your main.ts file where your angular2 application is bootstrapped.

Option A: Make sure your tsconfig.json is at the same level as the typings folder.

Note: DO NOT use the exclude flag to exclude typings folder.

project
|-- src
|-- node_modules
|-- package.json
|-- typings
|-- tsconfig.json

Option B: Reference in main file before bootstrap (Don't do this):

As shown in other answers, this file is no longer included by Angular

main.ts:

/// <reference path="../../typings/globals/es6-shim/index.d.ts" />

Remove all html tags from php string

For my this is best solution.

function strip_tags_content($string) { 
    // ----- remove HTML TAGs ----- 
    $string = preg_replace ('/<[^>]*>/', ' ', $string); 
    // ----- remove control characters ----- 
    $string = str_replace("\r", '', $string);
    $string = str_replace("\n", ' ', $string);
    $string = str_replace("\t", ' ', $string);
    // ----- remove multiple spaces ----- 
    $string = trim(preg_replace('/ {2,}/', ' ', $string));
    return $string; 

}

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

Non greedy (reluctant) regex matching in sed?

Simulating lazy (un-greedy) quantifier in sed

And all other regex flavors!

  1. Finding first occurrence of an expression:

    • POSIX ERE (using -r option)

      Regex:

        (EXPRESSION).*|.
      

      Sed:

        sed -r ?'s/(EXPRESSION).*|./\1/g' # Global `g` modifier should be on
      

      Example (finding first sequence of digits) Live demo:

        $ sed -r 's/([0-9]+).*|./\1/g' <<< 'foo 12 bar 34'
      
        12
      

      How does it work?

      This regex benefits from an alternation |. At each position engine tries to pick the longest match (this is a POSIX standard which is followed by couple of other engines as well) which means it goes with . until a match is found for ([0-9]+).*. But order is important too.

      enter image description here

      Since global flag is set, engine tries to continue matching character by character up to the end of input string or our target. As soon as the first and only capturing group of left side of alternation is matched (EXPRESSION) rest of line is consumed immediately as well .*. We now hold our value in the first capturing group.

    • POSIX BRE

      Regex:

        \(\(\(EXPRESSION\).*\)*.\)*
      

      Sed:

        sed 's/\(\(\(EXPRESSION\).*\)*.\)*/\3/'
      

      Example (finding first sequence of digits):

        $ sed 's/\(\(\([0-9]\{1,\}\).*\)*.\)*/\3/' <<< 'foo 12 bar 34'
      
        12
      

      This one is like ERE version but with no alternation involved. That's all. At each single position engine tries to match a digit.

      enter image description here

      If it is found, other following digits are consumed and captured and the rest of line is matched immediately otherwise since * means more or zero it skips over second capturing group \(\([0-9]\{1,\}\).*\)* and arrives at a dot . to match a single character and this process continues.

  2. Finding first occurrence of a delimited expression:

    This approach will match the very first occurrence of a string that is delimited. We can call it a block of string.

    sed 's/\(END-DELIMITER-EXPRESSION\).*/\1/; \
         s/\(\(START-DELIMITER-EXPRESSION.*\)*.\)*/\1/g'
    

    Input string:

    foobar start block #1 end barfoo start block #2 end
    

    -EDE: end

    -SDE: start

    $ sed 's/\(end\).*/\1/; s/\(\(start.*\)*.\)*/\1/g'
    

    Output:

    start block #1 end
    

    First regex \(end\).* matches and captures first end delimiter end and substitues all match with recent captured characters which is the end delimiter. At this stage our output is: foobar start block #1 end.

    enter image description here

    Then the result is passed to second regex \(\(start.*\)*.\)* that is same as POSIX BRE version above. It matches a single character if start delimiter start is not matched otherwise it matches and captures the start delimiter and matches the rest of characters.

    enter image description here


Directly answering your question

Using approach #2 (delimited expression) you should select two appropriate expressions:

  • EDE: [^:/]\/

  • SDE: http:

Usage:

$ sed 's/\([^:/]\/\).*/\1/g; s/\(\(http:.*\)*.\)*/\1/' <<< 'http://www.suepearson.co.uk/product/174/71/3816/'

Output:

http://www.suepearson.co.uk/

Note: this will not work with identical delimiters.

How to select an element inside "this" in jQuery?

$( this ).find( 'li.target' ).css("border", "3px double red");

or

$( this ).children( 'li.target' ).css("border", "3px double red");

Use children for immediate descendants, or find for deeper elements.

Can CSS detect the number of children an element has?

No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.

:only-child

The :only-child is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1) probably would.

:nth-child

The :nth-child selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:

p:nth-child( n + 8 ){
    /* add styles to make it pretty */
}

Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.

W3 CSS3 Spec on pseudo-classes

EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:

:empty and :not

This styles elements that have no children. Not that useful on its own, but when paired with the :not selector, you can style only the elements that have children:

div:not(:empty) {
    /* We know it has stuff in it! */
}

You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

Checking for empty or null List<string>

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

How to select only the records with the highest date in LINQ

Here is a simple way to do it

var lastPlayerControlCommand = this.ObjectContext.PlayerControlCommands
                                .Where(c => c.PlayerID == player.ID)
                                .OrderByDescending(t=>t.CreationTime)
                                .FirstOrDefault();

Also have a look this great LINQ place - LINQ to SQL Samples

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

cat, grep and cut - translated to python

You need a loop over the lines of a file, you need to learn about string methods

with open(filename,'r') as f:
    for line in f.readlines():
        # python can do regexes, but this is for s fixed string only
        if "something" in line:
            idx1 = line.find('"')
            idx2 = line.find('"', idx1+1)
            field = line[idx1+1:idx2-1]
            print(field)

and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...

For the future, try to ask more focused questions if you can,

AngularJS UI Router - change url without reloading state

Simply you can use $state.transitionTo instead of $state.go . $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true } . You can call $state.transitionTo and set notify: false . For example:

$state.go('.detail', {id: newId}) 

can be replaced by

$state.transitionTo('.detail', {id: newId}, {
    location: true,
    inherit: true,
    relative: $state.$current,
    notify: false
})

Edit: As suggested by fracz it can simply be:

$state.go('.detail', {id: newId}, {notify: false}) 

How to get HTTP Response Code using Selenium WebDriver

You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.

An usage example:

>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'

Making TextView scrollable on Android

The "pro tip" above from Someone Somewhere (Making TextView scrollable on Android) works great, however, what if you're dynamically adding text to the ScrollView and would like to automatically scroll to the bottom after an append only when the user is at the bottom of the ScrollView? (Perhaps because if the user has scrolled up to read something you don't want to automatically reset to the bottom during an append, which would be annoying.)

Anyway, here it is:

if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
        (mScrollView.getHeight() + mTextStatus.getLineHeight())) {
    scrollToBottom();
}

The mTextStatus.getLineHeight() will make it so that you don't scrollToBottom() if the user is within one line from the end of the ScrollView.

How to sort an array of associative arrays by value of a given key in PHP?

This function is re-usable:

function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
    uasort($array, function($a, $b) use($key, $callback) {
        return call_user_func($callback, $a[$key], $b[$key]);
    });
}

It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.

What is the correct way to free memory in C#

  1. Yes
  2. What do you mean by the same? It will be re-executed every time the method is run.
  3. Yes, the .Net garbage collector uses an algorithm that starts with any global/in-scope variables, traverses them while following any reference it finds recursively, and deletes any object in memory deemed to be unreachable. see here for more detail on Garbage Collection
  4. Yes, the memory from all variables declared in a method is released when the method exits as they are all unreachable. In addition, any variables that are declared but never used will be optimized out by the compiler, so in reality your Foo variable will never ever take up memory.
  5. the using statement simply calls dispose on an IDisposable object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.

How to add a button dynamically using jquery

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

RestSharp JSON Parameter Posting

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");

Update React component every second

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
  clearInterval(this.interval);
}

How do I remove blank elements from an array?

another method:

> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

how to set the background image fit to browser using html

body
{
    position: fixed;  /*fixes the image in background*/
    top: 0; /*fixes the image at top*/
    left: 0; /*fixes the image at left*/
    min-width: 100%; /*fixes the image width to 100% of screen*/
    min-height: 100%; /*fixes the image height to 100% of screen*/
}

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

CKEditor instance already exists

For those using the jquery "adapter" and having trouble (as I was), as super hackish yet working solution is to do something like this:

// content editor plugin
(function($){
    $.fn.contentEditor = function( params ) {
        var xParams = $.extend({}, $.fn.contentEditor.defaultParams, params);
        return this.each( function() {   
            var $editor = $(this);
            var $params = $.extend({}, xParams, $editor.data());

            // if identifier is set, detect type based on identifier in $editor
            if( $params.identifier.type ) {
                $params.type = $editor.find($params.identifier.type).val();
            }

            $editor.data('type', $params.type);

            // edit functionality
            editButton = $('<button>Edit Content</button>').on('click',function(){
                // content container
                var $cc = $('#' + $editor.data('type'));

                // editor window
                var $ew = $('<form class="editorWindow" />');
                $ew.appendTo('body');

                // editor content
                $ec = $('<textarea name="editorContent" />').val($cc.html());
                $ec.appendTo($ew);
                $ec.ckeditor();


                //$ec.ckeditorGet().setMode('source');


                $ew.dialog({
                    "autoOpen": true,
                    "modal": true,
                    "draggable": false,
                    "resizable": false,
                    "width": 850,
                    "height": 'auto',
                    "title": "Content Editor",
                    "buttons": { 
                        'Save': function() {                            
                            $cc.html( $ec.val() );
                            $ec.ckeditorGet().destroy(); 
                            $ew.remove();
                        },
                        'Cancel / Close': function() { 

                            $ec.ckeditorGet().destroy();                        
                            $ew.remove();
                        }
                    },
                    'close': function() {
                        $ec.ckeditorGet().destroy(); 
                    },
                    'open': function() {
                        $ew.find('a.cke_button_source').click();

                        setTimeout(function(){
                            $ew.find('a.cke_button_source.cke_on').click();
                        }, 500);
                    }
                });

                return false;
            });

            editButton.appendTo( $editor );

        });
    }

    // set default option values
    $.fn.contentEditor.defaultParams = {
        'identifier': {
            'type': 'input[name="type"]'
        }
    };   

})(jQuery);   

$(function(){

    $('form.contentEditor').contentEditor();

});

The key point being this part:

                'open': function() {
                    $ew.find('a.cke_button_source').click();

                    setTimeout(function(){
                        $ew.find('a.cke_button_source.cke_on').click();
                    }, 500);
                }

This fixes the problem with the editor text not being visible the next time you open the dialog. I realise this is very hackish, but considering that most of these are going to be used for admin tools, I don't think that's as big a concern as it normally would be.. and this works, so hopefully it will save someone some time ;)

Running Python code in Vim

Instead of putting the command mapping in your .vimrc, put the mapping in your ~/.vim/ftplugin/python.vim file (Windows $HOME\vimfiles\ftplugin\python.vim). If you don't have this file or directories, just make them. This way the key is only mapped when you open a .py file or any file with filetype=python, since you'll only be running this command on Python scripts.

For the actual mapping, I like to be able to edit in Vim while the script runs. Going off of @cazyas' answer, I have the following in my ftplugin\python.vim (Windows):

noremap <F5> <Esc>:w<CR>:!START /B python %<CR>

This will run the current Python script in the background. For Linux just change it to this:

noremap <F5> <Esc>:w<CR>:!python % &<CR>

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Get the last three chars from any string - Java

The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.

Try this link for a more verbose description of the getChars method.

I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.

Angular and Typescript: Can't find names - Error: cannot find name

you can add the code at the beginning of .ts files.

/// <reference path="../typings/index.d.ts" />

Twitter Bootstrap onclick event on buttons-radio

I searched so many pages: I found a beautiful solution. Check it out:

git link

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

    <script>
        $(function() {
            $("#my_launch_today_chk").change(function() {
                var chk = $(this).prop('checked');
                if(chk == true){
                    console.log("On");
                }else{
                    console.log("OFF");
                }
            });
        });
    </script>
</head>
<body >

<input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
</body>
</html>

Subtracting time.Duration from time in Go

You can negate a time.Duration:

then := now.Add(- dur)

You can even compare a time.Duration against 0:

if dur > 0 {
    dur = - dur
}

then := now.Add(dur)

You can see a working example at http://play.golang.org/p/ml7svlL4eW

Exception is never thrown in body of corresponding try statement

Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -

data['sex'].replace([0,1],['Female','Male'],inplace=True)

Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
Out[12]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
Out[17]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

How can I calculate the number of years between two dates?

getAge(month, day, year) {
    let yearNow = new Date().getFullYear();
    let monthNow = new Date().getMonth() + 1;
    let dayNow = new Date().getDate();
    if (monthNow === month && dayNow < day || monthNow < month) {
      return yearNow - year - 1;
    } else {
      return yearNow - year;
    }
  }

Origin <origin> is not allowed by Access-Control-Allow-Origin

If you need a quick work around in Chrome for ajax requests, this chrome plugin automatically allows you to access any site from any source by adding the proper response header

Chrome Extension Allow-Control-Allow-Origin: *

Good beginners tutorial to socket.io?

To start with Socket.IO I suggest you read first the example on the main page:

http://socket.io/

On the server side, read the "How to use" on the GitHub source page:

https://github.com/Automattic/socket.io

And on the client side:

https://github.com/Automattic/socket.io-client

Finally you need to read this great tutorial:

http://howtonode.org/websockets-socketio

Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.

How to hide keyboard in swift on pressing return key?

you can put this anywhere but not in a UIButton

 func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
    return (false)
}

then you can put this code in a button(also for example):

self.view.endEditing(true)

this worked for me

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

How to style SVG with external CSS?

One approach you can take is just to use CSS filters to change the appearance of the SVG graphics in the browser.

For example, if you have an SVG graphic that uses a fill color of red within the SVG code, you can turn it purple with a hue-rotate setting of 180 degrees:

#theIdOfTheImgTagWithTheSVGInIt {
    filter: hue-rotate(180deg);
    -webkit-filter: hue-rotate(180deg);
    -moz-filter: hue-rotate(180deg);
    -o-filter: hue-rotate(180deg);
    -ms-filter: hue-rotate(180deg);
}

Experiment with other hue-rotate settings to find the colors you want.

To be clear, the above CSS goes in the CSS that is applied to your HTML document. You are styling the img tag in the HTML code, not styling the code of the SVG.

And note that this won’t work with graphics that have a fill of black or white or gray. You have to have an actual color in there to rotate the hue of that color.

Fatal error: Maximum execution time of 30 seconds exceeded

To extend your max_execution_time you can use either ini_set or set_time_limit.

// Set maximum execution time to 10 seconds this way
ini_set('max_execution_time', 10);
// or this way
set_time_limit(10);

!! But be aware that, both functions restarts also counting of time script has already taken to execute

sleep(2);
ini_set('max_execution_time', 5);

register_shutdown_function(function(){
    var_dump(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']);
});

for(;;);

//
// var_dump outputs float(7.1981489658356)
//

so if you want to set exact maximum amount of time script can run, your command must be very first.

Differences between those two functions are

  • set_time_limit does not return info whether it was successful but it will throw a warning on error.
  • ini_set returns old value on success, or false on failure without any warning/error