How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers
Example template for C++
template< class T >
T mod( T a, T b )
{
T const r = a%b;
return ((r!=0)&&((r^b)<0) ? r + b : r);
}
With this template, the returned remainder will be zero or have the same sign as the divisor (denominator) (the equivalent of rounding towards negative infinity), instead of the C++ behavior of the remainder being zero or having the same sign as the dividend (numerator) (the equivalent of rounding towards zero).
How to filter object array based on attributes?
You should check out OGX.List which has built in filtering methods and extends the standard javascript array (and also grouping, sorting and finding). Here's a list of operators it supports for the filters:
'eq' //Equal to
'eqjson' //For deep objects, JSON comparison, equal to
'neq' //Not equal to
'in' //Contains
'nin' //Doesn't contain
'lt' //Lesser than
'lte' //Lesser or equal to
'gt' //Greater than
'gte' //Greater or equal to
'btw' //Between, expects value to be array [_from_, _to_]
'substr' //Substring mode, equal to, expects value to be array [_from_, _to_, _niddle_]
'regex' //Regex match
You can use it this way
let list = new OGX.List(your_array);
list.addFilter('price', 'btw', 100, 500);
list.addFilter('sqft', 'gte', 500);
let filtered_list = list.filter();
Or even this way
let list = new OGX.List(your_array);
let filtered_list = list.get({price:{btw:[100,500]}, sqft:{gte:500}});
Or as a one liner
let filtered_list = new OGX.List(your_array).get({price:{btw:[100,500]}, sqft:{gte:500}});
A weighted version of random.choice
Another way of doing this, assuming we have weights at the same index as the elements in the element array.
import numpy as np
weights = [0.1, 0.3, 0.5] #weights for the item at index 0,1,2
# sum of weights should be <=1, you can also divide each weight by sum of all weights to standardise it to <=1 constraint.
trials = 1 #number of trials
num_item = 1 #number of items that can be picked in each trial
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# gives number of times an item was selected at a particular index
# this assumes selection with replacement
# one possible output
# selected_item_arr
# array([[0, 0, 1]])
# say if trials = 5, the the possible output could be
# selected_item_arr
# array([[1, 0, 0],
# [0, 0, 1],
# [0, 0, 1],
# [0, 1, 0],
# [0, 0, 1]])
Now let's assume, we have to sample out 3 items in 1 trial. You can assume that there are three balls R,G,B present in large quantity in ratio of their weights given by weight array, the following could be possible outcome:
num_item = 3
trials = 1
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# selected_item_arr can give output like :
# array([[1, 0, 2]])
you can also think number of items to be selected as number of binomial/ multinomial trials within a set. So, the above example can be still work as
num_binomial_trial = 5
weights = [0.1,0.9] #say an unfair coin weights for H/T
num_experiment_set = 1
selected_item_arr = np.random.multinomial(num_binomial_trial, weights, num_experiment_set)
# possible output
# selected_item_arr
# array([[1, 4]])
# i.e H came 1 time and T came 4 times in 5 binomial trials. And one set contains 5 binomial trails.
Getting absolute URLs using ASP.NET Core
After RC2 and 1.0 you no longer need to inject an IHttpContextAccessor
to you extension class. It is immediately available in the IUrlHelper
through the urlhelper.ActionContext.HttpContext.Request
. You would then create an extension class following the same idea, but simpler since there will be no injection involved.
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
string scheme = url.ActionContext.HttpContext.Request.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
Leaving the details on how to build it injecting the accesor in case they are useful to someone. You might also just be interested in the absolute url of the current request, in which case take a look at the end of the answer.
You could modify your extension class to use the IHttpContextAccessor
interface to get the HttpContext
. Once you have the context, then you can get the HttpRequest
instance from HttpContext.Request
and use its properties Scheme
, Host
, Protocol
etc as in:
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
For example, you could require your class to be configured with an HttpContextAccessor:
public static class UrlHelperExtensions
{
private static IHttpContextAccessor HttpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
....
}
Which is something you can do on your Startup
class (Startup.cs file):
public void Configure(IApplicationBuilder app)
{
...
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
UrlHelperExtensions.Configure(httpContextAccessor);
...
}
You could probably come up with different ways of getting the IHttpContextAccessor
in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject the IHttpContextAccessor
into your static class. (Otherwise you will need the IHttpContext
as an argument on each call)
Just getting the absoluteUri of the current request
If you just want to get the absolute uri of the current request, you can use the extension methods GetDisplayUrl
or GetEncodedUrl
from the UriHelper
class. (Which is different from the UrLHelper)
GetDisplayUrl. Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only
for display. This format should not be used in HTTP headers or other
HTTP operations.
GetEncodedUrl. Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other
HTTP operations.
In order to use them:
- Include the namespace
Microsoft.AspNet.Http.Extensions
.
- Get the
HttpContext
instance. It is already available in some classes (like razor views), but in others you might need to inject an IHttpContextAccessor
as explained above.
- Then just use them as in
this.Context.Request.GetDisplayUrl()
An alternative to those methods would be manually crafting yourself the absolute uri using the values in the HttpContext.Request
object (Similar to what the RequireHttpsAttribute does):
var absoluteUri = string.Concat(
request.Scheme,
"://",
request.Host.ToUriComponent(),
request.PathBase.ToUriComponent(),
request.Path.ToUriComponent(),
request.QueryString.ToUriComponent());
ReactJS map through Object
When calling Object.keys
it returns a array of the object's keys.
Object.keys({ test: '', test2: ''}) // ['test', 'test2']
When you call Array#map
the function you pass will give you 2 arguments;
- the item in the array,
- the index of the item.
When you want to get the data, you need to use item
(or in the example below keyName
) instead of i
{Object.keys(subjects).map((keyName, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[keyName]}</span>
</li>
))}
jQuery creating objects
I actually found a better way using the jQuery approach
var box = {
config:{
color: 'red'
},
init:function(config){
$.extend(this.config,config);
}
};
var myBox = box.init({
color: blue
});
How to check if input is numeric in C++
I find myself using boost::lexical_cast
for this sort of thing all the time these days.
Example:
std::string input;
std::getline(std::cin,input);
int input_value;
try {
input_value=boost::lexical_cast<int>(input));
} catch(boost::bad_lexical_cast &) {
// Deal with bad input here
}
The pattern works just as well for your own classes too, provided they meet some simple requirements (streamability in the necessary direction, and default and copy constructors).
HTML/CSS: how to put text both right and left aligned in a paragraph
If the texts has different sizes and they must be underlined this is the solution:
<table>
<tr>
<td class='left'>January</td>
<td class='right'>2014</td>
</tr>
</table>
css:
table{
width: 100%;
border-bottom: 2px solid black;
/*this is the size of the small text's baseline over part (˜25px*3/4)*/
line-height: 19.5px;
}
table td{
vertical-align: baseline;
}
.left{
font-family: Arial;
font-size: 40px;
text-align: left;
}
.right{
font-size: 25px;
text-align: right;
}
demo here
How to extract code of .apk file which is not working?
Any .apk file from market or unsigned
If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card .
Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.
Download Dex2Jar zip from this link: SourceForge
Unzip the downloaded zip file.
Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.
dex2jar targetapp.apk file
(./dex2jar app.apk on terminal)
http://jd.benow.ca/ download decompiler from this link.
Open ‘targetapp.apk.dex2jar.jar’ with jd-gui
File > Save All Sources to sava the class files in jar to java files.
CentOS 7 and Puppet unable to install nc
Nc is a link to nmap-ncat.
It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.
Puppet cannot understand the links/virtualnames
your puppet should be:
package {
'nmap-ncat':
ensure => installed;
}
How could I use requests in asyncio?
Requests does not currently support asyncio
and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio
.
If I find myself with some time it's something I might actually look into, but I can't promise anything.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How to draw a rounded Rectangle on HTML Canvas?
To make the function more consistent with the normal means of using a canvas context, the canvas context class can be extended to include a 'fillRoundedRect
' method -- that can be called in the same way fillRect
is called:
var canv = document.createElement("canvas");
var cctx = canv.getContext("2d");
// If thie canvasContext class doesn't have a fillRoundedRect, extend it now
if (!cctx.constructor.prototype.fillRoundedRect) {
// Extend the canvaseContext class with a fillRoundedRect method
cctx.constructor.prototype.fillRoundedRect =
function (xx,yy, ww,hh, rad, fill, stroke) {
if (typeof(rad) == "undefined") rad = 5;
this.beginPath();
this.moveTo(xx+rad, yy);
this.arcTo(xx+ww, yy, xx+ww, yy+hh, rad);
this.arcTo(xx+ww, yy+hh, xx, yy+hh, rad);
this.arcTo(xx, yy+hh, xx, yy, rad);
this.arcTo(xx, yy, xx+ww, yy, rad);
if (stroke) this.stroke(); // Default to no stroke
if (fill || typeof(fill)=="undefined") this.fill(); // Default to fill
}; // end of fillRoundedRect method
}
The code checks to see if the prototype for the constructor for the canvas context object contains a 'fillRoundedRect
' property and adds one -- the first time around. It is invoked in the same manner as the fillRect
method:
ctx.fillStyle = "#eef"; ctx.strokeStyle = "#ddf";
// ctx.fillRect(10,10, 200,100);
ctx.fillRoundedRect(10,10, 200,100, 5);
The method uses the arcTo
method as Grumdring did. In the method, this
is a reference to the ctx
object. The stroke argument defaults to false if undefined. The fill argument defaults to fill the rectangle if undefined.
(Tested on Firefox, I don't know if all implementations permit extension in this manner.)
Drawing rotated text on a HTML5 canvas
Funkodebat posted a great solution which I have referenced many times.
Still, I find myself writing my own working model each time I need this.
So, here is my working model... with some added clarity.
First of all, the height of the text is equal to the pixel font size.
Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.
Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.
You will see in the code that we are rotating the text about its center.
To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.
Why resize the canvas?
I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display.
For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);
).
IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.
Hope this helps!
_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_
How to execute .sql script file using JDBC
I use this bit of code to import sql statements created by mysqldump:
public static void importSQL(Connection conn, InputStream in) throws SQLException
{
Scanner s = new Scanner(in);
s.useDelimiter("(;(\r)?\n)|(--\n)");
Statement st = null;
try
{
st = conn.createStatement();
while (s.hasNext())
{
String line = s.next();
if (line.startsWith("/*!") && line.endsWith("*/"))
{
int i = line.indexOf(' ');
line = line.substring(i + 1, line.length() - " */".length());
}
if (line.trim().length() > 0)
{
st.execute(line);
}
}
}
finally
{
if (st != null) st.close();
}
}
How can I list all foreign keys referencing a given table in SQL Server?
I'd use the Database Diagramming feature in SQL Server Management Studio, but since you ruled that out - this worked for me in SQL Server 2008 (don't have 2005).
To get list of referring table and column names...
select
t.name as TableWithForeignKey,
fk.constraint_column_id as FK_PartNo, c.
name as ForeignKeyColumn
from
sys.foreign_key_columns as fk
inner join
sys.tables as t on fk.parent_object_id = t.object_id
inner join
sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
fk.referenced_object_id = (select object_id
from sys.tables
where name = 'TableOthersForeignKeyInto')
order by
TableWithForeignKey, FK_PartNo
To get names of foreign key constraints
select distinct name from sys.objects where object_id in
( select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
)
How to adjust text font size to fit textview
In my case using app:autoSize
was not solving all cases, for example it doesn't prevent word breaking
This is what I ended up using, it will resize down the text so that there are no word breaks on multiple lines
/**
* Resizes down the text size so that there are no word breaks
*/
class AutoFitTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private val paint = Paint()
private val bounds = Rect()
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var shouldResize = false
paint.typeface = typeface
var textSize = textSize
paint.textSize = textSize
val biggestWord: String = text.split(" ").maxByOrNull { it.count() } ?: return
// Set bounds equal to the biggest word bounds
paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)
// Iterate to reduce the text size so that it makes the biggest word fit the line
while ((bounds.width() + paddingStart + paddingEnd + paint.fontSpacing) > measuredWidth) {
textSize--
paint.textSize = textSize
paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)
shouldResize = true
}
if (shouldResize) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
}
}
}
What are the different types of indexes, what are the benefits of each?
PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:
create index i on customers (id, name, whatever) where is_active is true;
If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:
select name from customers where is_active is true;
What is the difference between "INNER JOIN" and "OUTER JOIN"?
The Venn diagrams don't really do it for me.
They don't show any distinction between a cross join and an inner join, for example, or more generally show any distinction between different types of join predicate or provide a framework for reasoning about how they will operate.
There is no substitute for understanding the logical processing and it is relatively straightforward to grasp anyway.
- Imagine a cross join.
- Evaluate the
on
clause against all rows from step 1 keeping those where the predicate evaluates to true
- (For outer joins only) add back in any outer rows that were lost in step 2.
(NB: In practice the query optimiser may find more efficient ways of executing the query than the purely logical description above but the final result must be the same)
I'll start off with an animated version of a full outer join. Further explanation follows.
Explanation
Source Tables
First start with a CROSS JOIN
(AKA Cartesian Product). This does not have an ON
clause and simply returns every combination of rows from the two tables.
SELECT A.Colour, B.Colour FROM A CROSS JOIN B
Inner and Outer joins have an "ON" clause predicate.
- Inner Join. Evaluate the condition in the "ON" clause for all rows in the cross join result. If true return the joined row. Otherwise discard it.
- Left Outer Join. Same as inner join then for any rows in the left table that did not match anything output these with NULL values for the right table columns.
- Right Outer Join. Same as inner join then for any rows in the right table that did not match anything output these with NULL values for the left table columns.
- Full Outer Join. Same as inner join then preserve left non matched rows as in left outer join and right non matching rows as per right outer join.
Some examples
SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour
The above is the classic equi join.
Animated Version
SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour NOT IN ('Green','Blue')
The inner join condition need not necessarily be an equality condition and it need not reference columns from both (or even either) of the tables. Evaluating A.Colour NOT IN ('Green','Blue')
on each row of the cross join returns.
SELECT A.Colour, B.Colour FROM A INNER JOIN B ON 1 =1
The join condition evaluates to true for all rows in the cross join result so this is just the same as a cross join. I won't repeat the picture of the 16 rows again.
SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour
Outer Joins are logically evaluated in the same way as inner joins except that if a row from the left table (for a left join) does not join with any rows from the right hand table at all it is preserved in the result with NULL
values for the right hand columns.
SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour IS NULL
This simply restricts the previous result to only return the rows where B.Colour IS NULL
. In this particular case these will be the rows that were preserved as they had no match in the right hand table and the query returns the single red row not matched in table B
. This is known as an anti semi join.
It is important to select a column for the IS NULL
test that is either not nullable or for which the join condition ensures that any NULL
values will be excluded in order for this pattern to work correctly and avoid just bringing back rows which happen to have a NULL
value for that column in addition to the un matched rows.
SELECT A.Colour, B.Colour FROM A RIGHT OUTER JOIN B ON A.Colour = B.Colour
Right outer joins act similarly to left outer joins except they preserve non matching rows from the right table and null extend the left hand columns.
SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON A.Colour = B.Colour
Full outer joins combine the behaviour of left and right joins and preserve the non matching rows from both the left and the right tables.
SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON 1 = 0
No rows in the cross join match the 1=0
predicate. All rows from both sides are preserved using normal outer join rules with NULL in the columns from the table on the other side.
SELECT COALESCE(A.Colour, B.Colour) AS Colour FROM A FULL OUTER JOIN B ON 1 = 0
With a minor amend to the preceding query one could simulate a UNION ALL
of the two tables.
SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour = 'Green'
Note that the WHERE
clause (if present) logically runs after the join. One common error is to perform a left outer join and then include a WHERE clause with a condition on the right table that ends up excluding the non matching rows. The above ends up performing the outer join...
... And then the "Where" clause runs. NULL= 'Green'
does not evaluate to true so the row preserved by the outer join ends up discarded (along with the blue one) effectively converting the join back to an inner one.
If the intention was to include only rows from B where Colour is Green and all rows from A regardless the correct syntax would be
SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour AND B.Colour = 'Green'
SQL Fiddle
See these examples run live at SQLFiddle.com.
Deleting specific rows from DataTable
I have a dataset in my app and I went to set changes (deleting a row) to it but ds.tabales["TableName"]
is read only. Then I found this solution.
It's a wpf C#
app,
try {
var results = from row in ds.Tables["TableName"].AsEnumerable() where row.Field<string>("Personalid") == "47" select row;
foreach (DataRow row in results) {
ds.Tables["TableName"].Rows.Remove(row);
}
}
What is the $$hashKey added to my JSON.stringify result
https://www.timcosta.io/angular-js-object-comparisons/
Angular is pretty magical the first time people see it. Automatic DOM updates when you update a variable in your JS, and the same variable will update in your JS file when someone updates its value in the DOM. This same functionality works across page elements, and across controllers.
The key to all of this is the $$hashKey Angular attaches to objects and arrays used in ng-repeats.
This $$hashKey causes a lot of confusion for people who are sending full objects to an API that doesn't strip extra data. The API will return a 400 for all of your requests, but that $$hashKey just wont go away from your objects.
Angular uses the $$hashKey to keep track of which elements in the DOM belong to which item in an array that is being looped through in an ng-repeat. Without the $$hashKey Angular would have no way to apply changes the occur in the JavaScript or DOM to their counterpart, which is one of the main uses for Angular.
Consider this array:
users = [
{
first_name: "Tim"
last_name: "Costa"
email: "[email protected]"
}
]
If we rendered that into a list using ng-repeat="user in users", each object in it would receive a $$hashKey for tracking purposes from Angular. Here are two ways to avoid this $$hashKey.
PHP Array to CSV
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
how to write unified new line in PHP?
Unique constraint on multiple columns
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
- Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...
- A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button
- Check the columns you want included
Click OK in each window and you're done.
jQuery: Scroll down page a set increment (in pixels) on click?
Just check this:
$(document).ready(function() {
$(".scroll").click(function(event){
$('html, body').animate({scrollTop: '+=150px'}, 800);
});
});
It will make scroller scroll from current position when your element is clicked
And 150px is used to scroll for 150px downwards
Bootstrap Modal Backdrop Remaining
After inspecting the element, the div
with the modal-backdrop
class still remains after I hit the browser back button, so I simply remove it:
$(window).on('popstate', function() {
$(".modal-backdrop").remove();
});
How to read file binary in C#?
Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:
using System;
using System.IO;
using System.Text;
class Program {
static void Main(string[] args) {
// Read the file into <bits>
var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 16 bytes per line
for (int ix = 0; ix < len; ix += 16) {
var cnt = Math.Min(16, len - ix);
var line = new byte[cnt];
Array.Copy(bits, ix, line, 0, cnt);
// Write address + hex + ascii
Console.Write("{0:X6} ", ix);
Console.Write(BitConverter.ToString(line));
Console.Write(" ");
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
Console.WriteLine(Encoding.ASCII.GetString(line));
}
Console.ReadLine();
}
}
Android: How to stretch an image to the screen width while maintaining aspect ratio?
I accomplished this with a custom view. Set layout_width="fill_parent" and layout_height="wrap_content", and point it to the appropriate drawable:
public class Banner extends View {
private final Drawable logo;
public Banner(Context context) {
super(context);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs) {
super(context, attrs);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
@Override protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * logo.getIntrinsicHeight() / logo.getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
Converting EditText to int? (Android)
You can use parseInt with try and catch block
try
{
int myVal= Integer.parseInt(mTextView.getText().toString());
}
catch (NumberFormatException e)
{
// handle the exception
int myVal=0;
}
Or you can create your own tryParse method :
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
and use it in your code like:
int myVal= tryParse(mTextView.getText().toString());
Note: The following code without try/catch will throw an exception
int myVal= new Integer(mTextView.getText().toString()).intValue();
Or
int myVal= Integer.decode(mTextView.getText().toString()).intValue();
Running an executable in Mac Terminal
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
Loop through a date range with JavaScript
I think I found an even simpler answer, if you allow yourself to use Moment.js:
_x000D_
_x000D_
// cycle through last five days, today included_x000D_
// you could also cycle through any dates you want, mostly for_x000D_
// making this snippet not time aware_x000D_
const currentMoment = moment().subtract(4, 'days');_x000D_
const endMoment = moment().add(1, 'days');_x000D_
while (currentMoment.isBefore(endMoment, 'day')) {_x000D_
console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);_x000D_
currentMoment.add(1, 'days');_x000D_
}
_x000D_
<script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_
Convert a list of characters into a string
Use the join
method of the empty string to join all of the strings together with the empty string in between, like so:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
How can I get Eclipse to show .* files?
For Project Explorer View:
1. Click on arrow(View Menu) in right corner
2. Select Customize View... item from menu
3. Uncheck *.resources checkbox under Filters tab
4. Click OK
--
Eclipse Juno
How to generate a random integer number from within a range
Following on from @Ryan Reich's answer, I thought I'd offer my cleaned up version. The first bounds check isn't required given the second bounds check, and I've made it iterative rather than recursive. It returns values in the range [min, max], where max >= min
and 1+max-min < RAND_MAX
.
unsigned int rand_interval(unsigned int min, unsigned int max)
{
int r;
const unsigned int range = 1 + max - min;
const unsigned int buckets = RAND_MAX / range;
const unsigned int limit = buckets * range;
/* Create equal size buckets all in a row, then fire randomly towards
* the buckets until you land in one of them. All buckets are equally
* likely. If you land off the end of the line of buckets, try again. */
do
{
r = rand();
} while (r >= limit);
return min + (r / buckets);
}
How to play YouTube video in my Android application?
Google has a YouTube Android Player API that enables you to incorporate video playback functionality into your Android applications. The API itself is very easy to use and works well. For example, here is how to create a new activity to play a video using the API.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);
startActivity(intent);
See this for more details.
How to cast ArrayList<> from List<>
When you are using second approach you are initializing arraylist with its predefined values.
Like generally we do
ArrayList listofStrings = new ArrayList<>();
Let's say you have an array with values, now you want to convert this array into arraylist.
you need to first get the list from the array using Arrays utils.
Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.
List<String> listofOptions = (List<String>) Arrays.asList(options);
then you can user constructoru of an arraylist to instantiate with predefined values.
ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
So your second approach is working that you have passed values which will intantiate arraylist with the list elements.
More over
ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list.
If you try to add or remove over Arrays.asList it will give you
UnsupportedOperationException
Formatting dates on X axis in ggplot2
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
How to insert close button in popover for Bootstrap
FWIW, here's the generic solution that I'm using. I'm using Bootstrap 3, but I think the general approach should work with Bootstrap 2 as well.
The solution enables popovers and adds a 'close' button for all popovers identified by the 'rel="popover"' tag using a generic block of JS code. Other than the (standard) requirement that there be a rel="popover" tag, you can put an arbitrary number of popovers on the page, and you don't need to know their IDs -- in fact they don't need IDs at all. You do need to use the 'data-title' HTML tag format to set the title attribute of your popovers, and have data-html set to "true".
The trick that I found necessary was to build an indexed map of references to the popover objects ("po_map"). Then I can add an 'onclick' handler via HTML that references the popover object via the index that JQuery gives me for it ("p_list['+index+'].popover(\'toggle\')"). That way I don't need to worry about the ids of the popover objects, since I have a map of references to the objects themselves with a JQuery-provided unique index.
Here's the javascript:
var po_map = new Object();
function enablePopovers() {
$("[rel='popover']").each(function(index) {
var po=$(this);
po_map[index]=po;
po.attr("data-title",po.attr("data-title")+
'<button id="popovercloseid" title="close" type="button" class="close" onclick="po_map['+index+'].popover(\'toggle\')">×</button>');
po.popover({});
});
}
$(document).ready(function() { enablePopovers() });
this solution let me easily put a close button on all the popovers all across my site.
jQuery UI DatePicker - Change Date Format
dateFormat
The format for parsed and displayed dates. This attribute is one of
the regionalisation attributes. For a full list of the possible
formats see the formatDate function.
Code examples Initialize a datepicker with the dateFormat option
specified.
$( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });
Get or set the dateFormat option, after init.
//getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );
//setter
$( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
How to set a header in an HTTP response?
Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).
Cast to generic type in C#
Does this work for you?
interface IMessage
{
void Process(object source);
}
class LoginMessage : IMessage
{
public void Process(object source)
{
}
}
abstract class MessageProcessor
{
public abstract void ProcessMessage(object source, object type);
}
class MessageProcessor<T> : MessageProcessor where T: IMessage
{
public override void ProcessMessage(object source, object o)
{
if (!(o is T)) {
throw new NotImplementedException();
}
ProcessMessage(source, (T)o);
}
public void ProcessMessage(object source, T type)
{
type.Process(source);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<Type, MessageProcessor> messageProcessors = new Dictionary<Type, MessageProcessor>();
messageProcessors.Add(typeof(string), new MessageProcessor<LoginMessage>());
LoginMessage message = new LoginMessage();
Type key = message.GetType();
MessageProcessor processor = messageProcessors[key];
object source = null;
processor.ProcessMessage(source, message);
}
}
This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor.
Edit: I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.
Override console.log(); for production
It would be super useful to be able to toggle logging in the production build. The code below turns the logger off by default.
When I need to see logs, I just type debug(true)
into the console.
var consoleHolder = console;
function debug(bool){
if(!bool){
consoleHolder = console;
console = {};
Object.keys(consoleHolder).forEach(function(key){
console[key] = function(){};
})
}else{
console = consoleHolder;
}
}
debug(false);
To be thorough, this overrides ALL of the console methods, not just console.log
.
VBA equivalent to Excel's mod function
Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function
This function always works and is the exact copy of the Excel function.
Create Directory if it doesn't exist with Ruby
You are probably trying to create nested directories. Assuming foo
does not exist, you will receive no such file or directory
error for:
Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'
To create nested directories at once, FileUtils
is needed:
require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]
Edit2: you do not have to use FileUtils
, you may do system call (update from @mu is too short comment):
> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true
But that seems (at least to me) as worse approach as you are using external 'tool' which may be unavailable on some systems (although I can hardly imagine system without mkdir
, but who knows).
String formatting in Python 3
Here are the docs about the "new" format syntax. An example would be:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals
and penalties
are integers (i.e. their default format is ok), it could be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since the parameters are fields of self
, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Explaining:
{}
means just the next positional argument, with default format;
{0}
means the argument with index 0
, with default format;
{:d}
is the next positional argument, with decimal integer format;
{0:d}
is the argument with index 0
, with decimal integer format.
There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)
"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)
"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'
"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'
"games: {:>3}".format(player1.games) # 'games: 123'
"games: {:>3}".format(player2.games) # 'games: 4'
"games: {:0>3}".format(player2.games) # 'games: 004'
Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).
enum - getting value of enum on string conversion
I implemented access using the following
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
now I can just do
print(D.x)
to get 1
as result.
You can also use self.name
in case you wanted to print x
instead of 1
.
.htaccess - how to force "www." in a generic way?
If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Hiding elements in responsive layout?
New visible classes added to Bootstrap
Extra small devices
Phones (<768px) (Class names : .visible-xs-block, hidden-xs)
Small devices
Tablets (=768px) (Class names : .visible-sm-block, hidden-sm)
Medium devices
Desktops (=992px) (Class names : .visible-md-block, hidden-md)
Large devices
Desktops (=1200px) (Class names : .visible-lg-block, hidden-lg)
Below is deprecated as of v3.2.0
Extra small devices
Phones (<768px) (Class names : .visible-xs, hidden-xs)
Small devices
Tablets (=768px) (Class names : .visible-sm, hidden-sm)
Medium devices
Desktops (=992px) (Class names : .visible-md, hidden-md)
Large devices
Desktops (=1200px) (Class names : .visible-lg, hidden-lg)
Much older Bootstrap
.hidden-phone, .hidden-tablet
etc. are unsupported/obsolete.
UPDATE:
In Bootstrap 4 there are 2 types of classes:
- The
hidden-*-up
which hide the element when the viewport is at the given breakpoint or wider.
hidden-*-down
which hide the element when the viewport is at the given breakpoint or smaller.
Also, the new xl
viewport is added for devices that are more then 1200px width. For more information click here.
Export SQL query data to Excel
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in
clause...
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.
When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.
Hope this helps any others having a similar issue.
c# razor url parameter from view
@(ViewContext.RouteData.Values["parameterName"])
worked with ROUTE PARAM.
Request.Params["paramName"]
did not work with ROUTE PARAM.
How do you get the path to the Laravel Storage folder?
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
How to upper case every first letter of word in a string?
My code after reading a few above answers.
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* @param pWord
* String to be made more readable
* @return Human-readable string
*/
public static String humanize2(String pWord)
{
StringBuilder sb = new StringBuilder();
String[] words = pWord.replaceAll("_", " ").split("\\s");
for (int i = 0; i < words.length; i++)
{
if (i > 0)
sb.append(" ");
if (words[i].length() > 0)
{
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1)
{
sb.append(words[i].substring(1));
}
}
}
return sb.toString();
}
How to output messages to the Eclipse console when developing for Android
System.out.println()
also outputs to LogCat. The benefit of using good old System.out.println()
is that you can print an object like System.out.println(object)
to the console if you need to check if a variable is initialized or not.
Log.d
, Log.v
, Log.w
etc methods only allow you to print strings to the console and not objects. To circumvent this (if you desire), you must use String.format
.
Variable's memory size in Python
Use sys.getsizeof
to get the size of an object, in bytes.
>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>
Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.
Callback functions in Java
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
Play sound on button click android
All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?
Your MediaPlayer
will sometimes fail to play your sound if you click the button to many times.
I ran into this performance problem with the MediaPlayer
class a few days ago.
Is the MediaPlayer
class save to use? Not always. If you have short sounds it is better to use the SoundPool
class.
A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.
SoundPool is not as easy to use as the MediaPlayer
class but has some great benefits when it comes to performance and reliability.
Follow this link and learn how to use the SoundPool class in you application:
https://developer.android.com/reference/android/media/SoundPool
Youtube: Save Solution
Get MD5 hash of big files in Python
I think the following code is more pythonic:
from hashlib import md5
def get_md5(fname):
m = md5()
with open(fname, 'rb') as fp:
for chunk in fp:
m.update(chunk)
return m.hexdigest()
How do you open an SDF file (SQL Server Compact Edition)?
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
- View ->
- Server Explorer ->
- Data Connections ->
- Add Connection...
- Change... (Data Source:)
- Microsoft SQL Server Compact 4.0
- Browse...
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
Correlation heatmap
Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).
import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline
# load the R package ISLR
infert = com.importr("ISLR")
# load the Auto dataset
auto_df = com.load_data('Auto')
# calculate the correlation matrix
corr = auto_df.corr()
# plot the heatmap
sns.heatmap(corr,
xticklabels=corr.columns,
yticklabels=corr.columns)
If you wanted to be even more fancy, you can use Pandas Style, for example:
cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
def magnify():
return [dict(selector="th",
props=[("font-size", "7pt")]),
dict(selector="td",
props=[('padding', "0em 0em")]),
dict(selector="th:hover",
props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'),
('font-size', '12pt')])
]
corr.style.background_gradient(cmap, axis=1)\
.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
.set_caption("Hover to magify")\
.set_precision(2)\
.set_table_styles(magnify())
How to set header and options in axios?
try this code
in example code use axios get rest API.
in mounted
mounted(){
var config = {
headers: {
'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
'x-rapidapi-key': '5156f83861mshd5c5731412d4c5fp18132ejsn8ae65e661a54'
}
};
axios.get('https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats?
country=Thailand', config)
.then((response) => {
console.log(response.data);
});
}
Hope is help.
Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved
I solved it now. However it only is solved in Netbeans. Not sure why eclipse still won't take the settings.xml that is changed. The solution is however to remove/comment the User/Password param in settings.xml
Before:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxyserver.company.com</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
After:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>proxyserver.company.com</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
Returning a boolean value in a JavaScript function
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
Is there a "do ... until" in Python?
There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:
import itertools
def dowhile(predicate):
it = itertools.repeat(None)
for _ in it:
yield
if not predicate(): break
so, for example:
i=7; j=3
for _ in dowhile(lambda: i<j):
print i, j
i+=1; j-=1
executes one leg, as desired, even though the predicate's already false at the start.
It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:
def incandec(i, j, delta=1):
while True:
yield i, j
if j <= i: break
i+=delta; j-=delta
which you can use like:
for i, j in incandec(i=7, j=3):
print i, j
It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for
loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).
What do "branch", "tag" and "trunk" mean in Subversion repositories?
In general (tool agnostic view), a branch is the mechanism used for parallel development. An SCM can have from 0 to n branches. Subversion has 0.
Trunk is a main branch recommended by Subversion, but you are in no way forced to create it. You could call it 'main' or 'releases', or not have one at all!
Branch represents a development effort. It should never be named after a resource (like 'vonc_branch') but after:
- a purpose 'myProject_dev' or 'myProject_Merge'
- a release perimeter 'myProjetc1.0_dev'or myProject2.3_Merge' or 'myProject6..2_Patch1'...
Tag is a snapshot of files in order to easily get back to that state.
The problem is that tag and branch is the same in Subversion. And I would definitely recommend the paranoid approach:
you can use one of the access control scripts provided with Subversion to prevent anyone from doing anything but creating new copies in the tags area.
A tag is final. Its content should never change. NEVER. Ever. You forgot a line in the release note? Create a new tag. Obsolete or remove the old one.
Now, I read a lot about "merging back such and such in such and such branches, then finally in the trunk branch".
That is called merge workflow and there is nothing mandatory here. It is not because you have a trunk branch that you have to merge back anything.
By convention, the trunk branch can represent the current state of your development, but that is for a simple sequential project, that is a project which has:
- no 'in advance' development (for the preparing the next-next version implying such changes that they are not compatible with the current 'trunk' development)
- no massive refactoring (for testing a new technical choice)
- no long-term maintenance of a previous release
Because with one (or all) of those scenario, you get yourself four 'trunks', four 'current developments', and not all you do in those parallel development will necessarily have to be merged back in 'trunk'.
Reset select value to default
You can also reset the values of multiple SELECTs and then trigger the submit button.
Please see it here in action:
Live Example:
$(function(){
$("#filter").click(function(){
//alert('clicked!');
$('#name').prop('selectedIndex',0);
$('#name2').prop('selectedIndex',0);
$('#submitBtn').click();
});
});
Streaming via RTSP or RTP in HTML5
My observations regarding the HTML 5 video tag and rtsp(rtp) streams are, that it only works with konqueror(KDE 4.4.1, Phonon-backend set to GStreamer). I got only video (no audio) with a H.264/AAC RTSP(RTP) stream.
The streams from http://media.esof2010.org/ didn't work with konqueror(KDE 4.4.1, Phonon-backend set to GStreamer).
Make XmlHttpRequest POST using JSON
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
ElasticSearch - Return Unique Values
If you want to get all unique values without any approximation or setting a magic number (size: 500
), then use COMPOSITE AGGREGATION (ES 6.5+).
From official documentation:
"If you want to retrieve all terms or all combinations of terms in a nested terms aggregation you should use the COMPOSITE AGGREGATION which allows to paginate over all possible terms rather than setting a size greater than the cardinality of the field in the terms aggregation. The terms aggregation is meant to return the top terms and does not allow pagination."
Implementation example in JavaScript:
_x000D_
_x000D_
const ITEMS_PER_PAGE = 1000;_x000D_
_x000D_
const body = {_x000D_
"size": 0, // Returning only aggregation results: https://www.elastic.co/guide/en/elasticsearch/reference/current/returning-only-agg-results.html_x000D_
"aggs" : {_x000D_
"langs": {_x000D_
"composite" : {_x000D_
"size": ITEMS_PER_PAGE,_x000D_
"sources" : [_x000D_
{ "language": { "terms" : { "field": "language" } } }_x000D_
]_x000D_
}_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
const uniqueLanguages = [];_x000D_
_x000D_
while (true) {_x000D_
const result = await es.search(body);_x000D_
_x000D_
const currentUniqueLangs = result.aggregations.langs.buckets.map(bucket => bucket.key);_x000D_
_x000D_
uniqueLanguages.push(...currentUniqueLangs);_x000D_
_x000D_
const after = result.aggregations.langs.after_key;_x000D_
_x000D_
if (after) {_x000D_
// continue paginating unique items_x000D_
body.aggs.langs.composite.after = after;_x000D_
} else {_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(uniqueLanguages);
_x000D_
_x000D_
_x000D_
Pipe to/from the clipboard in Bash script
There's a wealth of clipboards you could be dealing with. I expect you're probably a Linux user who wants to put stuff in the X Windows primary clipboard. Usually, the clipboard you want to talk to has a utility that lets you talk to it.
In the case of X, there's xclip
(and others). xclip -selection c
will send data to the clipboard that works with Ctrl + C, Ctrl + V in most applications.
If you're on Mac OS X, there's pbcopy
. e.g cat example.txt | pbcopy
If you're in Linux terminal mode (no X) then look into gpm
or screen which has a clipboard. Try the screen
command readreg
.
Under Windows 10+ or cygwin, use /dev/clipboard
or clip
.
Sort Pandas Dataframe by Date
You can use pd.to_datetime()
to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.
>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
Date Symbol
0 02/20/2015 A
1 01/15/2016 A
2 08/21/2015 A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
For future search, you can change the sort statement:
>>> df.sort_values(by='Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
Python Variable Declaration
This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:
variable_name: type_name
or this:
variable_name # type: shinyType
So in your case(if you have a CustomObject
class defined), you can do:
customObj: CustomObject
See this or that for more info.
How do I create delegates in Objective-C?
lets say you have a class that you developed and want to declare a delegate property to be able to notify it when some event happens :
@class myClass;
@protocol myClassDelegate <NSObject>
-(void)myClass:(MyClass*)myObject requiredEventHandlerWithParameter:(ParamType*)param;
@optional
-(void)myClass:(MyClass*)myObject optionalEventHandlerWithParameter:(ParamType*)param;
@end
@interface MyClass : NSObject
@property(nonatomic,weak)id< MyClassDelegate> delegate;
@end
so you declare a protocol in MyClass
header file (or a separate header file) , and declare the required/optional event handlers that your delegate must/should implement , then declare a property in MyClass
of type (id< MyClassDelegate>
) which means any objective c class that conforms to the protocol MyClassDelegate
, you'll notice that the delegate property is declared as weak , this is very important to prevent retain cycle (most often the delegate retains the MyClass
instance so if you declared the delegate as retain, both of them will retain each other and neither of them will ever be released).
you will notice also that the protocol methods passes the MyClass
instance to the delegate as parameter , this is best practice in case the delegate want to call some methods on MyClass
instance and also helps when the delegate declares itself as MyClassDelegate
to multiple MyClass
instances , like when you have multiple UITableView's
instances in your ViewController
and declares itself as a UITableViewDelegate
to all of them.
and inside your MyClass
you notify the delegate with declared events as follows :
if([_delegate respondsToSelector:@selector(myClass: requiredEventHandlerWithParameter:)])
{
[_delegate myClass:self requiredEventHandlerWithParameter:(ParamType*)param];
}
you first check if your delegate responds to the protocol method that you are about to call in case the delegate doesn't implement it and the app will crash then (even if the protocol method is required).
PHPExcel - set cell type before writing a value in it
I wanted the Number same as I get from database for example.
1) 00100.220000
2) 00123
3) 0000.0000100
So I modified the code as below
$objPHPExcel->getActiveSheet()
->setCellValue('A3', '00100.220000');
$objPHPExcel->getActiveSheet()
->getStyle('A3')
->getNumberFormat()
->setFormatCode('00000.000000');
$objPHPExcel->getActiveSheet()
->setCellValue('A4', '00123');
$objPHPExcel->getActiveSheet()
->getStyle('A4')
->getNumberFormat()
->setFormatCode('00000');
$objPHPExcel->getActiveSheet()
->setCellValue('A5', '0000.0000100');
$objPHPExcel->getActiveSheet()
->getStyle('A5')
->getNumberFormat()
->setFormatCode('0000.0000000');
How do I unbind "hover" in jQuery?
I found this works as second argument (function) to .hover()
$('#yourId').hover(
function(){
// Your code goes here
},
function(){
$(this).unbind()
}
});
The first function (argument to .hover()) is mouseover and will execute your code. The second argument is mouseout which will unbind the hover event from #yourId.
Your code will be executed only once.
How to determine if one array contains all elements of another array
a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]
a - b
# => [5, 1, 14, 8]
b - a
# => [15]
(b - a).empty?
# => false
Python: subplot within a loop: first panel appears in wrong position
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
Convert Rtf to HTML
I think you can load it in a Word document object by using .NET office programmability support and Visual Studio tools for office.
And then use the document instance to re-save as an HTML document.
I am not sure how but I believe it is possible entirely in .NET without any 3rd party library.
How to sort an ArrayList?
In JAVA 8 its much easy now.
List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase = alphaNumbers.stream()
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]
-- For reverse use this
.sorted(Comparator.reverseOrder())
Should I use the Reply-To header when sending emails as a service to others?
You may want to consider placing the customer's name in the From
header and your address in the Sender
header:
From: Company A <[email protected]>
Sender: [email protected]
Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To
of Company A's address won't seem out of sorts.
From RFC 5322:
The "From:" field specifies the author(s) of the message,
that is, the mailbox(es) of the person(s) or system(s) responsible
for the writing of the message. The "Sender:" field specifies the
mailbox of the agent responsible for the actual transmission of the
message. For example, if a secretary were to send a message for
another person, the mailbox of the secretary would appear in the
"Sender:" field and the mailbox of the actual author would appear in
the "From:" field.
Iterating over all the keys of a map
Is there a way to get a list of all the keys in a Go language map?
ks := reflect.ValueOf(m).MapKeys()
how do I iterate over all the keys?
Use the accepted answer:
for k, _ := range m { ... }
The controller for path was not found or does not implement IController
Here is my problem and the solution that what worked for me.
I added a new controller with a single action returning a string to an existing application. But when I navigated to that controller via browser, I was getting the same error as mentioned above.
After doing lot of googling, I found out that I simply had to modify my Global.asax.cs file for it to recognize the new controller. All I did was added a space to Global.asax.cs file so that it is modified and it worked
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.
Update Tkinter Label from variable
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
Declaring a boolean in JavaScript using just var
You can use and test uninitialized variables at least for their 'definedness'.
Like this:
var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false
Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.
var thisMayBeTrue;
thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly
// converted to 1 and 1 is implicitly converted to true)
thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true
thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the
// ! or !! operator tests the 'definedness' of a variable.
PS: you can't test 'definedness' for nonexisting variables though. So:
alert(!!HelloWorld);
gives a reference Error ('HelloWorld is not defined')
(is there a better word for 'definedness'? Pardon my dutch anyway;~)
How do I go about adding an image into a java project with eclipse?
If you still have problems with Eclipse finding your files, you might try the following:
- Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
Clicking a button within a form causes page refresh
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button'
when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
Convert generic list to dataset in C#
I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
return ds;
}
What is the method for converting radians to degrees?
For double in c# this might be helpful:
public static double Conv_DegreesToRadians(this double degrees)
{
//return degrees * (Math.PI / 180d);
return degrees * 0.017453292519943295d;
}
public static double Conv_RadiansToDegrees(this double radians)
{
//return radians * (180d / Math.PI);
return radians * 57.295779513082323d;
}
checked = "checked" vs checked = true
The original checked
attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.
This, however is not valid for XHTML that followed HTML 4.
The standard proposed to use checked="checked"
as a condition for true - so both ways you posted end up doing the same thing.
It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).
Detect change to ngModel on a select tag (Angular 2)
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
Having issues with a MySQL Join that needs to meet multiple conditions
also this should work (not tested):
SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc
If u.id_fu is a numeric field then you can remove the ' around them.
The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".
Also I and Oracle too recommend to enclose table and field names in backticks.
So you won't get into trouble if a field name contains a keyword.
permission denied - php unlink
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use;
1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
Convert a string into an int
I use:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:@"%d", integer];
}
Get refresh token google api
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is
important to store that refresh token for future use. If your
application loses the refresh token, it will have to re-prompt the
user for consent before obtaining another refresh token. If you need
to re-prompt the user for consent, include the approval_prompt
parameter in the authorization code request, and set the value to
force
.
So, when you have already granted access, subsequent requests for a grant_type
of authorization_code
will not return the refresh_token
, even if access_type
was set to offline
in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token
after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt
to force
.
Cheers,
PS This change was announced in a blog post as well.
How to get the unique ID of an object which overrides hashCode()?
The javadoc for Object specifies that
This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.
If a class overrides hashCode, it means that it wants to generate a specific id, which will (one can hope) have the right behaviour.
You can use System.identityHashCode to get that id for any class.
Select All as default value for Multivalue parameter
This is rather easy to achieve by making a dataset with a text-query like this:
SELECT 'Item1'
UNION
SELECT 'Item2'
UNION
SELECT 'Item3'
UNION
SELECT 'Item4'
UNION
SELECT 'ItemN'
The query should return all items that can be selected.
How can I return pivot table output in MySQL?
There is a tool called MySQL Pivot table generator, it can help you create web based pivot table that you can later export to excel(if you like). it can work if your data is in a single table or in several tables .
All you need to do is to specify the data source of the columns (it supports dynamic columns), rows , the values in the body of the table and table relationship (if there are any)
The home page of this tool is http://mysqlpivottable.net
Head and tail in one line
Python 2, using lambda
>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
Injecting Mockito mocks into a Spring bean
Given:
@Service
public class MyService {
@Autowired
private MyDAO myDAO;
// etc
}
You can have the class that is being tested loaded via autowiring, mock the dependency with Mockito, and then use Spring's ReflectionTestUtils to inject the mock into the class being tested.
@ContextConfiguration(classes = { MvcConfiguration.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
private MyDAO myDAOMock;
@Before
public void before() {
myDAOMock = Mockito.mock(MyDAO.class);
ReflectionTestUtils.setField(myService, "myDAO", myDAOMock);
}
// etc
}
Please note that before Spring 4.3.1, this method won't work with services behind a proxy (annotated with @Transactional
, or Cacheable
, for example). This has been fixed by SPR-14050.
For earlier versions, a solution is to unwrap the proxy, as described there: Transactional annotation avoids services being mocked (which is what ReflectionTestUtils.setField
does by default now)
$_SERVER['HTTP_REFERER'] missing
Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:
$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
Clear and refresh jQuery Chosen dropdown list
MVC 4:
function Cargar_BS(bs) {
$.getJSON('@Url.Action("GetBienServicio", "MonitoreoAdministracion")',
{
id: bs
},
function (d) {
$("#txtIdItem").empty().append('<option value="">-Seleccione-</option>');
$.each(d, function (idx, item) {
jQuery("<option/>").text(item.C_DescBs).attr("value", item.C_CodBs).appendTo("#txtIdItem");
})
$('#txtIdItem').trigger("chosen:updated");
});
}
How to insert a new line in Linux shell script?
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
ng-change not working on a text input
When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
<input type="text" name="abc" class="color" ng-model="myStyle.color">
You don't need to watch the change at all!
Address already in use: JVM_Bind java
The quick answer on how to prevent it is that you most likely need to stop JBoss before starting it again.
You should be able to call the "Terminate" button in the Console view to shutdown the server.
CSS Circle with border
You forgot to set the width of the border! Change border: red;
to border:1px solid red;
Here the full code to get the circle:
_x000D_
_x000D_
.circle {_x000D_
background-color:#fff;_x000D_
border:1px solid red; _x000D_
height:100px;_x000D_
border-radius:50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius:50%;_x000D_
width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_
Xcode Objective-C | iOS: delay function / NSTimer help?
sleep
doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:
- (void)button_circleBusy:(id)sender {
firstButton.enabled = NO;
// 60 milliseconds is .06 seconds
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
firstButton.enabled = YES;
secondButton.enabled = NO;
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...
How to install bcmath module?
I found that the repo that had the package was not enabled. On OEL7,
$ vi /etc/yum.repos.d/ULN-Base.repo
Set enabled to 1 for ol7_optional_latest
$ yum install php-bcmath
and that worked...
I used the following command to find where the package was
$ yum --noplugins --showduplicates --enablerepo \* --disablerepo \*-source --disablerepo C5.\*,c5-media,\*debug\*,\*-source list \*bcmath
Get a list of checked checkboxes in a div using jQuery
function listselect() {
var selected = [];
$('.SelectPhone').prop('checked', function () {
selected.push($(this).val());
});
alert(selected.length);
<input type="checkbox" name="SelectPhone" class="SelectPhone" value="1" />
<input type="checkbox" name="SelectPhone" class="SelectPhone" value="2" />
<input type="checkbox" name="SelectPhone" class="SelectPhone" value="3" />
<button onclick="listselect()">show count</button>
Add colorbar to existing axis
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
How to move an element into another element?
If you want a quick demo and more details about how you move elements, try this link:
http://html-tuts.com/move-div-in-another-div-with-jquery
Here is a short example:
To move ABOVE an element:
$('.whatToMove').insertBefore('.whereToMove');
To move AFTER an element:
$('.whatToMove').insertAfter('.whereToMove');
To move inside an element, ABOVE ALL elements inside that container:
$('.whatToMove').prependTo('.whereToMove');
To move inside an element, AFTER ALL elements inside that container:
$('.whatToMove').appendTo('.whereToMove');
javascript setTimeout() not working
If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.
i.e. works
setTimeout(function(){ startTimer(p1, p2); }, 1000);
i.e. won't work because it will call the function right away
setTimeout( startTimer(p1, p2), 1000);
How to add click event to a iframe with JQuery
You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.
Like this:
<div id="iframe_id_wrapper">
<iframe id="iframe_id" src="http://something.com"></iframe>
</div>
And disable pointer events on iframe itself.
#iframe_id { pointer-events: none; }
After this changes your code will work like expected.
$('#iframe_id_wrapper').click(function() {
//run function that records clicks
});
Hashmap does not work with int, char
Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.
Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer>
if you need to.
TCharIntHashMap: An open addressed Map implementation for char keys and int values.
How to configure encoding in Maven?
If you combine the answers above, finally a pom.xml that configured for UTF-8 should seem like that.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>YOUR_COMPANY</groupId>
<artifactId>YOUR_APP</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<project.java.version>1.8</project.java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- Your dependencies -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${project.java.version}</source>
<target>${project.java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Why does python use 'else' after for and while loops?
The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.
for a in range(3):
print(a)
if a==4: # change value to force break or not
break
else: #no break +10 for whoever thought of this decoration
print('for completed OK')
print('statement after for loop')
Hiding the scroll bar on an HTML page
In addition to Peter's answer:
#element::-webkit-scrollbar {
display: none;
}
This will work the same for Internet Explorer 10:
#element {
-ms-overflow-style: none;
}
How to speed up insertion performance in PostgreSQL
In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:
- Set the level-of-rollback-on-errors to "Transaction" by specifying
Protocol=-1
in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
- Use server-side prepared statements by specifying
UseServerSidePrepare=1
in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
- Disable auto-commit on each statement using
SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
- Once all rows have been inserted, commit the transaction using
SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
. There is no need to explicitly open a transaction.
Unfortunately, psqlodbc "implements" SQLBulkOperations
by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.
Excel VBA - Range.Copy transpose paste
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions
Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
How to declare a inline object with inline variables without a parent class
You can also declare 'x' with the keyword var:
var x = new
{
driver = new
{
firstName = "john",
lastName = "walter"
},
car = new
{
brand = "BMW"
}
};
This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :
x.driver.firstName // "john"
x.car.brand // "BMW"
var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"
How to fix height of TR?
Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div
element, like so:
_x000D_
_x000D_
td.container > div {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
height: 20px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="container">_x000D_
<div>This is a long line of text designed not to wrap _x000D_
when the container becomes too small.</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
This way, the div
's height is that of the containing cell and the text cannot grow the div
, keeping the cell/row the same height no matter what the window size is.
How to set transparent background for Image Button in code?
DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button
(or the generic view) will no more highlight at click!!!
I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view
Use this in the button specifications
android:background="?android:selectableItemBackground"
This requires API 11
How to set Android camera orientation properly?
From other member and my problem:
Camera Rotation issue depend on different Devices and certain Version.
Version 1.6: to fix the Rotation Issue, and it is good for most of devices
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation",90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Version 2.2: not for all devices
camera.setDisplayOrientation(90);
http://code.google.com/p/android/issues/detail?id=1193#c42
Open popup and refresh parent page on close popup
In my case I opened a pop up window on click on linkbutton in parent page.
To refresh parent on closing child using
window.opener.location.reload();
in child window caused re open the child window (Might be because of View State I guess. Correct me If I m wrong).
So I decided not to reload page in parent and load the the page again assigning same url to it.
To avoid popup opening again after closing pop up window this might help,
window.onunload = function(){
window.opener.location = window.opener.location;};
Open Google Chrome from VBA/Excel
I found an easier way to do it and it works perfectly even if you don't know the path where the chrome is located.
First of all, you have to paste this code in the top of the module.
Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
After that you have to create this two modules:
Sub LoadExplorer()
LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub
Sub LoadFile(FileName As String)
ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub
With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.
Ps: It works perfectly for others browsers just changing "Chrome.exe" to opera, bing, etc.
Python Pandas: Get index of rows which column matches certain value
First you may check query
when the target column is type bool
(PS: about how to use it please check link )
df.query('BoolCol')
Out[123]:
BoolCol
10 True
40 True
50 True
After we filter the original df by the Boolean column we can pick the index .
df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')
Also pandas have nonzero
, we just select the position of True
row and using it slice the DataFrame
or index
df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')
Polymorphism vs Overriding vs Overloading
overriding is more like hiding an inherited method by declaring a method with the same name and signature as the upper level method (super method), this adds a polymorphic behaviour to the class .
in other words the decision to choose wich level method to be called will be made at run time not on compile time .
this leads to the concept of interface and implementation .
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
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
How to move files from one git repo to another (not a clone), preserving history
If your history is sane, you can take the commits out as patch and apply them in the new repository:
cd repository
git log --pretty=email --patch-with-stat --reverse --full-index --binary -- path/to/file_or_folder > patch
cd ../another_repository
git am --committer-date-is-author-date < ../repository/patch
Or in one line
git log --pretty=email --patch-with-stat --reverse -- path/to/file_or_folder | (cd /path/to/new_repository && git am --committer-date-is-author-date)
(Taken from Exherbo’s docs)
creating a new list with subset of list using index in python
Suppose
a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]
and the list of indexes is stored in
b= [0, 1, 2, 4, 6, 7, 8]
then a simple one-line solution will be
c = [a[i] for i in b]
How to add Google Maps Autocomplete search box?
Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.
HTML
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
JavaScript
<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window
Access a function variable outside the function without using "global"
You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
Functions are objects in Python and can have arbitrary attributes assigned to them.
If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this
argument to each call to the decorated function.
This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self
— I picked something different to avoid confusion, but like the self
argument, it can be named whatever you wish.
Here's an example of that approach:
def add_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@add_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42
Note
This doesn't work for class methods. Just use the self
argument already passed being passed to instead of the method name. You can reference class-level attributes through type(self)
. See Function's attributes when in a class.
How do I import .sql files into SQLite 3?
From a sqlite prompt:
sqlite> .read db.sql
Or:
cat db.sql | sqlite3 database.db
Also, your SQL is invalid - you need ;
on the end of your statements:
create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);
How to Get True Size of MySQL Database?
You can get the size of your Mysql database by running the following command in Mysql client
SELECT sum(round(((data_length + index_length) / 1024 / 1024 / 1024), 2)) as "Size in GB"
FROM information_schema.TABLES
WHERE table_schema = "<database_name>"
Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3
In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Here we are just by passing the check by checking for OPTIONS verb.
How to concatenate columns in a Postgres SELECT?
PHP's Laravel framework,
I am using search first_name, last_name Fields consider like Full Name Search
Using || symbol Or concat_ws(), concat() methods
$names = str_replace(" ", "", $searchKey);
$customers = Customer::where('organization_id',$this->user->organization_id)
->where(function ($q) use ($searchKey, $names) {
$q->orWhere('phone_number', 'ilike', "%{$searchKey}%");
$q->orWhere('email', 'ilike', "%{$searchKey}%");
$q->orWhereRaw('(first_name || last_name) LIKE ? ', '%' . $names. '%');
})->orderBy('created_at','desc')->paginate(20);
This worked charm!!!
Gradle - Could not find or load main class
Just to make it clear for newbies trying to run a gradle project from Netbeans:
To understand this, you need to see what the main class name looks like and what the gradle build looks like:
Main class:
package com.stormtrident;
public class StormTrident {
public static void main(String[] cmdArgs) {
}
}
Notice that it is part of the package "com.stormtrident".
Gradle build:
apply plugin: 'java'
defaultTasks 'jar'
jar {
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'com.stormtrident.StormTrident'
}
}
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.stormtrident.StormTrident'
}
repositories {
mavenCentral()
}
dependencies {
//---apache storm
compile 'org.apache.storm:storm-core:1.0.0' //compile
testCompile group: 'junit', name: 'junit', version: '4.10'
}
link_to method and click event in Rails
To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});
Relative imports for the billionth time
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/
How to disable GCC warnings for a few lines of code
I had same issue with external libraries like ROS headers. I like to use following options in CMakeLists.txt for stricter compilation:
set(CMAKE_CXX_FLAGS "-std=c++0x -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code ${CMAKE_CXX_FLAGS}")
However doing this causes all kind of pedantic errors in externally included libraries as well. The solution is to disable all pedantic warnings before you include external libraries and re-enable like this:
//save compiler switches
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
//Bad headers with problem goes here
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
//restore compiler switches
#pragma GCC diagnostic pop
While, Do While, For loops in Assembly Language (emu8086)
For-loops:
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loops
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loops
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
How to find a number in a string using JavaScript?
Use a regular expression.
var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));
The expression \d+
means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:
var r = /\d+/;
is equivalent to:
var r = new RegExp("\d+");
See the details for the RegExp object.
The above will grab the first group of digits. You can loop through and find all matches too:
var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
alert(m[0]);
}
The g
(global) flag is key for this loop to work.
Java abstract interface
It's not necessary, it's optional, just as public
on interface methods.
See the JLS on this:
http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html
9.1.1.1 abstract Interfaces Every interface is implicitly abstract.
This modifier is obsolete and should not be used in new programs.
And
9.4 Abstract Method Declarations
[...]
For compatibility with older versions of the Java platform, it is
permitted but discouraged, as a matter of style, to redundantly
specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to
redundantly specify the public modifier for interface methods.
Can not find the tag library descriptor of springframework
I know it's an old question, but the tag library http://www.springframework.org/tags
is provided by spring-webmvc
package. With Maven it can be added to the project with the following lines to be added in the pom.xml
<properties>
<spring.version>3.0.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
Without Maven, just add that jar to your classpath. In any case it's not necessary to refer the tld file directly, it will be automatically found.
How to get default gateway in Mac OSX
The grep utility is not needed. Awk can do it all:
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
Note that if you have something like Parallels (or a VPN, or both) running, you may see two or more default routing entries - it will be true if you use the 'grep' suggestion above, too.
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
link#12
and
netstat -rn | awk '/default/ {print $2}'
utun1
192.168.128.1
link#12
To set a variable (_default) for further use (assuming only one entry for 'default') .....
_default=$( netstat -rn inet | awk '/default/ {print $2}' ) # I prefer $( ... ) over back-ticks
In the case of multiple default routes use:
netstat -rn | awk '/default/ {if ( index($6, "en") > 0 ){print $2} }'
192.168.128.1
These examples tested in Mavericks Terminal.app and are specific to OSX only. For example, other *nix versions frequently use 'eth' for ethernet/wireless connections, not 'en'.
This is also only tested with ksh. Other shells may need a slightly different syntax.
How to remove a branch locally?
I think (based on your comments) that I understand what you want to do: you want your local copy of the repository to have neither the ordinary local branch master
, nor the remote-tracking branch origin/master
, even though the repository you cloned—the github one—has a local branch master
that you do not want deleted from the github version.
You can do this by deleting the remote-tracking branch locally, but it will simply come back every time you ask your git to synchronize your local repository with the remote repository, because your git asks their git "what branches do you have" and it says "I have master
" so your git (re)creates origin/master
for you, so that your repository has what theirs has.
To delete your remote-tracking branch locally using the command line interface:
git branch -d -r origin/master
but again, it will just come back on re-synchronizations. It is possible to defeat this as well (using remote.origin.fetch
manipulation), but you're probably better off just being disciplined enough to not create or modify master
locally.