Call an overridden method from super class in typescript
The order of execution is:
A
's constructor
B
's constructor
The assignment occurs in B
's constructor after A
's constructor—_super
—has been called:
function B() {
_super.apply(this, arguments); // MyvirtualMethod called in here
this.testString = "Test String"; // testString assigned here
}
So the following happens:
var b = new B(); // undefined
b.MyvirtualMethod(); // "Test String"
You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod()
in B
's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A
's constructor and working that out somehow... there's lots of possibilities.
What is the relative performance difference of if/else versus switch statement in Java?
In my test the better performance is ENUM > MAP > SWITCH > IF/ELSE IF in Windows7.
import java.util.HashMap;
import java.util.Map;
public class StringsInSwitch {
public static void main(String[] args) {
String doSomething = null;
//METHOD_1 : SWITCH
long start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
switch (input) {
case "Hello World0":
doSomething = "Hello World0";
break;
case "Hello World1":
doSomething = "Hello World0";
break;
case "Hello World2":
doSomething = "Hello World0";
break;
case "Hello World3":
doSomething = "Hello World0";
break;
case "Hello World4":
doSomething = "Hello World0";
break;
case "Hello World5":
doSomething = "Hello World0";
break;
case "Hello World6":
doSomething = "Hello World0";
break;
case "Hello World7":
doSomething = "Hello World0";
break;
case "Hello World8":
doSomething = "Hello World0";
break;
case "Hello World9":
doSomething = "Hello World0";
break;
case "Hello World10":
doSomething = "Hello World0";
break;
case "Hello World11":
doSomething = "Hello World0";
break;
case "Hello World12":
doSomething = "Hello World0";
break;
case "Hello World13":
doSomething = "Hello World0";
break;
case "Hello World14":
doSomething = "Hello World0";
break;
case "Hello World15":
doSomething = "Hello World0";
break;
}
}
System.out.println("Time taken for String in Switch :"+ (System.currentTimeMillis() - start));
//METHOD_2 : IF/ELSE IF
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
if(input.equals("Hello World0")){
doSomething = "Hello World0";
} else if(input.equals("Hello World1")){
doSomething = "Hello World0";
} else if(input.equals("Hello World2")){
doSomething = "Hello World0";
} else if(input.equals("Hello World3")){
doSomething = "Hello World0";
} else if(input.equals("Hello World4")){
doSomething = "Hello World0";
} else if(input.equals("Hello World5")){
doSomething = "Hello World0";
} else if(input.equals("Hello World6")){
doSomething = "Hello World0";
} else if(input.equals("Hello World7")){
doSomething = "Hello World0";
} else if(input.equals("Hello World8")){
doSomething = "Hello World0";
} else if(input.equals("Hello World9")){
doSomething = "Hello World0";
} else if(input.equals("Hello World10")){
doSomething = "Hello World0";
} else if(input.equals("Hello World11")){
doSomething = "Hello World0";
} else if(input.equals("Hello World12")){
doSomething = "Hello World0";
} else if(input.equals("Hello World13")){
doSomething = "Hello World0";
} else if(input.equals("Hello World14")){
doSomething = "Hello World0";
} else if(input.equals("Hello World15")){
doSomething = "Hello World0";
}
}
System.out.println("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
//METHOD_3 : MAP
//Create and build Map
Map<String, ExecutableClass> map = new HashMap<String, ExecutableClass>();
for (int i = 0; i <= 15; i++) {
String input = "Hello World" + (i & 0xF);
map.put(input, new ExecutableClass(){
public void execute(String doSomething){
doSomething = "Hello World0";
}
});
}
//Start test map
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
map.get(input).execute(doSomething);
}
System.out.println("Time taken for String in Map :"+ (System.currentTimeMillis() - start));
//METHOD_4 : ENUM (This doesn't use muliple string with space.)
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "HW" + (i & 0xF);
HelloWorld.valueOf(input).execute(doSomething);
}
System.out.println("Time taken for String in ENUM :"+ (System.currentTimeMillis() - start));
}
}
interface ExecutableClass
{
public void execute(String doSomething);
}
// Enum version
enum HelloWorld {
HW0("Hello World0"), HW1("Hello World1"), HW2("Hello World2"), HW3(
"Hello World3"), HW4("Hello World4"), HW5("Hello World5"), HW6(
"Hello World6"), HW7("Hello World7"), HW8("Hello World8"), HW9(
"Hello World9"), HW10("Hello World10"), HW11("Hello World11"), HW12(
"Hello World12"), HW13("Hello World13"), HW14("Hello World4"), HW15(
"Hello World15");
private String name = null;
private HelloWorld(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
doSomething = "Hello World0";
}
public static HelloWorld fromString(String input) {
for (HelloWorld hw : HelloWorld.values()) {
if (input.equals(hw.getName())) {
return hw;
}
}
return null;
}
}
//Enum version for betterment on coding format compare to interface ExecutableClass
enum HelloWorld1 {
HW0("Hello World0") {
public void execute(String doSomething){
doSomething = "Hello World0";
}
},
HW1("Hello World1"){
public void execute(String doSomething){
doSomething = "Hello World0";
}
};
private String name = null;
private HelloWorld1(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
// super call, nothing here
}
}
/*
* http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
* https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10
* http://forums.xkcd.com/viewtopic.php?f=11&t=33524
*/
Saving a select count(*) value to an integer (SQL Server)
If @myInt is zero it means no rows in the table: it would be NULL if never set at all.
COUNT will always return a row, even for no rows in a table.
Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?
Your count/assign is correct but could be either way:
select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)
However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:
IF NOT EXISTS (SELECT * FROM myTable)
Request UAC elevation from within a Python script?
This is mostly an upgrade to Jorenko's answer, that allows to use parameters with spaces in Windows, but should also work fairly well on Linux :)
Also, will work with cx_freeze or py2exe since we don't use __file__
but sys.argv[0]
as executable
import sys,ctypes,platform
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
raise False
if __name__ == '__main__':
if platform.system() == "Windows":
if is_admin():
main(sys.argv[1:])
else:
# Re-run the program with admin rights, don't use __file__ since py2exe won't know about it
# Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters
lpParameters = ""
# Litteraly quote all parameters which get unquoted when passed to python
for i, item in enumerate(sys.argv[0:]):
lpParameters += '"' + item + '" '
try:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, lpParameters , None, 1)
except:
sys.exit(1)
else:
main(sys.argv[1:])
Simulate delayed and dropped packets on Linux
For dropped packets I would simply use iptables and the statistic module.
iptables -A INPUT -m statistic --mode random --probability 0.01 -j DROP
Above will drop an incoming packet with a 1% probability. Be careful, anything above about 0.14 and most of you tcp connections will most likely stall completely.
Take a look at man iptables and search for "statistic" for more information.
Creating a pandas DataFrame from columns of other DataFrames with similar indexes
Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )
# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()
df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
index = Index)
df3
how to set active class to nav menu from twitter bootstrap
You can use this JavaScript\jQuery
code:
// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');
It'll set the <a>
's parent <li>
and the <li>
's parent <ul>
as active.
A simple solution that works!
Original source:
Bootstrap add active class to li
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
If you are using Entity Framework version >= 5 then applying the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] annotation to your DateTime properties of your class will allow the database table's trigger to do its job of entering dates for record creation and record updating without causing your Entity Framework code to gag.
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateCreated { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateUpdated { get; set; }
This is similar to the 6th answer, written by Dongolo Jeno and Edited by Gille Q.
How to efficiently remove duplicates from an array without using Set
package javaa;
public class UniqueElementinAnArray
{
public static void main(String[] args)
{
int[] a = {10,10,10,10,10,100};
int[] output = new int[a.length];
int count = 0;
int num = 0;
//Iterate over an array
for(int i=0; i<a.length; i++)
{
num=a[i];
boolean flag = check(output,num);
if(flag==false)
{
output[count]=num;
++count;
}
}
//print the all the elements from an array except zero's (0)
for (int i : output)
{
if(i!=0 )
System.out.print(i+" ");
}
}
/***
* If a next number from an array is already exists in unique array then return true else false
* @param arr Unique number array. Initially this array is an empty.
* @param num Number to be search in unique array. Whether it is duplicate or unique.
* @return true: If a number is already exists in an array else false
*/
public static boolean check(int[] arr, int num)
{
boolean flag = false;
for(int i=0;i<arr.length; i++)
{
if(arr[i]==num)
{
flag = true;
break;
}
}
return flag;
}
}
HTML5 Video not working in IE 11
I've been having similar issues of a video not playing in IE11 on Windows 8.1. What I didn't realize was that I was running an N version of Windows, meaning no media features were installed. After installing the Media Feature Pack for N and KN versions of Windows 8.1 and rebooting my PC it was working fine.
As a side-note, the video worked fine in Chrome, Firefox, etc, since those browsers properly fell back to the webm
file.
For Restful API, can GET method use json data?
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).
I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1¶m2=val2
) or JSON (parsed by your API upon receipt)
Linux command line howto accept pairing for bluetooth device without pin
Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.
Here is how one might go about connecting to a device:
# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0: Type: BR/EDR Bus: USB
BD Address: AA:BB:CC:DD:EE:FF ACL MTU: 1021:8 SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
00:11:22:33:44:55 My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup
This would establish a serial connection to the device.
Python: Random numbers into a list
Fix the indentation of the print
statement
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
struct.error: unpack requires a string argument of length 4
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
How to initialize a static array?
If you are creating an array then there is no difference, however, the following is neater:
String[] suit = {
"spades",
"hearts",
"diamonds",
"clubs"
};
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"});
myMethod({"spades", "hearts"}); //won't compile!
Safely remove migration In Laravel
I agree with the current answers, I just wanna add little more information.
A new feature has been added to Laravel 5.3 and above version that will allow you to back out a single migration:
php artisan migrate:rollback --step=1
after, Manually delete the migration file under database/migrations/my_migration_file_name.php
This is a great feature for when you run a migration
In this way, you can safely remove the migration in laravel only in 2 step
Cycles in family tree software
Another mock serious answer for a silly question:
The real answer is, use an appropriate data structure. Human genealogy cannot fully be expressed using a pure tree with no cycles. You should use some sort of graph. Also, talk to an anthropologist before going any further with this, because there are plenty of other places similar errors could be made trying to model genealogy, even in the most simple case of "Western patriarchal monogamous marriage."
Even if we want to ignore locally taboo relationships as discussed here, there are plenty of perfectly legal and completely unexpected ways to introduce cycles into a family tree.
For example: http://en.wikipedia.org/wiki/Cousin_marriage
Basically, cousin marriage is not only common and expected, it is the reason humans have gone from thousands of small family groups to a worldwide population of 6 billion. It can't work any other way.
There really are very few universals when it comes to genealogy, family and lineage. Almost any strict assumption about norms suggesting who an aunt can be, or who can marry who, or how children are legitimized for the purpose of inheritance, can be upset by some exception somewhere in the world or history.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Does Java support structs?
Java 14 has added support for Records, which are structured data types that are very easy to build.
You can declare a Java record like this:
public record AuditInfo(
LocalDateTime createdOn,
String createdBy,
LocalDateTime updatedOn,
String updatedBy
) {}
public record PostInfo(
Long id,
String title,
AuditInfo auditInfo
) {}
And, the Java compiler will generate the following Java class associated to the AuditInfo
Record:
public final class PostInfo
extends java.lang.Record {
private final java.lang.Long id;
private final java.lang.String title;
private final AuditInfo auditInfo;
public PostInfo(
java.lang.Long id,
java.lang.String title,
AuditInfo auditInfo) {
/* compiled code */
}
public java.lang.String toString() { /* compiled code */ }
public final int hashCode() { /* compiled code */ }
public final boolean equals(java.lang.Object o) { /* compiled code */ }
public java.lang.Long id() { /* compiled code */ }
public java.lang.String title() { /* compiled code */ }
public AuditInfo auditInfo() { /* compiled code */ }
}
public final class AuditInfo
extends java.lang.Record {
private final java.time.LocalDateTime createdOn;
private final java.lang.String createdBy;
private final java.time.LocalDateTime updatedOn;
private final java.lang.String updatedBy;
public AuditInfo(
java.time.LocalDateTime createdOn,
java.lang.String createdBy,
java.time.LocalDateTime updatedOn,
java.lang.String updatedBy) {
/* compiled code */
}
public java.lang.String toString() { /* compiled code */ }
public final int hashCode() { /* compiled code */ }
public final boolean equals(java.lang.Object o) { /* compiled code */ }
public java.time.LocalDateTime createdOn() { /* compiled code */ }
public java.lang.String createdBy() { /* compiled code */ }
public java.time.LocalDateTime updatedOn() { /* compiled code */ }
public java.lang.String updatedBy() { /* compiled code */ }
}
Notice that the constructor, accessor methods, as well as equals
, hashCode
, and toString
are created for you, so it's very convenient to use Java Records.
A Java Record can be created like any other Java object:
PostInfo postInfo = new PostInfo(
1L,
"High-Performance Java Persistence",
new AuditInfo(
LocalDateTime.of(2016, 11, 2, 12, 0, 0),
"Vlad Mihalcea",
LocalDateTime.now(),
"Vlad Mihalcea"
)
);
Hadoop "Unable to load native-hadoop library for your platform" warning
I assume you're running Hadoop on 64bit CentOS. The reason you saw that warning is the native Hadoop library $HADOOP_HOME/lib/native/libhadoop.so.1.0.0
was actually compiled on 32 bit.
Anyway, it's just a warning, and won't impact Hadoop's functionalities.
Here is the way if you do want to eliminate this warning, download the source code of Hadoop and recompile libhadoop.so.1.0.0
on 64bit system, then replace the 32bit one.
Steps on how to recompile source code are included here for Ubuntu:
Good luck.
jQuery: How to get the HTTP status code from within the $.ajax.error method?
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
What is Dependency Injection?
The whole point of Dependency Injection (DI) is to keep application source code clean and stable:
- clean of dependency initialization code
- stable regardless of dependency used
Practically, every design pattern separates concerns to make future changes affect minimum files.
The specific domain of DI is delegation of dependency configuration and initialization.
Example: DI with shell script
If you occasionally work outside of Java, recall how source
is often used in many scripting languages (Shell, Tcl, etc., or even import
in Python misused for this purpose).
Consider simple dependent.sh
script:
#!/bin/sh
# Dependent
touch "one.txt" "two.txt"
archive_files "one.txt" "two.txt"
The script is dependent: it won't execute successfully on its own (archive_files
is not defined).
You define archive_files
in archive_files_zip.sh
implementation script (using zip
in this case):
#!/bin/sh
# Dependency
function archive_files {
zip files.zip "$@"
}
Instead of source
-ing implementation script directly in the dependent one, you use an injector.sh
"container" which wraps both "components":
#!/bin/sh
# Injector
source ./archive_files_zip.sh
source ./dependent.sh
The archive_files
dependency has just been injected into dependent script.
You could have injected dependency which implements archive_files
using tar
or xz
.
Example: removing DI
If dependent.sh
script used dependencies directly, the approach would be called dependency lookup (which is opposite to dependency injection):
#!/bin/sh
# Dependent
# dependency look-up
source ./archive_files_zip.sh
touch "one.txt" "two.txt"
archive_files "one.txt" "two.txt"
Now the problem is that dependent "component" has to perform initialization itself.
The "component"'s source code is neither clean nor stable because every changes in initialization of dependencies requires new release for "components"'s source code file as well.
Last words
DI is not as largely emphasized and popularized as in Java frameworks.
But it's a generic approach to split concerns of:
- application development (single source code release lifecycle)
- application deployment (multiple target environments with independent lifecycles)
Using configuration only with dependency lookup does not help as number of configuration parameters may change per dependency (e.g. new authentication type) as well as number of supported types of dependencies (e.g. new database type).
Is it possible to create a 'link to a folder' in a SharePoint document library?
The simplest way is to use the following pattern:
http://[server]/[site]/[ListName]/[Folder]/[SubFolder]
To place a shortcut to a document library:
- Upload it as *.url file. However, by default, this file type is not allowed.
- Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link
Conditional HTML Attributes using Razor MVC3
Note you can do something like this(at least in MVC3):
<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >
What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder
but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.
<td align="left" class="TopBorder" >
OR
<td align="left" style="border:0px" >
What goes wrong with providing your own quotes
If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:
<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>
This should evaluate to <button type="button" style="border:0px">
but Razor escapes all output from C# and thus produces:
style="border:0px"
You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:
style=""border:0px""
But in the DOM inspector HTML character codes display properly so you actually see:
style=""border:0px""
In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.
So the problem with trying to do the quoting yourself is Razor escapes these.
If you want complete control of quotes
Use Html.Raw to prevent quote escaping:
<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>
Renders as:
<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>
The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script>
and now any other user who views this page has their password instantly changed to a password that the malicious user knows.
How to remove all debug logging calls before building the release version of an Android app?
I suggest having a static boolean somewhere indicating whether or not to log:
class MyDebug {
static final boolean LOG = true;
}
Then wherever you want to log in your code, just do this:
if (MyDebug.LOG) {
if (condition) Log.i(...);
}
Now when you set MyDebug.LOG to false, the compiler will strip out all code inside such checks (since it is a static final, it knows at compile time that code is not used.)
For larger projects, you may want to start having booleans in individual files to be able to easily enable or disable logging there as needed. For example, these are the various logging constants we have in the window manager:
static final String TAG = "WindowManager";
static final boolean DEBUG = false;
static final boolean DEBUG_FOCUS = false;
static final boolean DEBUG_ANIM = false;
static final boolean DEBUG_LAYOUT = false;
static final boolean DEBUG_RESIZE = false;
static final boolean DEBUG_LAYERS = false;
static final boolean DEBUG_INPUT = false;
static final boolean DEBUG_INPUT_METHOD = false;
static final boolean DEBUG_VISIBILITY = false;
static final boolean DEBUG_WINDOW_MOVEMENT = false;
static final boolean DEBUG_ORIENTATION = false;
static final boolean DEBUG_APP_TRANSITIONS = false;
static final boolean DEBUG_STARTING_WINDOW = false;
static final boolean DEBUG_REORDER = false;
static final boolean DEBUG_WALLPAPER = false;
static final boolean SHOW_TRANSACTIONS = false;
static final boolean HIDE_STACK_CRAWLS = true;
static final boolean MEASURE_LATENCY = false;
With corresponding code like:
if (DEBUG_FOCUS || DEBUG_WINDOW_MOVEMENT) Log.v(
TAG, "Adding window " + window + " at "
+ (i+1) + " of " + mWindows.size() + " (after " + pos + ")");
Including another class in SCSS
Try this:
- Create a placeholder base class (%base-class) with the common
properties
- Extend your class (.my-base-class) with this placeholder.
Now you can extend %base-class in any of your classes (e.g. .my-class).
%base-class {
width: 80%;
margin-left: 10%;
margin-right: 10%;
}
.my-base-class {
@extend %base-class;
}
.my-class {
@extend %base-class;
margin-bottom: 40px;
}
Netbeans how to set command line arguments in Java
If it's a Maven project then Netbeans is running your application using the exec-maven-plugin so you'll need to append your options onto the existing exec.args
property found in the Run Maven dialog. This dialog can be accessed from the the Output window by pressing the yellow double arrow icon.
How do I include a JavaScript file in another JavaScript file?
Step 1: Declare the function in another class.
export const myreport = (value) => {
color = value.color;
name = value.name;
var mytext = name + " | " + color;
return mytext;
}
Step 2:- Import that function which is needed to be used.
import {myreport} from '../../Test'
Step 3:- Use that function.
let val = { color: "red", name: "error" }
var resultText = myreport(val)
console.log("resultText :- ", resultText)
Batch File: ( was unexpected at this time
you need double quotes in all your three if
statements, eg.:
IF "%a%"=="2" (
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if "!param1!"=="" goto :param1Prompt
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
USB Write is Unlocked!
)
)
pause
Prefer composition over inheritance?
Didn't find a satisfactory answer here, so I wrote a new one.
To understand why "prefer composition over inheritance", we need first get back the assumption omitted in this shortened idiom.
There are two benefits of inheritance: subtyping and subclassing
Subtyping means conforming to a type (interface) signature, i.e. a set of APIs, and one can override part of the signature to achieve subtyping polymorphism.
Subclassing means implicit reuse of method implementations.
With the two benefits comes two different purposes for doing inheritance: subtyping oriented and code reuse oriented.
If code reuse is the sole purpose, subclassing may give one more than what he needs, i.e. some public methods of the parent class don't make much sense for the child class. In this case, instead of favoring composition over inheritance, composition is demanded. This is also where the "is-a" vs. "has-a" notion comes from.
So only when subtyping is purposed, i.e. to use the new class later in a polymorphic manner, do we face the problem of choosing inheritance or composition. This is the assumption that gets omitted in the shortened idiom under discussion.
To subtype is to conform to a type signature, this means composition has always to expose no less amount of APIs of the type. Now the trade offs kick in:
Inheritance provides straightforward code reuse if not overridden, while composition has to re-code every API, even if it's just a simple job of delegation.
Inheritance provides straightforward open recursion via the internal polymorphic site this
, i.e. invoking overriding method (or even type) in another member function, either public or private (though discouraged). Open recursion can be simulated via composition, but it requires extra effort and may not always viable(?). This answer to a duplicated question talks something similar.
Inheritance exposes protected members. This breaks encapsulation of the parent class, and if used by subclass, another dependency between the child and its parent is introduced.
Composition has the befit of inversion of control, and its dependency can be injected dynamically, as is shown in decorator pattern and proxy pattern.
Composition has the benefit of combinator-oriented programming, i.e. working in a way like the composite pattern.
Composition immediately follows programming to an interface.
Composition has the benefit of easy multiple inheritance.
With the above trade offs in mind, we hence prefer composition over inheritance. Yet for tightly related classes, i.e. when implicit code reuse really make benefits, or the magic power of open recursion is desired, inheritance shall be the choice.
How to resolve the error on 'react-native start'
You can go to...
\node_modules\metro-config\src\defaults\blacklist.js and change...
var sharedBlacklist = [ /node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/, /heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/ ];
for this:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
How to include a Font Awesome icon in React's render()
React uses the className
attribute, like the DOM.
If you use the development build, and look at the console, there's a warning. You can see this on the jsfiddle.
Warning: Unknown DOM property class. Did you mean className?
Is it possible to have empty RequestParam values use the defaultValue?
You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
if(i == null) {
i = 10;
}
// ...
}
I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:
http://example.com/test
C# string reference type?
I believe your code is analogous to the following, and you should not have expected the value to have changed for the same reason it wouldn't here:
public static void Main()
{
StringWrapper testVariable = new StringWrapper("before passing");
Console.WriteLine(testVariable);
TestI(testVariable);
Console.WriteLine(testVariable);
}
public static void TestI(StringWrapper testParameter)
{
testParameter = new StringWrapper("after passing");
// this will change the object that testParameter is pointing/referring
// to but it doesn't change testVariable unless you use a reference
// parameter as indicated in other answers
}
Import Certificate to Trusted Root but not to Personal [Command Line]
If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:
certutil -importpfx c:\somepfx.pfx
this works but still a password is needed to be typed in manually for private key.
Including -p and "password" cause error too many arguments for certutil on XP
Difference between Parameters.Add(string, object) and Parameters.AddWithValue
There is no difference in terms of functionality. In fact, both do this:
return this.Add(new SqlParameter(parameterName, value));
The reason they deprecated the old one in favor of AddWithValue
is to add additional clarity, as well as because the second parameter is object
, which makes it not immediately obvious to some people which overload of Add
was being called, and they resulted in wildly different behavior.
Take a look at this example:
SqlCommand command = new SqlCommand();
command.Parameters.Add("@name", 0);
At first glance, it looks like it is calling the Add(string name, object value)
overload, but it isn't. It's calling the Add(string name, SqlDbType type)
overload! This is because 0 is implicitly convertible to enum types. So these two lines:
command.Parameters.Add("@name", 0);
and
command.Parameters.Add("@name", 1);
Actually result in two different methods being called. 1
is not convertible to an enum implicitly, so it chooses the object
overload. With 0
, it chooses the enum overload.
Pass Additional ViewData to a Strongly-Typed Partial View
To extend on what womp posted, you can pass new View Data while retaining the existing View Data if you use the constructor overload of the ViewDataDictionary
like so:
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary(this.ViewData) { { "index", index } }
);
Getting char from string at specified index
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
How to blur background images in Android
This is an easy way to blur Images Efficiently with Android's RenderScript that I found on this article
Create a Class called BlurBuilder
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
Copy any image to your drawable folder
Use BlurBuilder in your activity like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mContainerView = (LinearLayout) findViewById(R.id.container);
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
Bitmap blurredBitmap = BlurBuilder.blur( this, originalBitmap );
mContainerView.setBackground(new BitmapDrawable(getResources(), blurredBitmap));
Renderscript is included into support v8 enabling this answer down to api 8. To enable it using gradle include these lines into your gradle file (from this answer)
defaultConfig {
...
renderscriptTargetApi *your target api*
renderscriptSupportModeEnabled true
}
Result
python 3.x ImportError: No module named 'cStringIO'
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
What is the difference between Normalize.css and Reset CSS?
First reset.css
is the worst library you can use, because it removes the standard structure of HTML and displays everything you write just as text, after assigning the values of margin padding and other attributes to 0
. So for example you will find that <H1>
, will be the same as <H6>
.
On the other hand Normalize.css
uses the standard structure and also fixes almost all the errors existing in it. For example it fixes the problem with showing a form from one browser to another. Normalize fixes this by modifying this features so your elements will be shown the same on all browsers.
How to use Ajax.ActionLink?
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
Resize Google Maps marker icon image
If the original size is 100 x 100 and you want to scale it to 50 x 50, use scaledSize instead of Size.
var icon = {
url: "../res/sit_marron.png", // url
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
icon: icon
});
Get the (last part of) current directory name in C#
Try this:
String newString = "";
Sting oldString = "/Users/smcho/filegen_from_directory/AIRPassthrough";
int indexOfLastSlash = oldString.LastIndexOf('/', 0, oldString.length());
newString = oldString.subString(indexOfLastSlash, oldString.length());
Code may be off (I haven't tested it) but the idea should work
No line-break after a hyphen
You can also do it "the joiner way" by inserting "U+2060
Word Joiner".
If Accept-Charset
permits, the unicode character itself can be inserted directly into the HTML output.
Otherwise, it can be done using entity encoding. E.g. to join the text red-brown
, use:
red-⁠brown
or (decimal equivalent):
red-⁠brown
. Another usable character is "U+FEFF
Zero Width No-break Space"[ 1 ]:
red-brown
and (decimal equivalent):
red-brown
[1]: Note that while this method still works in major browsers like Chrome, it has been deprecated since Unicode 3.2.
Comparison of "the joiner way" with "U+2011
Non-breaking Hyphen":
The word joiner can be used for all other characters, not just hyphens.
When using the word joiner, most renderers will rasterize the text identically. On Chrome, FireFox, IE, and Opera, the rendering of normal hyphens, eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
is identical to the rendering of normal hyphens (with U+2060 Word Joiner), eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
while the above two renders differ from the rendering of "Non-breaking Hyphen", eg:
a‑b‑c‑d‑e‑f‑g‑h‑i‑j‑k‑l‑m‑n‑o‑p‑q‑r‑s‑t‑u‑v‑w‑x‑y‑z
. (The extent of the difference is browser-dependent and font-dependent. E.g. when using a font declaration of "arial
", Firefox and IE11 show relatively huge variations, while Chrome and Opera show smaller variations.)
Comparison of "the joiner way" with <span class=c1></span>
(CSS .c1 {white-space:nowrap;}
) and <nobr></nobr>
:
The word joiner can be used for situations where usage of HTML tags is restricted, e.g. forms of websites and forums.
On the spectrum of presentation and content, majority will consider the word joiner to be closer to content, when compared to tags.
• As tested on Windows 8.1 Core 64-bit using:
• IE 11.0.9600.18205
• Firefox 43.0.4
• Chrome 48.0.2564.109 (Official Build) m (32-bit)
• Opera 35.0.2066.92
On localhost, how do I pick a free port number?
For the sake of snippet of what the guys have explained above:
import socket
from contextlib import closing
def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
SQL Server CTE and recursion example
--DROP TABLE #Employee
CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)
INSERT INTO #Employee VALUES('M11M','Manager',NULL)
INSERT INTO #Employee VALUES('P11P','Manager',NULL)
INSERT INTO #Employee VALUES('AA','Clerk',1)
INSERT INTO #Employee VALUES('AB','Assistant',1)
INSERT INTO #Employee VALUES('ZC','Supervisor',2)
INSERT INTO #Employee VALUES('ZD','Security',2)
SELECT * FROM #Employee (NOLOCK)
;
WITH Emp_CTE
AS
(
SELECT EmpId,EmpName,Designation, ManagerID
,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
FROM #Employee
)
select EmpId,EmpName,Designation, ManagerID
FROM Emp_CTE
order BY ManagerID_N, EmpId
Confirm deletion in modal / dialog using Twitter Bootstrap?
GET recipe
For this task you can use already available plugins and bootstrap extensions. Or you can make your own confirmation popup with just 3 lines of code. Check it out.
Say we have this links (note data-href
instead of href
) or buttons that we want to have delete confirmation for:
<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>
<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
Delete record #54
</button>
Here #confirm-delete
points to a modal popup div in your HTML. It should have an "OK" button configured like this:
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
...
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Delete</a>
</div>
</div>
</div>
</div>
Now you only need this little javascript to make a delete action confirmable:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
So on show.bs.modal
event delete button href
is set to URL with corresponding record id.
Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
POST recipe
I realize that in some cases there might be needed to perform POST or DELETE request rather then GET. It it still pretty simple without too much code. Take a look at the demo below with this approach:
// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('recordId');
$modalDiv.addClass('loading');
$.post('/api/record/' + id).then(function() {
$modalDiv.modal('hide').removeClass('loading');
});
});
// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.title', this).text(data.recordTitle);
$('.btn-ok', this).data('recordId', data.recordId);
});
_x000D_
_x000D_
// Bind click to OK button within popup_x000D_
$('#confirm-delete').on('click', '.btn-ok', function(e) {_x000D_
_x000D_
var $modalDiv = $(e.delegateTarget);_x000D_
var id = $(this).data('recordId');_x000D_
_x000D_
$modalDiv.addClass('loading');_x000D_
setTimeout(function() {_x000D_
$modalDiv.modal('hide').removeClass('loading');_x000D_
}, 1000);_x000D_
_x000D_
// In reality would be something like this_x000D_
// $modalDiv.addClass('loading');_x000D_
// $.post('/api/record/' + id).then(function() {_x000D_
// $modalDiv.modal('hide').removeClass('loading');_x000D_
// });_x000D_
});_x000D_
_x000D_
// Bind to modal opening to set necessary data properties to be used to make request_x000D_
$('#confirm-delete').on('show.bs.modal', function(e) {_x000D_
var data = $(e.relatedTarget).data();_x000D_
$('.title', this).text(data.recordTitle);_x000D_
$('.btn-ok', this).data('recordId', data.recordId);_x000D_
});
_x000D_
.modal.loading .modal-content:before {_x000D_
content: 'Loading...';_x000D_
text-align: center;_x000D_
line-height: 155px;_x000D_
font-size: 20px;_x000D_
background: rgba(0, 0, 0, .8);_x000D_
position: absolute;_x000D_
top: 55px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
color: #EEE;_x000D_
z-index: 1000;_x000D_
}
_x000D_
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>_x000D_
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>_x000D_
<link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />_x000D_
_x000D_
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>_x000D_
<p>Do you want to proceed?</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>_x000D_
<button type="button" class="btn btn-danger btn-ok">Delete</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "The first one", #23_x000D_
</a>_x000D_
<br />_x000D_
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "Something cool", #54_x000D_
</button>
_x000D_
_x000D_
_x000D_
Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
Bootstrap 2.3
Here is an original version of the code I made when I was answering this question for Bootstrap 2.3 modal.
$('#modal').on('show', function() {
var id = $(this).data('id'),
removeBtn = $(this).find('.danger');
removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});
Demo: http://jsfiddle.net/MjmVr/1595/
HTML input type=file, get the image before submitting the form
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
Check if an element is present in a Bash array
You could do:
if [[ " ${arr[*]} " == *" d "* ]]; then
echo "arr contains d"
fi
This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.
The safest way is to loop over the array until you find the element:
array_contains () {
local seeking=$1; shift
local in=1
for element; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no # no
array_contains "d e" "${arr[@]}" && echo yes || echo no # yes
Here's a "cleaner" version where you just pass the array name, not all its elements
array_contains2 () {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
array_contains2 arr "a b" && echo yes || echo no # no
array_contains2 arr "d e" && echo yes || echo no # yes
For associative arrays, there's a very tidy way to test if the array contains a given key: The -v
operator
$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no
See 6.4 Bash Conditional Expressions in the manual.
plot data from CSV file with matplotlib
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
Switch between two frames in tkinter
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
FileProvider - IllegalArgumentException: Failed to find configured root
none of the above worked for me,
after a few hours debugging I found out that the problem is in createImageFile()
, specifically absolute path
vs relative path
I assume that you guys are using the official Android guide for taking photo. https://developer.android.com/training/camera/photobasics
private static File createImageFile(Context context) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Take note of the storageDir
, this is the location where the file will be created. So in order to get the absolute path of this file, I simply use image.getAbsolutePath()
, this path will be used in onActivityResult
if you need the Bitmap image after taking photo
below is the file_path.xml
, simply use .
so that it uses the absolute path
<paths>
<external-path
name="my_images"
path="." />
</paths>
and if you need the bitmap after taking photo
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeFile(mCurrentPhotoPath);
} catch (Exception e) {
e.printStackTrace();
}
}
How do I get the old value of a changed cell in Excel VBA?
In response to Matt Roy answer, I found this option a great response, although I couldn't post as such with my current rating. :(
However, while taking the opportunity to post my thoughts on his response, I thought I would take the opportunity to include a small modification. Just compare code to see.
So thanks to Matt Roy for bringing this code to our attention, and Chris.R for posting original code.
Dim OldValues As New Collection
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'>> Prevent user from multiple selection before any changes:
If Selection.Cells.Count > 1 Then
MsgBox "Sorry, multiple selections are not allowed.", vbCritical
ActiveCell.Select
Exit Sub
End If
'Copy old values
Set OldValues = Nothing
Dim c As Range
For Each c In Target
OldValues.Add c.Value, c.Address
Next c
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
On Local Error Resume Next ' To avoid error if the old value of the cell address you're looking for has not been copied
Dim c As Range
For Each c In Target
If OldValues(c.Address) <> "" And c.Value <> "" Then 'both Oldvalue and NewValue are Not Empty
Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
ElseIf OldValues(c.Address) = "" And c.Value = "" Then 'both Oldvalue and NewValue are Empty
Debug.Print "New value of " & c.Address & " is Empty " & c.Value & "; old value is Empty" & OldValues(c.Address)
ElseIf OldValues(c.Address) <> "" And c.Value = "" Then 'Oldvalue is Empty and NewValue is Not Empty
Debug.Print "New value of " & c.Address & " is Empty" & c.Value & "; old value was " & OldValues(c.Address)
ElseIf OldValues(c.Address) = "" And c.Value <> "" Then 'Oldvalue is Not Empty and NewValue is Empty
Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value is Empty" & OldValues(c.Address)
End If
Next c
'Copy old values (in case you made any changes in previous lines of code)
Set OldValues = Nothing
For Each c In Target
OldValues.Add c.Value, c.Address
Next c
Increasing the maximum number of TCP/IP connections in Linux
Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.
On the client side:
Increase the ephermal port range, and decrease the tcp_fin_timeout
To find out the default values:
sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout
The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout
defines the minimum time these sockets will stay in TIME_WAIT
state (unusable after being used once).
Usual system defaults are:
net.ipv4.ip_local_port_range = 32768 61000
net.ipv4.tcp_fin_timeout = 60
This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470
sockets per second. If you are not happy with that, you could begin with increasing the port_range
. Setting the range to 15000 61000
is pretty common these days. You could further increase the availability by decreasing the fin_timeout
. Suppose you do both, you should see over 1500 outbound connections per second, more readily.
To change the values:
sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30
The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."
Default Sysctl values on a typical Linux box for tcp_tw_recycle
& tcp_tw_reuse
would be
net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0
These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait
cycle. I recommend setting:
sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1
This allows fast cycling of sockets in time_wait
state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle
option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle
has been removed from Linux 4.12.
On the Server Side:
The net.core.somaxconn
value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.
sysctl net.core.somaxconn=1024
txqueuelen
parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.
ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local
Similarly bump up the values for net.core.netdev_max_backlog
and net.ipv4.tcp_max_syn_backlog
. Their default values are 1000 and 1024 respectively.
sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048
Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.
Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.
PHPUnit assert that an exception was thrown?
function yourfunction($a,$z){
if($a<$z){ throw new <YOUR_EXCEPTION>; }
}
here is the test
class FunctionTest extends \PHPUnit_Framework_TestCase{
public function testException(){
$this->setExpectedException(<YOUR_EXCEPTION>::class);
yourfunction(1,2);//add vars that cause the exception
}
}
Unable to load script from assets index.android.bundle on windows
I am facing this issue, lot of search and I resolved that issue.
c:\ProjectFolder\ProjectName> react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Than Run the react native :
c:\ProjectFolder\ProjectName>react-native run-android
AngularJS 1.2 $injector:modulerr
my error disappeared by adding this '()' at the end
(function(){
var home = angular.module('home',[]);
home.controller('QuestionsController',function(){
console.log("controller initialized");
this.addPoll = function(){
console.log("inside function");
};
});
})();
Git: add vs push vs commit
git add
adds files to the Git index, which is a staging area for objects prepared to be commited.
git commit
commits the files in the index to the repository, git commit -a
is a shortcut to add all the modified tracked files to the index first.
git push
sends all the pending changes to the remote repository to which your branch is mapped (eg. on GitHub).
In order to understand Git you would need to invest more effort than just glancing over the documentation, but it's definitely worth it. Just don't try to map Git commands directly to Subversion, as most of them don't have a direct counterpart.
how to install apk application from my pc to my mobile android
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
How can I generate a self-signed certificate with SubjectAltName using OpenSSL?
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?
The Get-ChildItem cmdlet has an -Exclude
parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:
function GetFiles($path = $pwd, [string[]]$exclude)
{
foreach ($item in Get-ChildItem $path)
{
if ($exclude | Where {$item -like $_}) { continue }
if (Test-Path $item.FullName -PathType Container)
{
$item
GetFiles $item.FullName $exclude
}
else
{
$item
}
}
}
How do I get the last inserted ID of a MySQL table in PHP?
NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.
The table:
create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));
Now if you do:
insert into xyz (name) values('one'),('two'),('three');
The mysqli::insert_id will be 1 not 3.
To get the correct value do:
mysqli::insert_id + mysqli::affected_rows) - 1
This has been document but it is a bit obscure.
Dialog with transparent background in Android
<style name="NewDialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:background">@android:color/transparent</item>
</style>
use in java
Dialog dialog = new Dialog(this, R.style.NewDialog);
I hope help you !
Playing mp3 song on python
I have tried most of the listed options here and found the following:
for windows 10:
similar to @Shuge Lee answer;
from playsound import playsound
playsound('/path/file.mp3')
you need to run:
$ pip install playsound
for Mac:
simply just try the following, which runs the os command,
import os
os.system("afplay file.mp3")
How to hash a string into 8 digits?
Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:
>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417
If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:
$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934
This means the hash()-based solution suggested, which can be shortened to just:
hash(s) % 10**8
will only return the same value within a given script run:
#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451
So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.
Best way to access a control on another form in Windows Forms?
public void Enable_Usercontrol1()
{
UserControl1 usercontrol1 = new UserControl1();
usercontrol1.Enabled = true;
}
/*
Put this Anywhere in your Form and Call it by Enable_Usercontrol1();
Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal
*/
View content of H2 or HSQLDB in-memory database
What about comfortably viewing (and also editing) the content over ODBC & MS-Access, Excel?
Softwareversions::
- H2 Version:1.4.196
- Win 10 Postgres ODBC Driver Version: psqlodbc_09_03_0210
- For Win7 ODBC Client: win7_psqlodbc_09_00_0101-x64.msi
H2 Server:
/*
For JDBC Clients to connect:
jdbc:h2:tcp://localhost:9092/trader;CIPHER=AES;IFEXISTS=TRUE;MVCC=true;LOCK_TIMEOUT=60000;CACHE_SIZE=131072;CACHE_TYPE=TQ
*/
public class DBStarter {
public static final String BASEDIR = "/C:/Trader/db/";
public static final String DB_URL = BASEDIR + "trader;CIPHER=AES;IFEXISTS=TRUE;MVCC=true;LOCK_TIMEOUT=10000;CACHE_SIZE=131072;CACHE_TYPE=TQ";
static void startServer() throws SQLException {
Server tcpServer = Server.createTcpServer(
"-tcpPort", "9092",
"-tcpAllowOthers",
"-ifExists",
// "-trace",
"-baseDir", BASEDIR
);
tcpServer.start();
System.out.println("H2 JDBC Server started: " + tcpServer.getStatus());
Server pgServer = Server.createPgServer(
"-pgPort", "10022",
"-pgAllowOthers",
"-key", "traderdb", DB_URL
);
pgServer.start();
System.out.println("H2 ODBC PGServer started: " + pgServer.getStatus());
}
}
Windows10 ODBC Datasource Configuration which can be used by any ODBC client:
In Databse field the name given in '-key' parameter has to be used.
POST data with request module on Node.JS
I had to post key value pairs without form and I could do it easily like below:
var request = require('request');
request({
url: 'http://localhost/test2.php',
method: 'POST',
json: {mes: 'heydude'}
}, function(error, response, body){
console.log(body);
});
store return json value in input hidden field
It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).
Anyway, if that is an array wrapper, you'll want something like this:
$('#my-hidden-field').val(theObject[0].id);
You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,
$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;
This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.
Determine if Android app is being used for the first time
My version for kotlin looks like the following:
PreferenceManager.getDefaultSharedPreferences(this).apply {
// Check if we need to display our OnboardingSupportFragment
if (!getBoolean("wasAppStartedPreviously", false)) {
// The user hasn't seen the OnboardingSupportFragment yet, so show it
startActivity(Intent(this@SplashScreenActivity, AppIntroActivity::class.java))
} else {
startActivity(Intent(this@SplashScreenActivity, MainActivity::class.java))
}
}
CASE statement in SQLite query
The syntax is wrong in this clause (and similar ones)
CASE lkey WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
It's either
CASE WHEN [condition] THEN [expression] ELSE [expression] END
or
CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END
So in your case it would read:
CASE WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
Check out the documentation (The CASE expression):
http://www.sqlite.org/lang_expr.html
How to List All Redis Databases?
you can use redis-cli INFO keyspace
localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0
How to generate XML file dynamically using PHP?
I'd use SimpleXMLElement.
<?php
$xml = new SimpleXMLElement('<xml/>');
for ($i = 1; $i <= 8; ++$i) {
$track = $xml->addChild('track');
$track->addChild('path', "song$i.mp3");
$track->addChild('title', "Track $i - Track Title");
}
Header('Content-type: text/xml');
print($xml->asXML());
String to Binary in C#
Here's an extension function:
public static string ToBinary(this string data, bool formatBits = false)
{
char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
int index = 0;
for (int i = 0; i < data.Length; i++)
{
string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
for (int j = 0; j < 8; j++)
{
buffer[index] = binary[j];
index++;
}
if (formatBits && i < (data.Length - 1))
{
buffer[index] = ' ';
index++;
}
}
return new string(buffer);
}
You can use it like:
Console.WriteLine("Testing".ToBinary());
and if you add 'true' as a parameter, it will automatically separate each binary sequence.
How can I pass a parameter in Action?
Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new !
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x!
produces a value of the type of x
with null
and undefined
excluded. Similar to type assertions of the forms <T>x
and x as T
, the !
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
How to get response as String using retrofit without using GSON or any other library in android
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
Remove part of string after "."
You just need to escape the period:
a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")
gsub("\\..*","",a)
[1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
Is using 'var' to declare variables optional?
There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
A declaration sets a DontDelete flag. An assignment does not.
A declaration ties that variable to the current scope.
A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.
converting date time to 24 hour format
IN two lines:
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm aa",Locale.getDefault());
FAJR = new SimpleDateFormat("HH:mm",Locale.getDefault()).format(simpleDateFormat.parse("8:35 PM");
TypeError: window.initMap is not a function
I am using React and I had mentioned &callback=initMap in the script as below
<script
src="https://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY&callback=initMap">
</script>
then is just removed the &callback=initMap
part now there is no such error as window.initMap is not a function in the console.
Failed to load resource: net::ERR_INSECURE_RESPONSE
I still experienced the problem described above on an Asus T100 Windows 10 test device for both (up to date) Edge and Chrome browser.
Solution was in the date/time settings of the device; somehow the date was not set correctly (date in the past). Restoring this by setting the correct date (and restarting the browsers) solved the issue for me. I hope I save someone a headache debugging this problem.
Linking dll in Visual Studio
You don't add or link directly against a DLL, you link against the LIB produced by the DLL.
A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).
To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:
#pragma comment(lib, "dll.lib")
With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).
Git conflict markers
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
How to 'bulk update' with Django?
If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:
some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)
If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.
If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.
Change private static final field using Java reflection
A little curiosity from the Java Language Specification, chapter 17, section 17.5.4 "Write-protected Fields":
Normally, a field that is final and static may not be modified.
However, System.in, System.out, and System.err are static final fields
that, for legacy reasons, must be allowed to be changed by the methods
System.setIn, System.setOut, and System.setErr. We refer to these
fields as being write-protected to distinguish them from ordinary
final fields.
Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4
using where and inner join in mysql
Try this :
SELECT
(
SELECT
`NAME`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) as `NAME`
FROM
school_locations
WHERE
(
SELECT
`TYPE`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) = 'coun';
How to loop over files in directory and change path and add suffix to filename
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
How can I change the app display name build with Flutter?
You can change it in iOS without opening Xcode by editing the project/ios/Runner/info.plist <key>CFBundleDisplayName</key>
to the String that you want as your name.
FWIW - I was getting frustrated with making changes in Xcode and Flutter, so I started committing all changes before opening Xcode, so I could see where the changes show up in the Flutter project.
excel delete row if column contains value from to-remove-list
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
- -Put Original List in Column A
-Put To Remove list in Column B
-Select both columns, then "Conditional Formatting"
-Select "Hightlight Cells Rules" --> "Duplicate Values"
-The duplicates should be hightlighted in both columns
-Then select Column A and then "Sort & Filter" ---> "Custom Sort"
-In the dialog box that appears, select the middle option "Sort On" and pick "Cell Color"
-Then select the next option "Sort Order" and choose "No Cell Color" "On bottom"
-All the highlighted cells should be at the top of the list.
-Select all the highlighted cells by scrolling down the list, then click delete.
How to find topmost view controller on iOS
Getting top most view controller for Swift using extensions
Code:
extension UIViewController {
@objc func topMostViewController() -> UIViewController {
// Handling Modal views
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
// Handling UIViewController's added as subviews to some other views.
else {
for view in self.view.subviews
{
// Key property which most of us are unaware of / rarely use.
if let subViewController = view.next {
if subViewController is UIViewController {
let viewController = subViewController as! UIViewController
return viewController.topMostViewController()
}
}
}
return self
}
}
}
extension UITabBarController {
override func topMostViewController() -> UIViewController {
return self.selectedViewController!.topMostViewController()
}
}
extension UINavigationController {
override func topMostViewController() -> UIViewController {
return self.visibleViewController!.topMostViewController()
}
}
Usage:
UIApplication.sharedApplication().keyWindow!.rootViewController!.topMostViewController()
Make a dictionary in Python from input values
This is what we ended up using:
n = 3
d = dict(raw_input().split() for _ in range(n))
print d
Input:
A1023 CRT
A1029 Regulator
A1030 Therm
Output:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
How can I create a small color box using html and css?
You can create these easily using the floating ability of CSS, for example.
I have created a small example on Jsfiddle over here, all the related css and html is also provided there.
_x000D_
_x000D_
.foo {_x000D_
float: left;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
margin: 5px;_x000D_
border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_
PHPExcel - set cell type before writing a value in it
When the text is a number with leading zeros, then do:
(Cuando el texto es un número que empieza por ceros, hacer)
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', $val,PHPExcel_Cell_DataType::TYPE_STRING);
Limiting Powershell Get-ChildItem by File Creation Date Range
Use Where-Object
, like:
Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") |
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv 'PATH\scans.csv'
How to Detect Browser Back Button event - Cross Browser
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
alert('hello world');
}
This is the only one solution that worked for me (it's not a onepage website).
It's working with Chrome, Firefox and Safari.
How to convert WebResponse.GetResponseStream return into a string?
Richard Schneider is right.
use code below to fetch data from site which is not utf8 charset will get wrong string.
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
"
i can't vote.so wrote this.
How to access the local Django webserver from outside world
For AWS users.
I had to use the following steps to get there.
1) Ensure that pip and django are installed at the sudo level
- sudo apt-get install python-pip
- sudo pip install django
2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0
- configured through AWS console
3) Add Public IP and DNS to ALLOWED_HOSTS
- ALLOWED_HOSTS is a list object that you can find in settings.py
- ALLOWED_HOSTS = ["75.254.65.19","ec2-54-528-27-21.compute-1.amazonaws.com"]
4) Launch development server with sudo on port 80
- sudo python manage.py runserver 0:80
Site now available at either of the following (no need for :80 as that is default for http):
- [Public DNS] i.e. ec2-54-528-27-21.compute-1.amazonaws.com
- [Public IP] i.e 75.254.65.19
How to force reloading php.ini file?
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
The project was not built since its build path is incomplete
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
- Right-click on the project, Build Path and go to Configure Build Path
- Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
- Close the dialog.
To add it:
Right-click on the project, Maven → Disable Maven Nature
Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
ESRI : Failed to parse source map
The error in the Google DevTools are caused Google extensions.
- I clicked on my Google icon in the browser
- created a guest profile at the bottom of the popup window.
- I then pasted my localhost address and voila!!
No more errors in the console.
best way to get folder and file list in Javascript
I don't like adding new package into my project just to handle this simple task.
And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.
So I made a function to get all the folder content (and its sub folder).... NON-Recursively
var getDirectoryContent = function(dirPath) {
/*
get list of files and directories from given dirPath and all it's sub directories
NON RECURSIVE ALGORITHM
By. Dreamsavior
*/
var RESULT = {'files':[], 'dirs':[]};
var fs = fs||require('fs');
if (Boolean(dirPath) == false) {
return RESULT;
}
if (fs.existsSync(dirPath) == false) {
console.warn("Path does not exist : ", dirPath);
return RESULT;
}
var directoryList = []
var DIRECTORY_SEPARATOR = "\\";
if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
directoryList.push(dirPath); // initial
while (directoryList.length > 0) {
var thisDir = directoryList.shift();
if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
var thisDirContent = fs.readdirSync(thisDir);
while (thisDirContent.length > 0) {
var thisFile = thisDirContent.shift();
var objPath = thisDir+thisFile
if (fs.existsSync(objPath) == false) continue;
if (fs.lstatSync(objPath).isDirectory()) { // is a directory
let thisDirPath = objPath+DIRECTORY_SEPARATOR;
directoryList.push(thisDirPath);
RESULT['dirs'].push(thisDirPath);
} else { // is a file
RESULT['files'].push(objPath);
}
}
}
return RESULT;
}
the only drawback of this function is that this is Synchronous function... You have been warned ;)
"git rm --cached x" vs "git reset head --? x"?
There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.
When you do something like git add file
you add it to the index. And when you commit it, you add it to the tree as well.
It will probably help you to know the three more common flags in git reset
:
git reset [--<mode>
] [<commit>
]
This form resets the current branch head to <commit>
and possibly
updates the index (resetting it to the tree of <commit>
) and the
working tree depending on <mode>
, which must be one of the
following:
--soft
Does not touch the index file nor the working tree at all (but resets
the head to <commit>
, just like all modes do). This leaves all your
changed files "Changes to be committed", as git status would put it.
--mixed
Resets the index but not the working tree (i.e., the changed files
are preserved but not marked for commit) and reports what has not been
updated. This is the default action.
--hard
Resets the index and working tree. Any changes to tracked files in
the working tree since <commit>
are discarded.
Now, when you do something like git reset HEAD
, what you are actually doing is git reset HEAD --mixed
and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add
). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add
was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD
is the exact opposite of git add
.
git rm
, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached
, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add
was used to add a new (previously untracked) file, then git rm --cached
is the exact opposite of git add
(and is pretty much identical to git reset HEAD
).
Git 2.25 introduced a new command for these cases, git restore
, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.
The preferred way of creating a new element with jQuery
According to the documentation for 3.4, It is preferred to use attributes with attr()
method.
$('<div></div>').attr(
{
id: 'some dynanmic|static id',
"class": 'some dynanmic|static class'
}
).click(function() {
$( "span", this ).addClass( "bar" ); // example from the docs
});
How to use execvp()
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
How to query as GROUP BY in django?
You can also use the regroup
template tag to group by attributes. From the docs:
cities = [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
...
{% regroup cities by country as country_list %}
<ul>
{% for country in country_list %}
<li>{{ country.grouper }}
<ul>
{% for city in country.list %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Looks like this:
- India
- Mumbai: 19,000,000
- Calcutta: 15,000,000
- USA
- New York: 20,000,000
- Chicago: 7,000,000
- Japan
It also works on QuerySet
s I believe.
source: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup
edit: note the regroup
tag does not work as you would expect it to if your list of dictionaries is not key-sorted. It works iteratively. So sort your list (or query set) by the key of the grouper before passing it to the regroup
tag.
Can you pass parameters to an AngularJS controller on creation?
I'm very late to this and I have no idea if this is a good idea, but you can include the $attrs
injectable in the controller function allowing the controller to be initialized using "arguments" provided on an element, e.g.
app.controller('modelController', function($scope, $attrs) {
if (!$attrs.model) throw new Error("No model for modelController");
// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "http://example.com/fetch?model="+$attrs.model;
})
<div ng-controller="modelController" model="foobar">
<a href="{{url}}">Click here</a>
</div>
Again, no idea if this is a good idea, but it seems to work and is another alternative.
How to build & install GLFW 3 and use it in a Linux project
Since the accepted answer does not allow more edits, I'm going to summarize it with a single copy-paste command (Replace 3.2.1 with the latest version available in the first line):
version="3.2.1" && \
wget "https://github.com/glfw/glfw/releases/download/${version}/glfw-${version}.zip" && \
unzip glfw-${version}.zip && \
cd glfw-${version} && \
sudo apt-get install cmake xorg-dev libglu1-mesa-dev && \
sudo cmake -G "Unix Makefiles" && \
sudo make && \
sudo make install
If you want to compile a program use the following commands:
g++ -std=c++11 -c main.cpp && \
g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
If you are following the learnopengl.com tutorial you may have to set up GLAD as well. In such case click on this link
http://glad.dav1d.de/#profile=core&specification=gl&api=gl%3D3.3&api=gles1%3Dnone&api=gles2%3Dnone&api=glsc2%3Dnone&language=c&loader=on
and then click on the "Generate" button at the bottom right corner of the website and download the zip file. Extract it and compile the sources with the following command:
g++ glad/src/glad.c -c -Iglad/include
Now, the commands to compile your program become like this:
g++ -std=c++11 -c main.cpp -Iglad/include && \
g++ main.o glad.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
How to set javascript variables using MVC4 with Razor
I found a very clean solution that allows separate logic and GUI:
in your razor .cshtml page try this:
<body id="myId" data-my-variable="myValue">
...your page code here
</body>
in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):
$("#myId").data("my-variable")
Difference between .dll and .exe?
Two things: the extension and the header flag stored in the file.
Both files are PE files. Both contain the exact same layout. A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).
One minor difference is that in most cases DLLs have an export section where symbols are exported. EXEs should never have an export section since they aren't libraries but nothing prevents that from happening. The Win32 loader doesn't care either way.
Other than that they are identical. So, in summary, EXEs are executable programs while DLLs are libraries loaded into a process and contain some sort of useful functionality like security, database access or something.
Can I find events bound on an element with jQuery?
You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().
For example type the following in the dev tools console:
// Get all event listners bound to the document object
getEventListeners(document);
Editing hosts file to redirect url?
You can't. A redirect requires a webserver to accept the first request and send back the redirect. The "hosts" file just lets you set your own DNS records.
How to check type of object in Python?
What type() means:
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
For comparisons:
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Python read in string from file and split it into values
I would do something like:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.
How to style UITextview to like Rounded Rect text field?
One way I found to do it without programming is to make the textfield background transparent, then place a Round Rect Button behind it. Make sure to change the button settings to disable it and uncheck the Disable adjusts image
checkbox.
Unique constraint on multiple columns
If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:
ALTER TABLE dbo.User
ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)
AttributeError: 'DataFrame' object has no attribute
value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute.
For example:
df['accepted'].value_counts()
It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using
df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()
Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"
I received this error while trying to run Google's Firebase analytics sample app:
Prerequisites:
Add Procedure:
- Go to https://firebase.google.com/
- Click on "GO TO CONSOLE"
- Click on "Add Project"
- Project name: Enter: sample-app
- Click "Create Project"
[Takes about 10 seconds or so...]
- Click "Continue"
- On the "Getting Started" page, click "Add Firebase to your Android app"
- Enter package name for the android app
[The full package name appears at the top of the manifest: "com.google.firebase.quickstart.analytics"]
- Click on download google-services.json
- In file explorer, add google-services.json to the directory:
"quickstart/analytics/app"
[Warning: Do not rename the file, it must be: google-services.json]
- Run 'app'
- The sample app already contains the necessary Gradle file settings.
- When adding a new project do: Tools -> Firebase -> Analytics -> Add
Event -> Connect App to Firebase.
- Adding a project via Android Studio ensures that all the Gradle Dependecies are setup.
Remove Procedure:
- Go to https://firebase.google.com/
- Click on "GO TO CONSOLE"
- Settings -> Project Settings -> Delete this App
- Settings -> Project Settings -> Delete Project
- Enter project ID and press delete
I added and removed the sample app multiple times without any noticeable side effects.
MySQL Update Inner Join tables query
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Update:
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
How do I send an HTML email?
You can find a complete and very simple java class for sending emails using Google(gmail) account here,
Send email message using java application
It uses following properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Javascript: Setting location.href versus location
One difference to keep in mind, though.
Let's say you want to build some URL using the current URL. The following code will in fact redirect you, because it's not calling String.replace
but Location.replace
:
nextUrl = window.location.replace('/step1', '/step2');
The following codes work:
// cast to string
nextUrl = (window.location+'').replace('/step1', '/step2');
// href property
nextUrl = window.location.href.replace('/step1', '/step2');
Adding a splash screen to Flutter apps
Flutter provides you the ability to have a splash screen by default but there are a lot of plugins that can do the job. If you don't want to use a plugin for the task and you're worried that adding a new plugin might affect your app size. Then you can do it like this.
FOR Android
Open launch_background.xml then you can put in the splash screen image, or gradient color you want. This is the first thing your user sees when they open your app.
For IOS
Open your app using Xcode, Click on Runner > Assest.xcassets > LaunchImage, You can add the image here. If you want to edit what position launch screen image should take or look like you can edit it on LaunchScreen.storyboard.
How do I change the string representation of a Python class?
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples
How to make a class JSON serializable
Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json
module uses re
for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/
Prevent div from moving while resizing the page
There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.
Relative
An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.
<div style="width:100%">
<!-- This div will be the full width of the browser, whatever size it is -->
<div style="width:300px">
<!-- this div will be 300px, whatever size the browser is -->
<p style="width:50%">
This paragraph's width will be 50% of it's parent (150px).
</p>
</div>
</div>
Another relative measurement is ems which are relative to font size.
Fixed
An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.
If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.
Null pointer Exception on .setOnClickListener
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Java Desktop application: SWT vs. Swing
For your requirements it sounds like the bottom line will be to use Swing since it is slightly easier to get started with and not as tightly integrated to the native platform as SWT.
Swing usually is a safe bet.
how to Call super constructor in Lombok
As an option you can use com.fasterxml.jackson.databind.ObjectMapper
to initialize a child class from parent
public class A {
int x;
int y;
}
public class B extends A {
int z;
}
ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);
You can still use any lombok
annotations on A and B if you need.
Warning - Build path specifies execution environment J2SE-1.4
Just change the version in Window-> Preferences-> Java -> Installed JREs. Check the installed JREs list.
Then, Right-click on your project -> properties -> Java build path -> libraries. Change the "JRE System Library" to the version in "installed JREs".
The warning will be gone.
ArrayList - How to modify a member of an object?
You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:
for(Customer customer : myList) {
if(customer!=null && "Doe".equals(customer.getName())) {
customer.setEmail("[email protected]");
break;
}
}
Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.
Stretch background image css?
.style1 {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
- Safari 3+
- Chrome Whatever+
- IE 9+
- Opera 10+ (Opera 9.5 supported background-size but not the keywords)
- Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)
In addition you can try this for an IE solution
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;
Credit to this article by Chris Coyier
http://css-tricks.com/perfect-full-page-background-image/
How to quickly check if folder is empty (.NET)?
Thanks, everybody, for replies. I tried to use Directory.GetFiles() and Directory.GetDirectories() methods. Good news! The performance improved ~twice! 229 calls in 221ms. But also I hope, that it is possible to avoid enumeration of all items in the folder. Agree, that still the unnecessary job is executing. Don't you think so?
After all investigations, I reached a conclusion, that under pure .NET further optimiation is impossible. I am going to play with WinAPI's FindFirstFile function. Hope it will help.
Fastest way(s) to move the cursor on a terminal command line?
In Cygwin, you can activate such feature by right-clicking the window. In the pop-up window, select Options... -> Mouse -> activate Clicks place command line cursor -> Apply.
From now on, simply clicking the left mouse button at some position within the command line will place the cursor there.