How to get the selected row values of DevExpress XtraGrid?
I found the solution as follows:
private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
TBGRNo.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "GRNo").ToString();
TBSName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SName").ToString();
TBFName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FName").ToString();
}
Can a foreign key be NULL and/or duplicate?
Short answer: Yes, it can be NULL or duplicate.
I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.
Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.
Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.
Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.
How to find out the MySQL root password
In your "hostname".err file inside the data folder MySQL works on, try to look for a string that starts with:
"A temporary password is generated for roor@localhost "
you can use
less /mysql/data/dir/hostname.err
then slash command followed by the string you wish to look for
/"A temporary password"
Then press n, to go to the Next result.
Execute PowerShell Script from C# with Commandline Arguments
Here is a way to add Parameters to the script if you used
pipeline.Commands.AddScript(Script);
This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.
pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();
And the fill variable method is:
private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
// Add additional variables to PowerShell
if (scriptParameters != null)
{
foreach (DictionaryEntry entry in scriptParameters)
{
CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
pipeline.Commands[0].Parameters.Add(Param);
}
}
}
this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:
Object resultcollection = runspace.SessionStateProxy.GetVariable("results");
//results being the name of the v
you'll have to do it the way I showed because for some reason if you do it the way
Kosi2801 suggests the script variables list doesn't get filled with your own variables.
Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor
As others have already mentioned you are required to provide a default constructor public Employee(){}
in your Employee
class.
What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object
, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee
therefore you must provide also the no-argument constructor.
Having said that Employee
class should look like this:
Your class Employee
import java.util.Date;
public class Employee
{
private String name, number;
private Date date;
public Employee(){} // No-argument Constructor
public Employee(String name, String number, Date date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(Date d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public Date getDate()
{
return date;
}
}
Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.
installing cPickle with python 3.5
cPickle
comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle
, you can do this:
>>> import _pickle as cPickle
However, in 3.x, it's easier just to use pickle
.
No need to install anything. If something requires cPickle
in python 3.x, then that's probably a bug.
PHP, getting variable from another php-file
You could also use a session for passing small bits of info. You will need to have session_start(); at the top of the PHP pages that use the session else the variables will not be accessable
page1.php
<?php
session_start();
$_SESSION['superhero'] = "batman";
?>
<a href="page2.php" title="">Go to the other page</a>
page2.php
<?php
session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc
echo $_SESSION['superhero'];
?>
Select columns from result set of stored procedure
As it's been mentioned in the question, it's hard to define the 80 column temp table before executing the stored procedure.
So the other way around this is to populate the table based on the stored procedure result set.
SELECT * INTO #temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;'
,'EXEC MyStoredProc')
If you are getting any error, you need to enable ad hoc distributed queries by executing following query.
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
To execute sp_configure
with both parameters to change a configuration option or to run the RECONFIGURE
statement, you must be granted the ALTER SETTINGS
server-level permission
Now you can select your specific columns from the generated table
SELECT col1, col2
FROM #temp
Running unittest with typical test directory structure
This BASH script will execute the python unittest test directory from anywhere in the file system, no matter what working directory you are in.
This is useful when staying in the ./src
or ./example
working directory and you need a quick unit test:
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
python -m unittest discover -s "$readlink"/test -v
No need for a test/__init__.py
file to burden your package/memory-overhead during production.
Sort array of objects by string property value
Combining Ege's dynamic solution with Vinay's idea, you get a nice robust solution:
Array.prototype.sortBy = function() {
function _sortByAttr(attr) {
var sortOrder = 1;
if (attr[0] == "-") {
sortOrder = -1;
attr = attr.substr(1);
}
return function(a, b) {
var result = (a[attr] < b[attr]) ? -1 : (a[attr] > b[attr]) ? 1 : 0;
return result * sortOrder;
}
}
function _getSortFunc() {
if (arguments.length == 0) {
throw "Zero length arguments not allowed for Array.sortBy()";
}
var args = arguments;
return function(a, b) {
for (var result = 0, i = 0; result == 0 && i < args.length; i++) {
result = _sortByAttr(args[i])(a, b);
}
return result;
}
}
return this.sort(_getSortFunc.apply(null, arguments));
}
Usage:
// Utility for printing objects
Array.prototype.print = function(title) {
console.log("************************************************************************");
console.log("**** "+title);
console.log("************************************************************************");
for (var i = 0; i < this.length; i++) {
console.log("Name: "+this[i].FirstName, this[i].LastName, "Age: "+this[i].Age);
}
}
// Setup sample data
var arrObj = [
{FirstName: "Zach", LastName: "Emergency", Age: 35},
{FirstName: "Nancy", LastName: "Nurse", Age: 27},
{FirstName: "Ethel", LastName: "Emergency", Age: 42},
{FirstName: "Nina", LastName: "Nurse", Age: 48},
{FirstName: "Anthony", LastName: "Emergency", Age: 44},
{FirstName: "Nina", LastName: "Nurse", Age: 32},
{FirstName: "Ed", LastName: "Emergency", Age: 28},
{FirstName: "Peter", LastName: "Physician", Age: 58},
{FirstName: "Al", LastName: "Emergency", Age: 51},
{FirstName: "Ruth", LastName: "Registration", Age: 62},
{FirstName: "Ed", LastName: "Emergency", Age: 38},
{FirstName: "Tammy", LastName: "Triage", Age: 29},
{FirstName: "Alan", LastName: "Emergency", Age: 60},
{FirstName: "Nina", LastName: "Nurse", Age: 54}
];
//Unit Tests
arrObj.sortBy("LastName").print("LastName Ascending");
arrObj.sortBy("-LastName").print("LastName Descending");
arrObj.sortBy("LastName", "FirstName", "-Age").print("LastName Ascending, FirstName Ascending, Age Descending");
arrObj.sortBy("-FirstName", "Age").print("FirstName Descending, Age Ascending");
arrObj.sortBy("-Age").print("Age Descending");
Understanding SQL Server LOCKS on SELECT queries
The SELECT WITH (NOLOCK)
allows reads of uncommitted data, which is equivalent to having the READ UNCOMMITTED
isolation level set on your database. The NOLOCK
keyword allows finer grained control than setting the isolation level on the entire database.
Wikipedia has a useful article: Wikipedia: Isolation (database systems)
It is also discussed at length in other stackoverflow articles.
Getting request URL in a servlet
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
Mathematical functions in Swift
As other noted you have several options. If you want only mathematical functions. You can import only Darwin.
import Darwin
If you want mathematical functions and other standard classes and functions. You can import Foundation.
import Foundation
If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.
For OS X, you need import Cocoa.
import Cocoa
For iOS, you need import UIKit.
import UIKit
You can easily discover your playground platform by opening File Inspector (??1).
oracle plsql: how to parse XML and insert into table
CREATE OR REPLACE PROCEDURE ADDEMP
(xml IN CLOB)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
SELECT
ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
FROM TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;
COMMIT;
END;
Public class is inaccessible due to its protection level
You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.
Linq on DataTable: select specific column into datatable, not whole table
LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.
So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.
Find it here how to do this.
DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");
Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).
Are nested try/except blocks in Python a good programming practice?
For your specific example, you don't actually need to nest them. If the expression in the try
block succeeds, the function will return, so any code after the whole try/except block will only be run if the first attempt fails. So you can just do:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
pass
# execution only reaches here when try block raised AttributeError
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
Nesting them isn't bad, but I feel like leaving it flat makes the structure more clear: you're sequentially trying a series of things and returning the first one that works.
Incidentally, you might want to think about whether you really want to use __getattribute__
instead of __getattr__
here. Using __getattr__
will simplify things because you'll know that the normal attribute lookup process has already failed.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
What are invalid characters in XML
For Java folks, Apache has a utility class (StringEscapeUtils
) that has a helper method escapeXml
which can be used for escaping characters in a string using XML entities.
How to display hidden characters by default (ZERO WIDTH SPACE ie. ​)
Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces
.
Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces
.
Edit:
Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.
Converting double to integer in Java
is there a possibility that casting a double created via Math.round()
will still result in a truncated down number
No, round()
will always round your double to the correct value, and then, it will be cast to an long
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double)
:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
What does "both" mean in <div style="clear:both">
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
SQL Server : Columns to Rows
DECLARE @TableName varchar(max)=NULL
SELECT @TableName=COALESCE(@TableName+',','')+t.TABLE_CATALOG+'.'+ t.TABLE_SCHEMA+'.'+o.Name
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME=o.name
WHERE i.indid < 2
AND OBJECTPROPERTY(o.id,'IsMSShipped') = 0
AND i.rowcnt >350
AND o.xtype !='TF'
ORDER BY o.name ASC
print @tablename
You can get list of tables which has rowcounts >350 . You can see at the solution list of table as row.
Crop image to specified size and picture location
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
When to use RSpec let()?
In general, let()
is a nicer syntax, and it saves you typing @name
symbols all over the place. But, caveat emptor! I have found let()
also introduces subtle bugs (or at least head scratching) because the variable doesn't really exist until you try to use it... Tell tale sign: if adding a puts
after the let()
to see that the variable is correct allows a spec to pass, but without the puts
the spec fails -- you have found this subtlety.
I have also found that let()
doesn't seem to cache in all circumstances! I wrote it up in my blog: http://technicaldebt.com/?p=1242
Maybe it is just me?
How big can a MySQL database get before performance starts to degrade
Database size DOES matter in terms of bytes and table's rows number. You will notice a huge performance difference between a light database and a blob filled one. Once my application got stuck because I put binary images inside fields instead of keeping images in files on the disk and putting only file names in database. Iterating a large number of rows on the other hand is not for free.
Reading multiple Scanner inputs
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
What is a "static" function in C?
static
functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).
EDIT: For those who thought, that the author of the questions meant a 'class method': As the question is tagged C
he means a plain old C function. For (C++/Java/...) class methods, static
means that this method can be called on the class itself, no instance of that class necessary.
Decode JSON with unknown structure
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
Underline text in UIlabel
An enhanced version of the code of Kovpas (color and line size)
@implementation UILabelUnderlined
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);
CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, tmpSize.width, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
@end
How do I get a reference to the app delegate in Swift?
Here's an extension for UIApplicationDelegate
that avoids hardcoding the AppDelegate
class name:
extension UIApplicationDelegate {
static var shared: Self {
return UIApplication.shared.delegate! as! Self
}
}
// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate
Compiling Java 7 code via Maven
Not sure what the OS is in use here, but you can eliminate a lot of java version futzing un debian/ubuntu with update-java-alternatives to set the default jvm system wide.
#> update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-6-sun 63 /usr/lib/jvm/java-6-sun
java-7-oracle 1073 /usr/lib/jvm/java-7-oracle
To set a new one, use:
#> update-java-alternatives -s java-7-oracle
No need to set JAVA_HOME for most apps.
Create a folder inside documents folder in iOS apps
Swift 4.0
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
// Creates that folder if not exists
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}
Using grep to search for hex strings in a file
grep has a -P switch allowing to use perl regexp syntax
the perl regex allows to look at bytes, using \x.. syntax.
so you can look for a given hex string in a file with: grep -aP "\xdf"
but the outpt won't be very useful; indeed better do a regexp on the hexdump output;
The grep -P can be useful however to just find files matrching a given binary pattern.
Or to do a binary query of a pattern that actually happens in text
(see for example How to regexp CJK ideographs (in utf-8) )
Maximum size of an Array in Javascript
I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.
WPF Datagrid Get Selected Cell Value
If you are selecting only one cell then get selected cell content like this
var cellInfo = dataGrid1.SelectedCells[0];
var content = cellInfo.Column.GetCellContent(cellInfo.Item);
Here content will be your selected cells value
And if you are selecting multiple cells then you can do it like this
var cellInfos = dataGrid1.SelectedCells;
var list1 = new List<string>();
foreach (DataGridCellInfo cellInfo in cellInfos)
{
if (cellInfo.IsValid)
{
//GetCellContent returns FrameworkElement
var content= cellInfo.Column.GetCellContent(cellInfo.Item);
//Need to add the extra lines of code below to get desired output
//get the datacontext from FrameworkElement and typecast to DataRowView
var row = (DataRowView)content.DataContext;
//ItemArray returns an object array with single element
object[] obj = row.Row.ItemArray;
//store the obj array in a list or Arraylist for later use
list1.Add(obj[0].ToString());
}
}
What is the meaning of @_ in Perl?
Also if a function returns an array, but the function is called without assigning its returned data to any variable like below. Here split() is called, but it is not assigned to any variable. We can access its returned data later through @_:
$str = "Mr.Bond|Chewbaaka|Spider-Man";
split(/\|/, $str);
print @_[0]; # 'Mr.Bond'
This will split the string $str
and set the array @_
.
How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker
Thanks for all. I got my expected output
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script>
$(function(){
$("#to").datepicker({ dateFormat: 'yy-mm-dd' });
$("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
minValue.setDate(minValue.getDate()+1);
$("#to").datepicker( "option", "minDate", minValue );
})
});
</script>
<div class="">
<p>From Date: <input type="text" id="from"></p>
<p>To Date: <input type="text" id="to"></p>
</div>
How to jump to top of browser page
Pure Javascript solution
theId.onclick = () => window.scrollTo({top: 0})
If you want smooth scrolling
theId.onclick = () => window.scrollTo({ top: 0, behavior: `smooth` })
Copy every nth line from one sheet to another
In A1 of your new sheet, put this:
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
This can be copied right too.
Is it a good idea to index datetime field in mysql?
MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.
Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).
Using the passwd command from within a shell script
I stumbled upon the same problem and for some reason the --stdin
option was not available on the version of passwd
I was using (shipped in Ubuntu 14.04).
If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd
command like this:
echo "<user>:<password>" | chpasswd
AngularJS ui-router login authentication
I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.
$urlRouterProvider.rule(function ($injector, $location) {
var UserService = $injector.get('UserService');
var path = $location.path(), normalized = path.toLowerCase();
if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
$location.path('/login/signin');
}
});
In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following
/login/signup // registering new user
/login/signin // login to app
so i have instant access to this two routes and every other route will be checked if you are online.
Here is my whole routing file for the login module
export default (
$stateProvider,
$locationProvider,
$urlRouterProvider
) => {
$stateProvider.state('login', {
parent: 'app',
url: '/login',
abstract: true,
template: '<ui-view></ui-view>'
})
$stateProvider.state('signin', {
parent: 'login',
url: '/signin',
template: '<login-signin-directive></login-signin-directive>'
});
$stateProvider.state('lock', {
parent: 'login',
url: '/lock',
template: '<login-lock-directive></login-lock-directive>'
});
$stateProvider.state('signup', {
parent: 'login',
url: '/signup',
template: '<login-signup-directive></login-signup-directive>'
});
$urlRouterProvider.rule(function ($injector, $location) {
var UserService = $injector.get('UserService');
var path = $location.path();
if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
$location.path('/login/signin');
}
});
$urlRouterProvider.otherwise('/error/not-found');
}
() => { /* code */ }
is ES6 syntax, use instead function() { /* code */ }
What to put in a python module docstring?
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
What is [Serializable] and when should I use it?
What is it?
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
Angular: Cannot find a differ supporting object '[object Object]'
I received this error in my code because I'd not run JSON.parse(result).
So my result was a string instead of an array of objects.
i.e. I got:
"[{},{}]"
instead of:
[{},{}]
import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
.then((value) => {
let servers: Server[] = JSON.parse(value) as Server[];
}
);
What does void do in java?
The reason the code will not work without void
is because the System.out.println(String string)
method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void
keyword in its signature.
You can see the documentation of the System.out.println here:
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29
To press the issue further, println is a classic example of a method which is performing computation as a "side effect."
Shell script - remove first and last quote (") from a variable
The easiest solution in Bash:
$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc
This is called substring expansion (see Gnu Bash Manual and search for ${parameter:offset:length}
). In this example it takes the substring from s
starting at position 1 and ending at the second last position. This is due to the fact that if length
is a negative value it is interpreted as a backwards running offset from the end of parameter
.
How to read GET data from a URL using JavaScript?
Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.
The a code below works and is still useful in situations where URLSearchParams
is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
Use as follows:
var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
which returns a an object like this:
{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}
So
parseURLParams("www.mints.com?name=something")
gives
{name: ["something"]}
EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.
How to get text from EditText?
If you are doing it before the setContentView()
method call, then the values will be null.
This will result in null:
super.onCreate(savedInstanceState);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
setContentView(R.layout.main_contacts);
while this will work fine:
super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
Automatically set appsettings.json for dev and release environments in asp.net core?
Create multiple appSettings.$(Configuration).json
files like:
appSettings.staging.json
appSettings.production.json
Create a pre-build event on the project which copies the respective file to appSettings.json
:
copy appSettings.$(Configuration).json appSettings.json
Use only appSettings.json
in your Config Builder:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Qt jpg image display
I understand your frustration the " Graphics view widget" is not the best way to do this, yes it can be done, but it's almost exactly the same as using a label ( for what you want any way) now all the ways listed do work but...
For you and any one else that may come across this question he easiest way to do it ( what you're asking any way ) is this.
QPixmap pix("Path\\path\\entername.jpeg");
ui->label->setPixmap(pix);
}
Common xlabel/ylabel for matplotlib subplots
Since I consider it relevant and elegant enough (no need to specify coordinates to place text), I copy (with a slight adaptation) an answer to another related question.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(5, 2, sharex=True, sharey=True, figsize=(6,15))
# add a big axis, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")
This results in the following (with matplotlib version 2.2.0):
How do I replace multiple spaces with a single space in C#?
I just wrote a new Join
that I like, so I thought I'd re-answer, with it:
public static string Join<T>(this IEnumerable<T> source, string separator)
{
return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}
One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
Push origin master error on new repository
I just had the same problem while creating my first Git repository ever. I had a typo in the Git origin remote creation - turns out I didn't capitalize the name of my repository.
git remote add origin [email protected]:Odd-engine
First I removed the old remote using
git remote rm origin
Then I recreated the origin, making sure the name of my origin was typed EXACTLY the same way my origin was spelled.
git remote add origin [email protected]:Odd-Engine
No more error! :)
no target device found android studio 2.1.1
go to "Run>edit configuration>" and select "Open select deployment target dialog" from deployment target option then run your app
it will show you a dialog box you can choose your target device from there,
enjoy it.
How to list all databases in the mongo shell?
I have found one solution, where admin()/others didn't worked.
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
var res = await exec('mongo --eval "db.adminCommand( { listDatabases: 1 }
)" --quiet')
return { res }
}
test()
.then(resp => {
console.log('All dbs', JSON.parse(resp.res.stdout).databases)
})
test()
INNER JOIN same table
I think the problem is in your JOIN
condition.
SELECT user.user_fname,
user.user_lname,
parent.user_fname,
parent.user_lname
FROM users AS user
JOIN users AS parent
ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]
Edit:
You should probably use LEFT JOIN
if there are users with no parents.
How to make program go back to the top of the code instead of closing
def start():
Offset = 5
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Please be sensible try just the lower case')
def getMessage():
print('Enter your message wanted to :')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (Offset))
key = int(input())
if (key >= 1 and key <= Offset):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
invalid use of incomplete type
The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case.
So what happens is that A<B>
is instantiated at
class B : public A<B>
at which point B
is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action
's declaration requires B
to be complete, because it is crawling in the scope of it:
Subclass::mytype
What you need to do is delaying the instantiation to some point at which B
is complete. One way of doing this is to modify the declaration of action
to make it a member template.
template<typename T>
void action(T var) {
(static_cast<Subclass*>(this))->do_action(var);
}
It is still type-safe because if var
is not of the right type, passing var
to do_action
will fail.
Retaining file permissions with Git
One addition to @Omid Ariyan's answer is permissions on directories. Add this after the for
loop's done
in his pre-commit
script.
for DIR in $(find ./ -mindepth 1 -type d -not -path "./.git" -not -path "./.git/*" | sed 's@^\./@@')
do
# Save the permissions of all the files in the index
echo $DIR";"`stat -c "%a;%U;%G" $DIR` >> $DATABASE
done
This will save directory permissions as well.
LIKE vs CONTAINS on SQL Server
The second (assuming you means CONTAINS
, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.
The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.
The CONTAINS
query should be:
SELECT * FROM table WHERE CONTAINS(Column, 'test');
Programmatically change UITextField Keyboard type
_textField .keyboardType = UIKeyboardTypeAlphabet;
_textField .keyboardType = UIKeyboardTypeASCIICapable;
_textField .keyboardType = UIKeyboardTypeDecimalPad;
_textField .keyboardType = UIKeyboardTypeDefault;
_textField .keyboardType = UIKeyboardTypeEmailAddress;
_textField .keyboardType = UIKeyboardTypeNamePhonePad;
_textField .keyboardType = UIKeyboardTypeNumberPad;
_textField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
_textField .keyboardType = UIKeyboardTypePhonePad;
_textField .keyboardType = UIKeyboardTypeTwitter;
_textField .keyboardType = UIKeyboardTypeURL;
_textField .keyboardType = UIKeyboardTypeWebSearch;
Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?
you should add
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
to
resources/android/xml/network_security_config.xml
like this
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config> </network-security-config>
HTML5 form validation pattern alphanumeric with spaces?
Use below code for HTML5 validation pattern alphanumeric without / with space :-
for HTML5 validation pattern alphanumeric without space :-
onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"
for HTML5 validation pattern alphanumeric with space :-
onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"
Obtain form input fields using jQuery?
Inspired by answers of Lance Rushing and Simon_Weaver, this is my favourite solution.
$('#myForm').submit( function( event ) {
var values = $(this).serializeArray();
// In my case, I need to fetch these data before custom actions
event.preventDefault();
});
The output is an array of objects, e.g.
[{name: "start-time", value: "11:01"}, {name: "end-time", value: "11:11"}]
With the code below,
var inputs = {};
$.each(values, function(k, v){
inputs[v.name]= v.value;
});
its final output would be
{"start-time":"11:01", "end-time":"11:01"}
How to INNER JOIN 3 tables using CodeIgniter
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();
Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.
Get Date Object In UTC format in Java
You can subtract the time zone difference from now.
final Calendar calendar = Calendar.getInstance();
final int utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long tempDate = new Date().getTime();
return new Date(tempDate - utcOffset);
How do detect Android Tablets in general. Useragent?
Xoom has the word Xoom in the user-agent: Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; Xoom Build/HRI66) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13
Galaxy Tab has "Mobile" in the user-agent: Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
So, it's easy to detect the Xoom, hard to detect if a specific Android version is mobile or not.
Get hostname of current request in node.js Express
If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:
var child_process = require("child_process");
child_process.exec("hostname -f", function(err, stdout, stderr) {
var hostname = stdout.trim();
});
Bash script to run php script
The bash script should be something like this:
#!/bin/bash
/usr/bin/php /path/to/php/file.php
You need the php executable (usually found in /usr/bin) and the path of the php script to be ran. Now you only have to put this bash script on crontab and you're done!
How to save and extract session data in codeigniter
You can set data to session simply like this in Codeigniter:
$this->load->library('session');
$this->session->set_userdata(array(
'user_id' => $user->uid,
'username' => $user->username,
'groupid' => $user->groupid,
'date' => $user->date_cr,
'serial' => $user->serial,
'rec_id' => $user->rec_id,
'status' => TRUE
));
and you can get it like this:
$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');
Safari 3rd party cookie iframe trick no longer working?
I tricked Safari with a .htaccess:
#http://www.w3.org/P3P/validator.html
<IfModule mod_headers.c>
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"NOI DSP COR NID CUR ADM DEV OUR BUS\""
Header set Set-Cookie "test_cookie=1"
</IfModule>
And it stopped working for me too. All my apps are losing the session in Safari and are redirecting out of Facebook. As I'm in a hurry to fix those apps, I'm currently searching for a solution. I'll keep you posted.
Edit (2012-04-06): Apparently Apple "fixed" it with 5.1.4. I'm sure this is the reaction to the Google-thing: "An issue existed in the enforcement of its cookie policy. Third-party websites could set cookies if the "Block Cookies" preference in Safari was set to the default setting of "From third parties and advertisers". http://support.apple.com/kb/HT5190
ipad safari: disable scrolling, and bounce effect?
You can use js for prevent scroll:
let body = document.body;
let hideScroll = function(e) {
e.preventDefault();
};
function toggleScroll (bool) {
if (bool === true) {
body.addEventListener("touchmove", hideScroll);
} else {
body.removeEventListener("touchmove", hideScroll);
}
}
And than just run/stop toggleScroll
func when you opnen/close modal.
Like this toggleScroll(true) / toggleScroll(false)
(This is only for iOS, on Android not working)
Multi-gradient shapes
You can layer gradient shapes in the xml using a layer-list.
Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)
<!-- Normal state. -->
<item>
<layer-list>
<item>
<shape>
<gradient
android:startColor="@color/grey_light"
android:endColor="@color/grey_dark"
android:type="linear"
android:angle="270"
android:centerColor="@color/grey_mediumtodark" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#00666666"
android:endColor="#77666666"
android:type="radial"
android:gradientRadius="200"
android:centerColor="#00666666"
android:centerX="0.5"
android:centerY="0" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
</layer-list>
</item>
Convert Long into Integer
The best simple way of doing so is:
public static int safeLongToInt( long longNumber )
{
if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE )
{
throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
}
return (int) longNumber;
}
Importing csv file into R - numeric values read as characters
Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R.
Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE)
. [If that does not work, please take a look at ?read.table
(which read.csv
wraps), however there may be some other underlying issue].
For example:
delim = "," # or is it "\t" ?
dec = "." # or is it "," ?
myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE)
Then, let's say your numeric columns is column 4
myDataFrame[, 4] <- as.numeric(myDataFrame[, 4]) # you can also refer to the column by "itsName"
Lastly, if you need any help with accomplishing in R the same tasks that you've done in Excel, there are plenty of folks here who would be happy to help you out
How to change Vagrant 'default' machine name?
This is the way I've assigned names to individual VMs. Change YOURNAMEHERE
to your desired name.
Contents of Vagrantfile:
Vagrant.configure("2") do |config|
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "precise32"
# The url from where the 'config.vm.box' box will be fetched if it
# doesn't already exist on the user's system.
config.vm.box_url = "http://files.vagrantup.com/precise32.box"
config.vm.define :YOURNAMEHERE do |t|
end
end
Terminal output:
$ vagrant status
Current machine states:
YOURNAMEHERE not created (virtualbox)
Replace multiple strings at once
You could use the replace method of the String
object with a function in the second parameter:
First Method (using a find and replace Object)
var findreplace = {"<" : "<", ">" : ">", "\n" : "<br/>"};
textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});
jsfiddle
Second method (using two arrays, find and replace)
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});
jsfiddle
Desired function:
function str_replace($f, $r, $s){
return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}
$textarea = str_replace($find, $replace, $textarea);
EDIT
This function
admits a String
or an Array
as parameters:
function str_replace($f, $r, $s){
return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}
How to serialize an Object into a list of URL query parameters?
Since I made such a big deal about a recursive function, here is my own version.
function objectParametize(obj, delimeter, q) {
var str = new Array();
if (!delimeter) delimeter = '&';
for (var key in obj) {
switch (typeof obj[key]) {
case 'string':
case 'number':
str[str.length] = key + '=' + obj[key];
break;
case 'object':
str[str.length] = objectParametize(obj[key], delimeter);
}
}
return (q === true ? '?' : '') + str.join(delimeter);
}
http://jsfiddle.net/userdude/Kk3Lz/2/
How to get base URL in Web API controller?
I inject this service into my controllers.
public class LinkFactory : ILinkFactory
{
private readonly HttpRequestMessage _requestMessage;
private readonly string _virtualPathRoot;
public LinkFactory(HttpRequestMessage requestMessage)
{
_requestMessage = requestMessage;
var configuration = _requestMessage.Properties[HttpPropertyKeys.HttpConfigurationKey] as HttpConfiguration;
_virtualPathRoot = configuration.VirtualPathRoot;
if (!_virtualPathRoot.EndsWith("/"))
{
_virtualPathRoot += "/";
}
}
public Uri ResolveApplicationUri(Uri relativeUri)
{
return new Uri(new Uri(new Uri(_requestMessage.RequestUri.GetLeftPart(UriPartial.Authority)), _virtualPathRoot), relativeUri);
}
}
Bootstrap 3 modal vertical position center
My solution
.modal-dialog-center {
margin-top: 25%;
}
<div id="waitForm" class="modal">
<div class="modal-dialog modal-dialog-center">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="headerBlock" class="modal-title"></h4>
</div>
<div class="modal-body">
<span id="bodyBlock"></span>
<br/>
<p style="text-align: center">
<img src="@Url.Content("~/Content/images/progress-loader.gif")" alt="progress"/>
</p>
</div>
</div>
</div>
</div>
Excel 2013 VBA Clear All Filters macro
Here is some code for fixing filters. For example, if you turn on filters in your sheet, then you add a column, then you want the new column to also be covered by a filter.
Private Sub AddOrFixFilters()
ActiveSheet.UsedRange.Select
' turn off filters if on, which forces a reset in case some columns weren't covered by the filter
If ActiveSheet.AutoFilterMode Then
Selection.AutoFilter
End If
' turn filters back on, auto-calculating the new columns to filter
Selection.AutoFilter
End Sub
How to use gitignore command in git
If you don't have a .gitignore file. You can create a new one by
touch .gitignore
And you can exclude a folder by entering the below command in the .gitignore file
/folderName
push this file into your git repository so that when a new person clone your project he don't have to add the same again
CSS: On hover show and hide different div's at the same time?
http://jsfiddle.net/MBLZx/
Here is the code
_x000D_
_x000D_
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
ggplot combining two plots from different data.frames
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
Creating Scheduled Tasks
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
Notepad++ Setting for Disabling Auto-open Previous Files
My problem was that Notepad++ was crashing on a file I had previously opened; I was unable to open the application at all. This blog post discusses how to delete the data from the "Sessions" file so that Notepad++ will open without having any prior files open:
From the blog post:
Method 1 - edit session.xml
- Open file session.xml in C:\Users\Username\AppData\Roaming\Notepad++ or %APPDATA%\Notepad++
- Delete its contents and save it
- Run Notepad++ , session.xml will get new content automatically
Method 2 - add the -nosession parameter to Notepad++ shortcut
- Create a desktop shortcut referring to your Notepad++ program, e.g. C:\Program Files\Notepad++\notepad++.exe
- Right click on this shortcut
- In the "Target" field add the -nosession parameter so the target field looks exaxtly like (apostrophes included too): "C:\Program
Files\Notepad++\notepad++.exe" -nosession
- Save and run Notepad++ from this shortcut icon with no recent files
Note: This is not a permanent setting, this simply deletes the prior session's information / opened files and starts over.
Alternatively, if you know the file which is causing notepad++ to hang, you can simply rename the file and open notepad++. This will solve the problem.
I hadn't seen this solution listed when I was googling my problem so I wanted to add it here!
How to change fonts in matplotlib (python)?
The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file.
Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):
import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()
print(fpath)
will show you where you should put the .ttf.
You can see the output here:
https://matplotlib.org/gallery/api/font_file.html
Get first element in PHP stdObject
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be
marked as correct, although my answer provides a hacked solution its not
the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)
[0]=>
object(stdClass)
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id;
If you need the key for some reason, you can do;
reset($obj);
$key = key($obj);
Hope that works for you. :-)
No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id;
$key = $objIterator->key();
How do I set default terminal to terminator?
Copy-paste the following into your current terminal:
gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"
This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.
What are bitwise shift (bit-shift) operators and how do they work?
Bit Masking & Shifting
Bit shifting is often used in low-level graphics programming. For example, a given pixel color value encoded in a 32-bit word.
Pixel-Color Value in Hex: B9B9B900
Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000
For better understanding, the same binary value labeled with what sections represent what color part.
Red Green Blue Alpha
Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000
Let's say for example we want to get the green value of this pixel's color. We can easily get that value by masking and shifting.
Our mask:
Red Green Blue Alpha
color : 10111001 10111001 10111001 00000000
green_mask : 00000000 11111111 00000000 00000000
masked_color = color & green_mask
masked_color: 00000000 10111001 00000000 00000000
The logical &
operator ensures that only the values where the mask is 1 are kept. The last thing we now have to do, is to get the correct integer value by shifting all those bits to the right by 16 places (logical right shift).
green_value = masked_color >>> 16
Et voilà, we have the integer representing the amount of green in the pixel's color:
Pixels-Green Value in Hex: 000000B9
Pixels-Green Value in Binary: 00000000 00000000 00000000 10111001
Pixels-Green Value in Decimal: 185
This is often used for encoding or decoding image formats like jpg
, png
, etc.
Bootstrap 3 dropdown select
;(function ($) {
$.fn.bootselect = function (options) {
this.each(function () {
var os = jQuery(this).find('option');
var parent = this.parentElement;
var css = jQuery(this).attr('class').split('input').join('btn').split('form-control').join('');
var vHtml = jQuery(this).find('option[value="' + jQuery(this).val() + '"]').html();
var html = '<div class="btn-group" role="group">' + '<button type="button" data-toggle="dropdown" value="1" class="btn btn-default ' + css + ' dropdown-toggle">' +
vHtml + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">';
var i = 0;
while (i < os.length) {
html += '<li><a href="#" data-value="' + jQuery(os[i]).val() + '" html-attr="' + jQuery(os[i]).html() + '">' + jQuery(os[i]).html() + '</a></li>';
i++;
}
html += '</ul>' + '</div>';
var that = this;
jQuery(parent).append(html);
jQuery(parent).find('ul.dropdown-menu > li > a').on('click', function () {
jQuery(parent).find('button.btn').html(jQuery(this).html() + '<span class="caret"></span>');
jQuery(that).find('option[value="' + jQuery(this).attr('data-value') + '"]')[0].selected = true;
jQuery(that).trigger('change');
});
jQuery(this).hide();
});
};
}(jQuery));
jQuery('.bootstrap-select').bootselect();
Python extending with - using super() Python 3 vs Python 2
In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__
. So if you don't define it in your class, you will get the one from the base.
Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__
, your class will inherit the first one only.
In such cases, you should really use super
if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).
If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super
):
class A:
def __init__(self):
print('A')
super().__init__()
class B:
def __init__(self):
print('B')
super().__init__()
class C(A, B):
pass
C()
#prints:
#A
#B
Notice how both base classes use super
even though they don't have their own base classes.
What super
does is: it calls the method from the next class in MRO (method resolution order). The MRO for C
is: (C, A, B, object)
. You can print C.__mro__
to see it.
So, C
inherits __init__
from A
and super
in A.__init__
calls B.__init__
(B
follows A
in MRO).
So by doing nothing in C
, you end up calling both, which is what you want.
Now if you were not using super
, you would end up inheriting A.__init__
(as before) but this time there's nothing that would call B.__init__
for you.
class A:
def __init__(self):
print('A')
class B:
def __init__(self):
print('B')
class C(A, B):
pass
C()
#prints:
#A
To fix that you have to define C.__init__
:
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
The problem with that is that in more complicated MI trees, __init__
methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.
What's the difference between compiled and interpreted language?
As other have said, compiled and interpreted are specific to an implementation of a programming language; they are not inherent in the language. For example, there are C interpreters.
However, we can (and in practice we do) classify programming languages based on its most common (sometimes canonical) implementation. For example, we say C is compiled.
First, we must define without ambiguity interpreters and compilers:
An interpreter for language X is a program
(or a machine, or just some kind of mechanism in general)
that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X.
A compiler from X to Y is a program
(or a machine, or just some kind of mechanism in general)
that translates any program p from some language X into
a semantically equivalent program p' in some language Y in such a way that interpreting p' with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X.
Notice that from a programmer point of view, CPUs are machine interpreters for their respective native machine language.
Now, we can do a tentative classification of programming languages into 3 categories depending on its most common implementation:
- Hard Compiled languages: When the programs are compiled entirely to machine language. The only interpreter used is a CPU. Example: Usually, to run a program in C, the source code is compiled to machine language, which is then executed by a CPU.
- Interpreted languages: When there is no compilation of any part of the original program to machine language. In other words, no new machine code is generated; only existing machine code is executed. An interpreter other than the CPU must also be used (usually a program).Example: In the canonical implementation of Python, the source code is compiled first to Python bytecode and then that bytecode is executed by CPython, an interpreter program for Python bytecode.
- Soft Compiled languages: When an interpreter other than the CPU is used but also parts of the original program may be compiled to machine language. This is the case of Java, where the source code is compiled to bytecode first and then, the bytecode may be interpreted by the Java Interpreter and/or further compiled by the JIT compiler.
Sometimes, soft and hard compiled languages are refered to simply compiled, thus C#, Java, C, C++ are said to be compiled.
Within this categorization, JavaScript used to be an interpreted language, but that was many years ago. Nowadays, it is JIT-compiled to native machine language in most major JavaScript implementations so I would say that it falls into soft compiled languages.
Convert stdClass object to array in PHP
Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.
Take that result and decode with an extra parameter of true, where it will convert to associative array
$array = json_decode(json_encode($oObject),true);
How to add \newpage in Rmarkdown in a smart way?
In the initialization chunk I define a function
pagebreak <- function() {
if(knitr::is_latex_output())
return("\\newpage")
else
return('<div style="page-break-before: always;" />')
}
In the markdown part where I want to insert a page break, I type
`r pagebreak()`
Sending data through POST request from a node.js server to a node.js server
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
How to return a specific element of an array?
(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:
array3[i]=e1
Also the findOut method doesn't return any value if the array length is 0. Adding a return 0;
at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.
How do I update a GitHub forked repository?
Actually, it is possible to create a branch in your fork from any commit of the upstream in the browser:
You can then fetch that branch to your local clone, and you won't have to push all that data back to GitHub when you push edits on top of that commit. Or use the web interface to change something in that branch.
How it works (it is a guess, I don't know how exactly GitHub does it): forks share object storage and use namespaces to separate users' references. So you can access all commits through your fork, even if they did not exist by the time of forking.
What is the difference between square brackets and parentheses in a regex?
Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.
/^(7|8|9)\d{9}$/
What this does:
^
and $
denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
()
denotes a capturing group.
7|8|9
denotes matching either of 7
, 8
, or 9
. It does this with alternations, which is what the pipe operator |
does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat
Pattern: [rf]at
Match string: carat
\d{9}
matches nine digits. \d
is a shorthanded metacharacter, which matches any digits.
/^[7|8|9][\d]{9}$/
Look at what it does:
^
and $
denotes anchored matches as well.
[7|8|9]
is a character class. Any characters from the list 7
, |
, 8
, |
, or 9
can be matched, thus the |
was added in incorrectly. This matches without backtracking.
[\d]
is a character class that inhabits the metacharacter \d
. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
{9}
indicates the previous single construct is repeated nine times in total.
The optimal regex is /^[789]\d{9}$/
, because /^(7|8|9)\d{9}$/
captures unnecessarily which imposes a performance decrease on most regex implementations (javascript happens to be one, considering the question uses keyword var
in code, this probably is JavaScript). The use of php which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes []
instead of alternations |
gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.
Angular - How to apply [ngStyle] conditions
<ion-col size="12">
<ion-card class="box-shadow ion-text-center background-size"
*ngIf="data != null"
[ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">
</ion-card>
How to verify CuDNN installation?
Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.
You can check that using cmake
. Create a directory caffe/build
and run cmake ..
from there. If the configuration is correct you will see these lines:
-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so)
-- NVIDIA CUDA:
-- Target GPU(s) : Auto
-- GPU arch(s) : sm_30
-- cuDNN : Yes
If everything is correct just run the make
orders to install caffe from there.
Break or return from Java 8 stream forEach?
Update with Java 9+ with takeWhile
:
MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
// doing something.
if (...) { // want to break;
ongoing.setFalse();
}
});
Count(*) vs Count(1) - SQL Server
As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.
SELECT COUNT(*) FROM something
counts records which is an easy task.
SELECT COUNT(1) FROM something
retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.
Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.
However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.
Android Studio: Add jar as library?
Unlike Eclipse we don't need to download jar and put it in /libs folder. Gradle handles these things we only need to add Gradle dependencies, Gradle downloads it and puts in gradle cache.
We need to add dependencies as:
dependencies {implementation 'com.google.code.gson:gson:2.2.4'}
thats it
However we can also download jar & add that as library but the best practice is to add Gradle dependencies.
How to store Emoji Character in MySQL Database
Both the databases and tables should have character set utf8mb4
and collation utf8mb4_unicode_ci
.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci
is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
Getting a Request.Headers value
Header exists:
if (Request.Headers["XYZComponent"] != null)
or even better:
string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;
if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)
which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse
does work on null
)
Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.
public static bool? ToBoolean(this string s)
{
bool result;
if (bool.TryParse(s, out result))
return result;
else
return null;
}
Usage (because this is an extension method and not instance method this will not throw an exception on null
- it may be confusing, though):
if (Request.Headers["XYZComponent"].ToBoolean() == true)
How to use jQuery with TypeScript
You can declare globals by augmenting the window interface:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
Sources:
What is ANSI format?
Strictly speaking, there is no such thing as ANSI encoding. Colloquially the term ANSI is used for several different encodings:
- ISO 8859-1
- Windows CP1252
- Current system encoding on a Windows machine (in Win32 API terminology).
Converting URL to String and back again
2020 | SWIFT 5.1:
From STRING to URL:
let url = URL(fileURLWithPath: "//Users/Me/Desktop/Doc.txt")
From URL to STRING:
let a = String(describing: url) // "file:////Users/Me/Desktop/Doc.txt"
let b = "\(url)" // "file:////Users/Me/Desktop/Doc.txt"
let c = url.absoluteString // "file:////Users/Me/Desktop/Doc.txt"
let d = url.path // "/Users/Me/Desktop/Doc.txt"
BUT value of d
will be invisible due to debug process, so...
THE BEST SOLUTION:
let e = "\(url.path)" // "/Users/Me/Desktop/Doc.txt"
Changing the CommandTimeout in SQL Management studio
If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers
This will get rid of this message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
SELECT INTO USING UNION QUERY
select *
into new_table
from table_A
UNION
Select *
From table_B
This only works if Table_A and Table_B have the same schemas
Get Android shared preferences value in activity/normal class
If you have a SharedPreferenceActivity by which you have saved your values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
and this is how you can retrieve the values.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.
mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
How does the "position: sticky;" property work?
I had to use the following CSS to get it working:
.parent {
display: flex;
justify-content: space-around;
align-items: flex-start;
overflow: visible;
}
.sticky {
position: sticky;
position: -webkit-sticky;
top: 0;
}
If above dosen't work then...
Go through all ancestors and make sure none of these elements have overflow: hidden
. You have to change this to overflow: visible
Handle spring security authentication exceptions with @ExceptionHandler
Update: If you like and prefer to see the code directly, then I have two examples for you, one using standard Spring Security which is what you are looking for, the other one is using the equivalent of Reactive Web and Reactive Security:
- Normal Web + Jwt Security
- Reactive Jwt
The one that I always use for my JSON based endpoints looks like the following:
@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
@Autowired
ObjectMapper mapper;
private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e)
throws IOException, ServletException {
// Called when the user tries to access an endpoint which requires to be authenticated
// we just return unauthorizaed
logger.error("Unauthorized error. Message - {}", e.getMessage());
ServletServerHttpResponse res = new ServletServerHttpResponse(response);
res.setStatusCode(HttpStatus.UNAUTHORIZED);
res.getServletResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
res.getBody().write(mapper.writeValueAsString(new ErrorResponse("You must authenticated")).getBytes());
}
}
The object mapper becomes a bean once you add the spring web starter, but I prefer to customize it, so here is my implementation for ObjectMapper:
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.modules(new JavaTimeModule());
// for example: Use created_at instead of createdAt
builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// skip null fields
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return builder;
}
The default AuthenticationEntryPoint you set in your WebSecurityConfigurerAdapter class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ............
@Autowired
private JwtAuthEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
// .antMatchers("/api/auth**", "/api/login**", "**").permitAll()
.anyRequest().permitAll()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.headers().frameOptions().disable(); // otherwise H2 console is not available
// There are many ways to ways of placing our Filter in a position in the chain
// You can troubleshoot any error enabling debug(see below), it will print the chain of Filters
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
// ..........
}
calling another method from the main method in java
You can only call instance method like do()
(which is an illegal method name, incidentally) against an instance of the class:
public static void main(String[] args){
new Foo().doSomething();
}
public void doSomething(){}
Alternatively, make doSomething()
static as well, if that works for your design.
Reactjs: Unexpected token '<' Error
Although, I had all proper babel loaders in my .babelrc config file. This build script with parcel-bundler was producing the unexpected token error < and mime type errors in the browser console for me on manual page refresh.
"scripts": {
"build": "parcel build ui/index.html --public-url ./",
"dev": "parcel watch ui/index.html"
}
Updating the build script fixed the issues for me.
"scripts": {
"build": "parcel build ui/index.html",
"ui": "parcel watch ui/index.html"
}
What to do with "Unexpected indent" in python?
Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.
While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.
Check if value already exists within list of dictionaries?
Based on @Mark Byers great answer, and following @Florent question,
just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:
names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})
if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):
print('Not exists!')
else:
print('Exists!')
Result:
Exists!
How to: "Separate table rows with a line"
You have to use CSS.
In my opinion when you have a table often it is good with a separate line each side of the line.
Try this code:
HTML:
<table>
<tr class="row"><td>row 1</td></tr>
<tr class="row"><td>row 2</td></tr>
</table>
CSS:
.row {
border:1px solid black;
}
Bye
Andrea
How to compare each item in a list with the rest, only once?
Your solution is correct, but your outer loop is still longer than needed. You don't need to compare the last element with anything else because it's been already compared with all the others in the previous iterations. Your inner loop still prevents that, but since we're talking about collision detection you can save the unnecessary check.
Using the same language you used to illustrate your algorithm, you'd come with something like this:
for (int i = 0, i < mylist.size() - 1; ++i)
for (int j = i + 1, j < mylist.size(); --j)
compare(mylist[i], mylist[j])
How to force a html5 form validation without submitting it via jQuery
May be late to the party but yet somehow I found this question while trying to solve similar problem. As no code from this page worked for me, meanwhile I came up with solution that works as specified.
Problem is when your <form>
DOM contain single <button>
element, once fired, that <button>
will automatically sumbit form. If you play with AJAX, You probably need to prevent default action. But there is a catch: If you just do so, You will also prevent basic HTML5 validation. Therefore, it is good call to prevent defaults on that button only if the form is valid. Otherwise, HTML5 validation will protect You from submitting. jQuery checkValidity()
will help with this:
jQuery:
$(document).ready(function() {
$('#buttonID').on('click', function(event) {
var isvalidate = $("#formID")[0].checkValidity();
if (isvalidate) {
event.preventDefault();
// HERE YOU CAN PUT YOUR AJAX CALL
}
});
});
Code described above will allow You to use basic HTML5 validation (with type and pattern matching) WITHOUT submitting form.
Hide Twitter Bootstrap nav collapse on click
Another quick solution for Bootstrap 3.* could be:
$( document ).ready(function() {
//
// Hide collapsed menu on click
//
$('.nav a').each(function (idx, obj) {
var selected = $(obj);
selected.on('click', function() {
if (selected.closest('.collapse.in').length > 0) {
$('.navbar-toggle').click(); //bootstrap 3.x by Richard
}
});
});
});
Null vs. False vs. 0 in PHP
In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.
Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.
Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.
How to save S3 object to a file using boto3
boto3 now has a nicer interface than the client:
resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)
This by itself isn't tremendously better than the client
in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.
Resources
generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.
List all kafka topics
For dockerized kafka/zookeeper
docker ps
find you zookeeper container id
docker exec -it <id> bash
cd bin
./zkCli.sh
ls /brokers/topics
how to use DEXtoJar
- Download Dex2jar and Extract it.
- Go to Download path
./d2j-dex2jar.sh /path-to-your/someApk.apk
if .sh is not compilable, update the permission: chmod a+x d2j-dex2jar.sh.
- It will generate .jar file.
- Now use the jar with JD-GUI to decompile it
React / JSX Dynamic Component Name
There is an official documentation about how to handle such situations is available here: https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime
Basically it says:
Wrong:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Wrong! JSX type can't be an expression.
return <components[props.storyType] story={props.story} />;
}
Correct:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Correct! JSX type can be a capitalized variable.
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
How to check if a String is numeric in Java
Parallel checking for very long strings using IntStream
In Java 8, the following tests if all characters of the given string
are within '0' to '9'. Mind that the empty string is accepted:
string.chars().unordered().parallel().allMatch( i -> '0' <= i && '9' >= i )
Disabling submit button until all fields have values
Grave digging... I like a different approach:
elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)
checkStatus = (e) =>
elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
filled = $.grep(elems, (n) -> n)
bool = elems.size() != $(filled).size()
$('input:submit').attr('disabled', bool)
Why doesn't the Scanner class have a nextChar method?
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation.
Source
You can use (char) System.in.read();
.
Bundling data files with PyInstaller (--onefile)
I found the existing answers confusing, and took a long time to work out where the problem is. Here's a compilation of everything I found.
When I run my app, I get an error Failed to execute script foo
(if foo.py
is the main file). To troubleshoot this, don't run PyInstaller with --noconsole
(or edit main.spec
to change console=False
=> console=True
). With this, run the executable from a command-line, and you'll see the failure.
The first thing to check is that it's packaging up your extra files correctly. You should add tuples like ('x', 'x')
if you want the folder x
to be included.
After it crashes, don't click OK. If you're on Windows, you can use Search Everything. Look for one of your files (eg. sword.png
). You should find the temporary path where it unpacked the files (eg. C:\Users\ashes999\AppData\Local\Temp\_MEI157682\images\sword.png
). You can browse this directory and make sure it included everything. If you can't find it this way, look for something like main.exe.manifest
(Windows) or python35.dll
(if you're using Python 3.5).
If the installer includes everything, the next likely problem is file I/O: your Python code is looking in the executable's directory, instead of the temp directory, for files.
To fix that, any of the answers on this question work. Personally, I found a mixture of them all to work: change directory conditionally first thing in your main entry-point file, and everything else works as-is:
if hasattr(sys, '_MEIPASS'):
os.chdir(sys._MEIPASS)
Makefile If-Then Else and Loops
Here's an example if:
ifeq ($(strip $(OS)),Linux)
PYTHON = /usr/bin/python
FIND = /usr/bin/find
endif
Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.
Difference between $(document.body) and $('body')
I have found a pretty big difference in timing when testing in my browser.
I used the following script:
WARNING: running this will freeze your browser a bit, might even crash it.
_x000D_
_x000D_
var n = 10000000, i;_x000D_
i = n;_x000D_
console.time('selector');_x000D_
while (i --> 0){_x000D_
$("body");_x000D_
}_x000D_
_x000D_
console.timeEnd('selector');_x000D_
_x000D_
i = n;_x000D_
console.time('element');_x000D_
while (i --> 0){_x000D_
$(document.body);_x000D_
}_x000D_
_x000D_
console.timeEnd('element');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_
I did 10 million interactions, and those were the results (Chrome 65):
selector: 19591.97509765625ms
element: 4947.8759765625ms
Passing the element directly is around 4 times faster than passing the selector.
Laravel 5: Display HTML with Blade
On controller.
$your_variable = '';
$your_variable .= '<p>Hello world</p>';
return view('viewname')->with('your_variable', $your_variable)
If you do not want your data to be escaped, you may use the following syntax:
{!! $your_variable !!}
Output
Hello world
Absolute vs relative URLs
In most instances relative URLs are the way to go, they are portable by nature, which means if you wanted to lift your site and put it someone where else it would work instantly, reducing possibly hours of debugging.
There is a pretty decent article on absolute vs relative URLs, check it out.
How to save data file into .RData?
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
How to check which locks are held on a table
You can find blocking sql and wait sql by running this:
SELECT
t1.resource_type ,
DB_NAME( resource_database_id) AS dat_name ,
t1.resource_associated_entity_id,
t1.request_mode,
t1.request_session_id,
t2.wait_duration_ms,
( SELECT TEXT FROM sys.dm_exec_requests r CROSS apply sys.dm_exec_sql_text ( r.sql_handle ) WHERE r.session_id = t1.request_session_id ) AS wait_sql,
t2.blocking_session_id,
( SELECT TEXT FROM sys.sysprocesses p CROSS apply sys.dm_exec_sql_text ( p.sql_handle ) WHERE p.spid = t2.blocking_session_id ) AS blocking_sql
FROM
sys.dm_tran_locks t1,
sys.dm_os_waiting_tasks t2
WHERE
t1.lock_owner_address = t2.resource_address
How to add property to object in PHP >= 5.3 strict mode without generating error
you should use magic methods __Set and __get. Simple example:
class Foo
{
//This array stores your properties
private $content = array();
public function __set($key, $value)
{
//Perform data validation here before inserting data
$this->content[$key] = $value;
return $this;
}
public function __get($value)
{ //You might want to check that the data exists here
return $this->$content[$value];
}
}
Of course, don't use this example as this : no security at all :)
EDIT : seen your comments, here could be an alternative based on reflection and a decorator :
class Foo
{
private $content = array();
private $stdInstance;
public function __construct($stdInstance)
{
$this->stdInstance = $stdInstance;
}
public function __set($key, $value)
{
//Reflection for the stdClass object
$ref = new ReflectionClass($this->stdInstance);
//Fetch the props of the object
$props = $ref->getProperties();
if (in_array($key, $props)) {
$this->stdInstance->$key = $value;
} else {
$this->content[$key] = $value;
}
return $this;
}
public function __get($value)
{
//Search first your array as it is faster than using reflection
if (array_key_exists($value, $this->content))
{
return $this->content[$value];
} else {
$ref = new ReflectionClass($this->stdInstance);
//Fetch the props of the object
$props = $ref->getProperties();
if (in_array($value, $props)) {
return $this->stdInstance->$value;
} else {
throw new \Exception('No prop in here...');
}
}
}
}
PS : I didn't test my code, just the general idea...
How to perform runtime type checking in Dart?
There are two operators for type testing: E is T
tests for E an instance of type T while E is! T
tests for E not an instance of type T.
Note that E is Object
is always true, and null is T
is always false unless T===Object
.
How can I create a text box for a note in markdown?
Have you tried using double tabs? To make a box:
Start on a fresh line
Hit tab twice, type up the content
Your content should appear in a box
It works for me in a regular Rmarkdown document with html output. The double-tabbed portion should appear in a rounded rectangular light grey box.