Git: How configure KDiff3 as merge tool and diff tool
For Mac users
Here is @Joseph's accepted answer, but with the default Mac install path location of kdiff3
(Note that you can copy and paste this and run it in one go)
git config --global --add merge.tool kdiff3
git config --global --add mergetool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add mergetool.kdiff3.trustExitCode false
git config --global --add diff.guitool kdiff3
git config --global --add difftool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add difftool.kdiff3.trustExitCode false
JUNIT Test class in Eclipse - java.lang.ClassNotFoundException
I received this error because I had recently created a new workspace and my "Installed JREs" were not set up correctly. Make sure in Preferences -> Java -> Installed JREs
the root folder of your JDK is selected. The default for me in a new workspace was a JRE for some reason.
'readline/readline.h' file not found
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
Priority queue in .Net
class PriorityQueue<T>
{
IComparer<T> comparer;
T[] heap;
public int Count { get; private set; }
public PriorityQueue() : this(null) { }
public PriorityQueue(int capacity) : this(capacity, null) { }
public PriorityQueue(IComparer<T> comparer) : this(16, comparer) { }
public PriorityQueue(int capacity, IComparer<T> comparer)
{
this.comparer = (comparer == null) ? Comparer<T>.Default : comparer;
this.heap = new T[capacity];
}
public void push(T v)
{
if (Count >= heap.Length) Array.Resize(ref heap, Count * 2);
heap[Count] = v;
SiftUp(Count++);
}
public T pop()
{
var v = top();
heap[0] = heap[--Count];
if (Count > 0) SiftDown(0);
return v;
}
public T top()
{
if (Count > 0) return heap[0];
throw new InvalidOperationException("??????");
}
void SiftUp(int n)
{
var v = heap[n];
for (var n2 = n / 2; n > 0 && comparer.Compare(v, heap[n2]) > 0; n = n2, n2 /= 2) heap[n] = heap[n2];
heap[n] = v;
}
void SiftDown(int n)
{
var v = heap[n];
for (var n2 = n * 2; n2 < Count; n = n2, n2 *= 2)
{
if (n2 + 1 < Count && comparer.Compare(heap[n2 + 1], heap[n2]) > 0) n2++;
if (comparer.Compare(v, heap[n2]) >= 0) break;
heap[n] = heap[n2];
}
heap[n] = v;
}
}
easy.
getting the index of a row in a pandas apply function
To access the index in this case you access the name
attribute:
In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
Note that if this is really what you are trying to do that the following works and is much faster:
In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop
EDIT
Looking at this question 3+ years later, you could just do:
In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
but assuming it isn't as trivial as this, whatever your rowFunc
is really doing, you should look to use the vectorised functions, and then use them against the df index:
In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
How to initialize a List<T> to a given size (as opposed to capacity)?
A bit late but first solution you proposed seems far cleaner to me : you dont allocate memory twice.
Even List constrcutor needs to loop through array in order to copy it; it doesn't even know by advance there is only null elements inside.
1.
- allocate N
- loop N
Cost: 1 * allocate(N) + N * loop_iteration
2.
- allocate N
- allocate N + loop ()
Cost : 2 * allocate(N) + N * loop_iteration
However List's allocation an loops might be faster since List is a built-in class, but C# is jit-compiled sooo...
If REST applications are supposed to be stateless, how do you manage sessions?
Stateless here means that state or meta data of request is not maintained on server side. By maintaining each request or user's state on server, it would lead to performance bottlenecks. Server is just requested with required attributes to perform any specific operations.
Coming to managing sessions, or giving customize experience to users, it requires to maintain some meta data or state of user likely user's preferences, past request history. This can be done by maintaining cookies, hidden attributes or into session object.
This can maintain or keep track of user's state in the application.
Hope this helps!
Determine .NET Framework version for dll
In PowerShell you can use the following to get the target runtime:
$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).ImageRuntimeVersion
I adapted this to PowerShell from Ben Griswold's answer.
If you want to know the target framework version specified in Visual Studio, use:
$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq "TargetFrameworkAttribute" } |
Select-Object -ExpandProperty ConstructorArguments |
Select-Object -ExpandProperty value
You should get something like
.NETFramework,Version=v4.5.2
How to add buttons dynamically to my form?
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
private void button1_Click(object sender, EventArgs e)
{
int h =3;
Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(20, 43);
buttonArray[i].Name= ""+i+"";
buttonArray[i].Click += button_Click;//function
buttonArray[i].Location = new Point(40, 20 + (i * 20));
panel1.Controls.Add(buttonArray[i]);
} }
What is secret key for JWT based authentication and how to generate it?
What is the secret key does, you may have already known till now.
It is basically HMAC SH256 (Secure Hash).
The Secret is a symmetrical key.
Using the same key you can generate, & reverify, edit, etc.
For more secure, you can go with private, public key (asymmetric way).
Private key to create token, public key to verify at client level.
Coming to secret key what to give
You can give anything, "sudsif", "sdfn2173", any length
you can use online generator, or manually write
I prefer using openssl
C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg
generate, then encode with base 64
C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20
The generated value is saved inside the file named "openssl-secret.txt"
generate, & store into a file.
One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.
I recommend reading this article
https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/
JQuery get all elements by class name
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
C# Macro definitions in Preprocessor
Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).
Increment value in mysql update query
Hope I'm not going offtopic on my first post, but I'd like to expand a little on the casting of integer to string as some respondents appear to have it wrong.
Because the expression in this query uses an arithmetic operator (the plus symbol +), MySQL will convert any strings in the expression to numbers.
To demonstrate, the following will produce the result 6:
SELECT ' 05.05 '+'.95';
String concatenation in MySQL requires the CONCAT() function so there is no ambiguity here and MySQL converts the strings to floats and adds them together.
I actually think the reason the initial query wasn't working is most likely because the $points variable was not in fact set to the user's current points. It was either set to zero, or was unset: MySQL will cast an empty string to zero. For illustration, the following will return 0:
SELECT ABS('');
Like I said, I hope I'm not being too off-topic. I agree that Daan and Tomas have the best solutions for this particular problem.
Jquery Open in new Tab (_blank)
Replace this line:
$(this).target = "_blank";
With:
$( this ).attr( 'target', '_blank' );
That will set its HREF to _blank.
How to use Servlets and Ajax?
$.ajax({
type: "POST",
url: "url to hit on servelet",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Info has been added to the list successfully.<br>"+
"The Details are as follws : <br> Name : ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
ngModel cannot be used to register form controls with a parent formGroup directive
This error apears when you have some form controls (like Inputs, Selects, etc) in your form group tags with no formControlName property.
Those examples throws the error:
<form [formGroup]="myform">
<input type="text">
<input type="text" [ngmodel]="nameProperty">
<input type="text" [formGroup]="myform" [name]="name">
</fom>
There are two ways, the stand alone:
<form [formGroup]="myform">
<input type="text" [ngModelOptions]="{standalone: true}">
<input type="text" [ngmodel]="nameProperty" [ngModelOptions]="{standalone: true}">
<!-- input type="text" [formGroup]="myform" [name]="name" --> <!-- no works with standalone --
</form>
Or including it into the formgroup
<form [formGroup]="myform">
<input type="text" formControlName="field1">
<input type="text" formControlName="nameProperty">
<input type="text" formControlName="name">
</fom>
The last one implies to define them in the initialization formGroup
this.myForm = new FormGroup({
field1: new FormControl(''),
nameProperty: new FormControl(''),
name: new FormControl('')
});
Convert seconds into days, hours, minutes and seconds
foreach ($email as $temp => $value) {
$dat = strtotime($value['subscription_expiration']); //$value come from mysql database
//$email is an array from mysqli_query()
$date = strtotime(date('Y-m-d'));
$_SESSION['expiry'] = (((($dat - $date)/60)/60)/24)." Days Left";
//you will get the difference from current date in days.
}
$value come from Database. This code is in Codeigniter. $SESSION is used for storing user subscriptions. it is mandatory. I used it in my case, you can use whatever you want.
Zero-pad digits in string
There's also str_pad
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
SQL query for today's date minus two months
If you are using SQL Server try this:
SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())
Based on your update it would be:
SELECT * FROM FB WHERE Dte < DATEADD(month, -2, GETDATE())
How to show what a commit did?
The answers by Bomber and Jakub (Thanks!) are correct and work for me in different situations.
For a quick glance at what was in the commit, I use
git show <replace this with your commit-id>
But I like to view a graphical Diff when studying something in detail and have set up a P4diff as my git diff and then use
git diff <replace this with your commit-id>^!
Use a loop to plot n charts Python
We can create a for loop and pass all the numeric columns into it.
The loop will plot the graphs one by one in separate pane as we are including
plt.figure() into it.
import pandas as pd
import seaborn as sns
import numpy as np
numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.
for i in data[numeric_features].columns:
plt.figure(figsize=(12,5))
plt.title(i)
sns.boxplot(data=data[i])
Best way to format multiple 'or' conditions in an if statement (Java)
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
Predicate Delegates in C#
Just a delegate that returns a boolean. It is used a lot in filtering lists but can be used wherever you'd like.
List<DateRangeClass> myList = new List<DateRangeClass<GetSomeDateRangeArrayToPopulate);
myList.FindAll(x => (x.StartTime <= minDateToReturn && x.EndTime >= maxDateToReturn):
How do I remove a comma off the end of a string?
This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:
if (substr($string, -1, 1) == ',')
{
$string = substr($string, 0, -1);
}
If you want to remove all commas from the end of a line use the simpler:
$string = rtrim($string, ',');
The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:
$string = rtrim($string, ", \t\n");
How can I use threading in Python?
For me, the perfect example for threading is monitoring asynchronous events. Look at this code.
# thread_test.py
import threading
import time
class Monitor(threading.Thread):
def __init__(self, mon):
threading.Thread.__init__(self)
self.mon = mon
def run(self):
while True:
if self.mon[0] == 2:
print "Mon = 2"
self.mon[0] = 3;
You can play with this code by opening an IPython session and doing something like:
>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2
Wait a few minutes
>>> a[0] = 2
Mon = 2
How to overlay density plots in R?
You can use the ggjoy
package. Let's say that we have three different beta
distributions such as:
set.seed(5)
b1<-data.frame(Variant= "Variant 1", Values = rbeta(1000, 101, 1001))
b2<-data.frame(Variant= "Variant 2", Values = rbeta(1000, 111, 1011))
b3<-data.frame(Variant= "Variant 3", Values = rbeta(1000, 11, 101))
df<-rbind(b1,b2,b3)
You can get the three different distributions as follows:
library(tidyverse)
library(ggjoy)
ggplot(df, aes(x=Values, y=Variant))+
geom_joy(scale = 2, alpha=0.5) +
scale_y_discrete(expand=c(0.01, 0)) +
scale_x_continuous(expand=c(0.01, 0)) +
theme_joy()
Difference between __getattr__ vs __getattribute__
Lets see some simple examples of both __getattr__
and __getattribute__
magic methods.
__getattr__
Python will call __getattr__
method whenever you request an attribute that hasn't already been defined. In the following example my class Count has no __getattr__
method. Now in main when I try to access both obj1.mymin
and obj1.mymax
attributes everything works fine. But when I try to access obj1.mycurrent
attribute -- Python gives me AttributeError: 'Count' object has no attribute 'mycurrent'
class Count():
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent) --> AttributeError: 'Count' object has no attribute 'mycurrent'
Now my class Count has __getattr__
method. Now when I try to access obj1.mycurrent
attribute -- python returns me whatever I have implemented in my __getattr__
method. In my example whenever I try to call an attribute which doesn't exist, python creates that attribute and set it to integer value 0.
class Count:
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
def __getattr__(self, item):
self.__dict__[item]=0
return 0
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent1)
__getattribute__
Now lets see the __getattribute__
method. If you have __getattribute__
method in your class, python invokes this method for every attribute regardless whether it exists or not. So why we need __getattribute__
method? One good reason is that you can prevent access to attributes and make them more secure as shown in the following example.
Whenever someone try to access my attributes that starts with substring 'cur' python raises AttributeError
exception. Otherwise it returns that attribute.
class Count:
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
Important: In order to avoid infinite recursion in __getattribute__
method, its implementation should always call the base class method with the same name to access any attributes it needs. For example: object.__getattribute__(self, name)
or super().__getattribute__(item)
and not self.__dict__[item]
IMPORTANT
If your class contain both getattr and getattribute magic methods then __getattribute__
is called first. But if __getattribute__
raises
AttributeError
exception then the exception will be ignored and __getattr__
method will be invoked. See the following example:
class Count(object):
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None
def __getattr__(self, item):
self.__dict__[item]=0
return 0
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)
# note this class subclass object
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
Undefined reference to main - collect2: ld returned 1 exit status
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
Enumerations on PHP
Here is a github library for handling type-safe enumerations in php:
This library handle classes generation, classes caching and it implements the Type Safe Enumeration design pattern, with several helper methods for dealing with enums, like retrieving an ordinal for enums sorting, or retrieving a binary value, for enums combinations.
The generated code use a plain old php template file, which is also configurable, so you can provide your own template.
It is full test covered with phpunit.
php-enums on github (feel free to fork)
Usage: (@see usage.php, or unit tests for more details)
<?php
//require the library
require_once __DIR__ . '/src/Enum.func.php';
//if you don't have a cache directory, create one
@mkdir(__DIR__ . '/cache');
EnumGenerator::setDefaultCachedClassesDir(__DIR__ . '/cache');
//Class definition is evaluated on the fly:
Enum('FruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'));
//Class definition is cached in the cache directory for later usage:
Enum('CachedFruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'), '\my\company\name\space', true);
echo 'FruitsEnum::APPLE() == FruitsEnum::APPLE(): ';
var_dump(FruitsEnum::APPLE() == FruitsEnum::APPLE()) . "\n";
echo 'FruitsEnum::APPLE() == FruitsEnum::ORANGE(): ';
var_dump(FruitsEnum::APPLE() == FruitsEnum::ORANGE()) . "\n";
echo 'FruitsEnum::APPLE() instanceof Enum: ';
var_dump(FruitsEnum::APPLE() instanceof Enum) . "\n";
echo 'FruitsEnum::APPLE() instanceof FruitsEnum: ';
var_dump(FruitsEnum::APPLE() instanceof FruitsEnum) . "\n";
echo "->getName()\n";
foreach (FruitsEnum::iterator() as $enum)
{
echo " " . $enum->getName() . "\n";
}
echo "->getValue()\n";
foreach (FruitsEnum::iterator() as $enum)
{
echo " " . $enum->getValue() . "\n";
}
echo "->getOrdinal()\n";
foreach (CachedFruitsEnum::iterator() as $enum)
{
echo " " . $enum->getOrdinal() . "\n";
}
echo "->getBinary()\n";
foreach (CachedFruitsEnum::iterator() as $enum)
{
echo " " . $enum->getBinary() . "\n";
}
Output:
FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)
FruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)
FruitsEnum::APPLE() instanceof Enum: bool(true)
FruitsEnum::APPLE() instanceof FruitsEnum: bool(true)
->getName()
APPLE
ORANGE
RASBERRY
BANNANA
->getValue()
apple
orange
rasberry
bannana
->getValue() when values have been specified
pig
dog
cat
bird
->getOrdinal()
1
2
3
4
->getBinary()
1
2
4
8
Fragment onResume() & onPause() is not called on backstack
Here's my more robust version of Gor's answer (using fragments.size()is unreliable due to size not being decremented after fragment is popped)
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getFragmentManager() != null) {
Fragment topFrag = NavigationHelper.getCurrentTopFragment(getFragmentManager());
if (topFrag != null) {
if (topFrag instanceof YourFragment) {
//This fragment is being shown.
} else {
//Navigating away from this fragment.
}
}
}
}
});
And the 'getCurrentTopFragment' method:
public static Fragment getCurrentTopFragment(FragmentManager fm) {
int stackCount = fm.getBackStackEntryCount();
if (stackCount > 0) {
FragmentManager.BackStackEntry backEntry = fm.getBackStackEntryAt(stackCount-1);
return fm.findFragmentByTag(backEntry.getName());
} else {
List<Fragment> fragments = fm.getFragments();
if (fragments != null && fragments.size()>0) {
for (Fragment f: fragments) {
if (f != null && !f.isHidden()) {
return f;
}
}
}
}
return null;
}
Minimum Hardware requirements for Android development
I use an i5 processor with 4Gb RAM. It works very well. I feel this is the minimum configuration required to run both eclipse and android avd simultaneously.
Just an old processor with high RAM is not sufficient.
How to disable logging on the standard error stream in Python?
Logging has the following structure:
- loggers are arranged according to a namespace hierarchy with dot separators;
- each logger has a level (
logging.WARNING
by default for the root logger and logging.NOTSET
by default for non-root loggers) and an effective level (the effective level of the parent logger for non-root loggers with a level logging.NOTSET
and the level of the logger otherwise);
- each logger has a list of filters;
- each logger has a list of handlers;
- each handler has a level (
logging.NOTSET
by default);
- each handler has a list of filters.
Logging has the following process (represented by a flowchart):
Therefore to disable a particular logger you can do one of the following:
Set the level of the logger to logging.CRITICAL + 1
.
Using the main API:
import logging
logger = logging.getLogger("foo")
logger.setLevel(logging.CRITICAL + 1)
Using the config API:
import logging.config
logging.config.dictConfig({
"version": 1,
"loggers": {
"foo": {
"level": logging.CRITICAL + 1
}
}
})
Add a filter lambda record: False
to the logger.
Using the main API:
import logging
logger = logging.getLogger("foo")
logger.addFilter(lambda record: False)
Using the config API:
import logging.config
logging.config.dictConfig({
"version": 1,
"filters": {
"all": {
"()": lambda: (lambda record: False)
}
},
"loggers": {
"foo": {
"filters": ["all"]
}
}
})
Remove the existing handlers of the logger, add a handler logging.NullHandler()
to the logger (to prevent events from being handled by the handler logging.lastResort
which is a logging.StreamHandler
using the current stream sys.stderr
and a level logging.WARNING
) and set the attribute propagate
of the logger to False
(to prevent events from being handled by the handlers of the ancestor loggers of the logger).
Using the main API:
import logging
logger = logging.getLogger("foo")
for handler in logger.handlers.copy():
logger.removeHandler(handler)
logger.addHandler(logging.NullHandler())
logger.propagate = False
Using the config API:
import logging.config
logging.config.dictConfig({
"version": 1,
"handlers": {
"null": {
"class": "logging.NullHandler"
}
},
"loggers": {
"foo": {
"handlers": ["null"],
"propagate": False
}
}
})
Warning. — Contrary to approaches 1 and 2 which only prevent events logged by the logger from being emitted by the handlers of the logger and its ancestor loggers, approach 3 also prevents events logged by the descendant loggers of the logger (e.g. logging.getLogger("foo.bar")
) to be emitted by the handlers of the logger and its ancestor loggers.
Note. — Setting the attribute disabled
of the logger to True
is not yet another approach, as it is not part of the public API. See https://bugs.python.org/issue36318:
import logging
logger = logging.getLogger("foo")
logger.disabled = True # DO NOT DO THIS
SQL Inner Join On Null Values
Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:
SELECT * FROM `Y` INNER JOIN `X` ON (`Y`.`QID` IS NOT NULL AND `X`.`QID` IS NOT NULL);
This gives you every non-null row in Y joined to every non-null row in X.
Update: Rico says he also wants the rows with NULL values, why not just:
SELECT * FROM `Y` INNER JOIN `X`;
Change the On/Off text of a toggle button Android
You can use the following to set the text from the code:
toggleButton.setText(textOff);
// Sets the text for when the button is first created.
toggleButton.setTextOff(textOff);
// Sets the text for when the button is not in the checked state.
toggleButton.setTextOn(textOn);
// Sets the text for when the button is in the checked state.
To set the text using xml, use the following:
android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked."
This information is from here
Split a vector into chunks
Yet another possibility is the splitIndices
function from package parallel
:
library(parallel)
splitIndices(20, 3)
Gives:
[[1]]
[1] 1 2 3 4 5 6 7
[[2]]
[1] 8 9 10 11 12 13
[[3]]
[1] 14 15 16 17 18 19 20
What does "./" (dot slash) refer to in terms of an HTML file path location?
For example css files are in folder named CSS
and html files are in folder HTML
, and both these are in folder named XYZ
means we refer css files in html as
<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />
Here ..
moves up to HTML
and .
refers to the current directory XYZ
---by this logic you would just reference as:
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
Print a div content using Jquery
use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
What is the difference between varchar and varchar2 in Oracle?
As for now, they are synonyms.
VARCHAR
is reserved by Oracle
to support distinction between NULL
and empty string in future, as ANSI
standard prescribes.
VARCHAR2
does not distinguish between a NULL
and empty string, and never will.
If you rely on empty string and NULL
being the same thing, you should use VARCHAR2
.
concatenate variables
Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:
rem The retail files set
set FILES_SET="(*.exe *.dll"
rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"
rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
rem Append the closing bracket
set FILES_SET=%FILES_SET%)
echo %FILES_SET%
Cheers...
Save file/open file dialog box, using Swing & Netbeans GUI editor
I think you face three problems:
- understanding the FileChooser
- writing/reading files
- understanding extensions and file formats
ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)
ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.
ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.
-bash: export: `=': not a valid identifier
I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.
Scenario 1: There cannot be spaces beside the =
(equals) sign
$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question
$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier
$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier
Scenario 2: Object value assignment should not have spaces besides quotes
$ export TEMP_ENV={ "key" : "json example" }
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier
Scenario 3: List value assignment should not have spaces between values
$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier
I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.
How to compare two dates to find time difference in SQL Server 2005, date manipulation
Try this in Sql Server
SELECT
start_date as firstdate,end_date as seconddate
,cast(datediff(MI,start_date,end_date)as decimal(10,3)) as minutediff
,cast(cast(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) as int ) as varchar(10)) + ' ' + 'Days' + ' '
+ cast(cast((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) -
floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)) ) * 24 as int) as varchar(10)) + ':'
+ cast( cast(((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)
- floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24
-
cast(floor((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)
- floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24) as decimal)) * 60 as int) as varchar(10))
FROM [AdventureWorks2012].dbo.learndate
Python csv string to array
Use this to have a csv loaded into a list
import csv
csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
['2nd_line', '0']]
How to list all databases in the mongo shell?
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
Plotting 4 curves in a single plot, with 3 y-axes
In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:
clear
clc
x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];
xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;
for i=1:N_
L=1-(numberOfExtraPlots*a)-0.2;
axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
if(i==1)
color = [rand(1),rand(1),rand(1)];
figure('Units','pixels','Position',[200 200 1200 600])
axes('Units','normalized','Position',axesPosition,...
'Color','w','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'NextPlot','add');
plot(x,Y(i,:),'Color',color);
xlabel('Time (s)');
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
else
color = [rand(1),rand(1),rand(1)];
axes('Units','normalized','Position',axesPosition,...
'Color','none','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
V = (xWidth*a*(i-1))/L;
b=xLimit+[V 0];
x_=linspace(b(1),b(2),10);
plot(x_,Y(i,:),'Color',color);
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
end
end
The code above will produce something like this:
How do I fire an event when a iframe has finished loading in jQuery?
Here is what I do for any action and it works in Firefox, IE, Opera, and Safari.
<script type="text/javascript">
$(document).ready(function(){
doMethod();
});
function actionIframe(iframe)
{
... do what ever ...
}
function doMethod()
{
var iFrames = document.getElementsByTagName('iframe');
// what ever action you want.
function iAction()
{
// Iterate through all iframes in the page.
for (var i = 0, j = iFrames.length; i < j; i++)
{
actionIframe(iFrames[i]);
}
}
// Check if browser is Safari or Opera.
if ($.browser.safari || $.browser.opera)
{
// Start timer when loaded.
$('iframe').load(function()
{
setTimeout(iAction, 0);
}
);
// Safari and Opera need something to force a load.
for (var i = 0, j = iFrames.length; i < j; i++)
{
var iSource = iFrames[i].src;
iFrames[i].src = '';
iFrames[i].src = iSource;
}
}
else
{
// For other good browsers.
$('iframe').load(function()
{
actionIframe(this);
}
);
}
}
</script>
biggest integer that can be stored in a double
The largest integer that can be represented in IEEE 754 double (64-bit) is the same as the largest value that the type can represent, since that value is itself an integer.
This is represented as 0x7FEFFFFFFFFFFFFF
, which is made up of:
- The sign bit 0 (positive) rather than 1 (negative)
- The maximum exponent
0x7FE
(2046 which represents 1023 after the bias is subtracted) rather than 0x7FF
(2047 which indicates a NaN
or infinity).
- The maximum mantissa
0xFFFFFFFFFFFFF
which is 52 bits all 1.
In binary, the value is the implicit 1 followed by another 52 ones from the mantissa, then 971 zeros (1023 - 52 = 971) from the exponent.
The exact decimal value is:
179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
This is approximately 1.8 x 10308.
How do I switch between command and insert mode in Vim?
Coming from emacs I've found that I like ctrl +
keys to do stuff, and in vim I've found that both [ctrl + C]
and [alt + backspace]
will enter Normal mode from insert mode. You might try and see if any of those works out for you.
How do you use youtube-dl to download live streams (that are live)?
I'll be using this Live Event from NASA TV as an example:
https://www.youtube.com/watch?v=21X5lGlDOfg
First, list the formats for the video:
$ ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code extension resolution note
91 mp4 256x144 HLS 197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92 mp4 426x240 HLS 338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93 mp4 640x360 HLS 829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300 mp4 1280x720 3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)
Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
for this example:
? ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8
Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).
Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:
ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts
struct in class
If you give the struct no name it will work
class E
{
public:
struct
{
int v;
};
};
Otherwise write X x and write e.x.v
Submit a form in a popup, and then close the popup
I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.
First, I utilize the onsubmit
event in the form, and pass this
to the function to make it easier to deal with this particular form.
<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.
<script type="text/javascript">
function closeSelf (f) {
f.submit();
window.close();
}
</script>
Hope this helps someone out. Enjoy!
Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin
First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.
<form action="/system/wpacert" method="post" enctype="multipart/form-data" id="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#certform').ajaxForm(function () {
window.close();
});
});
</script>
Update rows in one table with data from another table based on one column in each being equal
update
table1 t1
set
(
t1.column1,
t1.column2
) = (
select
t2.column1,
t2.column2
from
table2 t2
where
t2.column1 = t1.column1
)
where exists (
select
null
from
table2 t2
where
t2.column1 = t1.column1
);
Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):
update
table1 t1
set
(
t1.column1,
t1.column2
) = (
select
t2.column1,
t2.column2
from
table2 t2
where
t2.column1 = t1.column1
and
rownum = 1
)
where exists (
select
null
from
table2 t2
where
t2.column1 = t1.column1
);
"multiple target patterns" Makefile error
I met with the same error.
After struggling, I found that it was due to "Space" in the folder name.
For example :
Earlier My folder name was :
"Qt Projects"
Later I changed it to :
"QtProjects"
and my issue was resolved.
Its very simple but sometimes a major issue.
Disable button in WPF?
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
Resizing UITableView to fit content
based on
fl034's answer
SWift 5
var tableViewHeight: NSLayoutConstraint?
tableViewHeight = NSLayoutConstraint(item: servicesTableView,
attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute,
multiplier: 0.0, constant: 10)
tableViewHeight?.isActive = true
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tableViewHeight?.constant = tableView.contentSize.height
tableView.layoutIfNeeded()
}
rails generate model
The error shows you either didn't create the rails project yet or you're not in the rails project directory.
Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.
Example: Assuming you didn't create the Rails app yet:
$> rails new myapp
$> cd myapp
Now generate the model from your commandline.
$> rails generate model your_model_name
Getting current date and time in JavaScript
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))
How should I use Outlook to send code snippets?
Would sending the mail as plain-text sort this?
"How to Send a Plain Text Message in Outlook":
- Select Actions | New Mail Message Using | Plain Text from the menu in Outlook.
- Create your message as usual.
- Click Send to deliver it.
Being plain text it shouldn't screw up your code, with "smart" quotes, auto-capitalisation and such.
Another possible option, if this is a common problem within the company perhaps you could setup an internal code-paste site, there's plenty of open-source ones around, like Open Pastebin
Closing database connections in Java
Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.
You should do this with any object that implements AutoClosable.
try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
String sqlToExecute = "SELECT * FROM persons";
try (ResultSet resultSet = statement.execute(sqlToExecute)) {
if (resultSet.next()) {
System.out.println(resultSet.getString("name");
}
}
} catch (SQLException e) {
System.out.println("Failed to select persons.");
}
The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.
Conversion between UTF-8 ArrayBuffer and String
This should work:
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <[email protected]>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
function Utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
len = array.length;
i = 0;
while (i < len) {
c = array[i++];
switch (c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.
Check out the JSFiddle demo.
Also see the related questions: here, here
java.lang.IllegalArgumentException: View not attached to window manager
I had the same problem, you can solve it by:
@Override
protected void onPostExecute(MyResult result) {
try {
if ((this.mDialog != null) && this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.mDialog = null;
}
}
Query comparing dates in SQL
Instead of '2013-04-12' whose meaning depends on the local culture, use '20130412' which is recognized as the culture invariant format.
If you want to compare with December 4th, you should write '20131204'. If you want to compare with April 12th, you should write '20130412'.
The article Write International Transact-SQL Statements from SQL Server's documentation explains how to write statements that are culture invariant:
Applications that use other APIs, or Transact-SQL scripts, stored procedures, and triggers, should use the unseparated numeric strings. For example, yyyymmdd as 19980924.
EDIT
Since you are using ADO, the best option is to parameterize the query and pass the date value as a date parameter. This way you avoid the format issue entirely and gain the performance benefits of parameterized queries as well.
UPDATE
To use the the the ISO 8601 format in a literal, all elements must be specified. To quote from the ISO 8601 section of datetime's documentation
To use the ISO 8601 format, you must specify each element in the format. This also includes the T, the colons (:), and the period (.) that are shown in the format.
... the fraction of second component is optional. The time component is specified in the 24-hour format.
How do I get which JRadioButton is selected from a ButtonGroup
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJRadioButton extends JFrame implements ActionListener
{
JRadioButton rb1,rb2; //components
ButtonGroup bg;
MyJRadioButton()
{
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1=new JRadioButton("male");
rb2=new JRadioButton("female");
//add radio button to button group
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//add radio buttons to frame,not button group
add(rb1);
add(rb2);
//add action listener to JRadioButton, not ButtonGroup
rb1.addActionListener(this);
rb2.addActionListener(this);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}
}
How to downgrade to older version of Gradle
Change your gradle version in project setting:
If you are using mac,click File->Project structure,then change gradle version,here:
And check your build.gradle of project,change dependency of gradle,like this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
}
}
Sort an array of objects in React and render them
This might be what you're looking for:
// ... rest of code
// copy your state.data to a new array and sort it by itemM in ascending order
// and then map
const myData = [].concat(this.state.data)
.sort((a, b) => a.itemM > b.itemM ? 1 : -1)
.map((item, i) =>
<div key={i}> {item.matchID} {item.timeM}{item.description}</div>
);
// render your data here...
The method sort
will mutate the original array . Hence I create a new array using the concat
method. The sorting on the field itemM
should work on sortable entities like string and numbers.
To delay JavaScript function call using jQuery
Since you declare sample
inside the anonymous function you pass to ready
, it is scoped to that function.
You then pass a string to setTimeout
which is eval
ed after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout
, using eval is inefficient and hard to debug.
setTimeout(sample,2000)
Spring boot Security Disable security
You need to add this entry to application.properties to bypass Springboot Default Security
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
Then there won't be any authentication box.
otrws, credentials are:-
user
and 99b962fa-1848-4201-ae67-580bdeae87e9
(password randomly generated)
Note: my springBootVersion = '1.5.14.RELEASE'
'\r': command not found - .bashrc / .bash_profile
I am using cygwin and Windows7, the trick was NOT to put the set -o igncr
into your .bashrc but put the whole SHELLOPTS
into you environment variables under Windows. (So nothing with unix / cygwin...) I think it does not work from .bashrc
because "the drops is already sucked"
as we would say in german. ;-)
So my SHELLOPTS
looks like this
braceexpand:emacs:hashall:histexpand:history:igncr:interactive-comments:monitor
How to make a edittext box in a dialog
Wasim's answer lead me in the right direction but I had to make some changes to get it working for my current project.
I am using this function in a fragment and calling it on button click.
fun showPostDialog(title: String) {
val alert = AlertDialog.Builder(activity)
val edittext = EditText(activity)
edittext.hint = "Enter Name"
edittext.maxLines = 1
var layout = activity?.let { FrameLayout(it) }
//set padding in parent layout
// layout.isPaddingRelative(45,15,45,0)
layout?.setPadding(45,15,45,0)
alert.setTitle(title)
layout?.addView(edittext)
alert.setView(layout)
alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {
dialog, which ->
run {
val qName = edittext.text.toString()
showToast("Posted to leaderboard successfully")
view?.hideKeyboard()
}
})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {
dialog, which ->
run {
dialog.dismiss()
}
})
alert.show()
}
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
fun showToast(message: String) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
}
I hope it helps someone else in the near future.
Happy coding!
PHP XML how to output nice format
You can try to do this:
...
// get completed xml document
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml_string = $doc->saveXML();
echo $xml_string;
You can make set these parameter right after you've created the DOMDocument
as well:
$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
That's probably more concise. Output in both cases is (Demo):
<?xml version="1.0"?>
<root>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
</root>
I'm not aware how to change the indentation character(s) with DOMDocument
. You could post-process the XML with a line-by-line regular-expression based replacing (e.g. with preg_replace
):
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
Alternatively, there is the tidy extension with tidy_repair_string
which can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Most efficient way to check if a file is empty in Java on Windows
Now both these methods fail at times when the log file is empty (has no content), yet the file size is not zero (2 bytes).
Actually, I think you will find that the file is NOT empty. Rather I think that you will find that those two characters are a CR and a NL; i.e. the file consists of one line that is empty.
If you want to test if a file is either empty or has a single empty line then a simple, relatively efficient way is:
try (BufferedReader br = new BufferedReader(FileReader(fileName))) {
String line = br.readLine();
if (line == null ||
(line.length() == 0 && br.readLine() == null)) {
System.out.println("NO ERRORS!");
} else {
System.out.println("SOME ERRORS!");
}
}
Can we do this more efficiently? Possibly. It depends on how often you have to deal with the three different cases:
- a completely empty file
- a file consisting of a single empty line
- a file with a non-empty line, or multiple lines.
You can probably do better by using Files.length()
and / or reading just the first two bytes. However, the problems include:
- If you both test the file size AND read the first few bytes then you are making 2 syscalls.
- The actual line termination sequence could be CR, NL or CR NL, depending on the platform. (I know you say this is for Windows, but what happens if you need to port your application? Or if someone sends you a non-Windows file?)
- It would be nice to avoid setting up stream / reader stack, but the file's character encoding could map CR and NL to something other than the bytes
0x0d
and 0x0a
. (For example ... UTF-16)
- Then there's the annoying habit of some Windows utilities have putting BOM markers into UTF-8 encoded files. (This would even mess up the simple version above!)
All of this means that the most efficient possible solution is going to be rather complicated.
When do I use path params vs. query params in a RESTful API?
Segmentation is more hierarchal and "pretty" but can be limiting.
For example, if you have a url with three segments, each one passing different parameters to search for a car via make, model and color:
www.example.com/search/honda/civic/blue
This is a very pretty url and more easily remembered by the end user, but now your kind of stuck with this structure. Say you want to make it so that in the search the user could search for ALL blue cars, or ALL Honda Civics? A query parameter solves this because it give a key value pair. So you could pass:
www.example.com/search?color=blue
www.example.com/search?make=civic
Now you have a way to reference the value via it's key - either "color" or "make" in your query code.
You could get around this by possibly using more segments to create a kind of key value structure like:
www.example.com/search/make/honda/model/civic/color/blue
Hope that makes sense..
Counting the number of files in a directory using Java
If you have directories containing really (>100'000) many files, here is a (non-portable) way to go:
String directoryPath = "a path";
// -f flag is important, because this way ls does not sort it output,
// which is way faster
String[] params = { "/bin/sh", "-c",
"ls -f " + directoryPath + " | wc -l" };
Process process = Runtime.getRuntime().exec(params);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String fileCount = reader.readLine().trim() - 2; // accounting for .. and .
reader.close();
System.out.println(fileCount);
Animation CSS3: display + opacity
On absolute or fixed elements you could also use z-index:
.item {
position: absolute;
z-index: -100;
}
.item:hover {
z-index: 100;
}
Other elements should have a z-index between -100 and 100 now.
How to connect PHP with Microsoft Access database
If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec()
approach. Here is a simple example:
<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql =
"SELECT AgentName FROM Agents " .
"WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);
// query parameter value(s)
$params = array(
5,
'Homer'
);
$sth->execute($params);
while ($row = $sth->fetch()) {
echo $row['AgentName'] . "\r\n";
}
NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF
. If you do need to support such characters then neither PDO_ODBC
nor the old odbc_
functions will work; you'll need to use the solution described in this answer.
Trigger validation of all fields in Angular Form submit
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
What exactly is the difference between Web API and REST API in MVC?
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
REST
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
RESTful
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
Web API
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
Android global variable
You could use application preferences. They are accessible from any activity or piece of code as long as you pass on the Context object, and they are private to the application that uses them, so you don't need to worry about exposing application specific values, unless you deal with routed devices. Even so, you could use hashing or encryption schemes to save the values. Also, these preferences are stored from an application run to the next.
Here is some code examples that you can look at.
Creating a thumbnail from an uploaded image
Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
How to hide column of DataGridView when using custom DataSource?
In some cases, it might be a bad idea to first add the column to the DataGridView and then hide it.
I for example have a class that has an NHibernate proxy for an Image property for company logos. If I accessed that property (e.g. by calling its ToString method to show that in a DataGridView), it would download the image from the SQL server. If I had a list of Company objects and used that as the dataSource of the DataGridView like that, then (I suspect) it would download ALL the logos BEFORE I could hide the column.
To prevent this, I used the custom attribute
[System.ComponentModel.Browsable(false)]
on the image property, so that the DataGridView ignores the property (doesn't create the column and doesn't call the ToString methods).
public class Company
{
...
[System.ComponentModel.Browsable(false)]
virtual public MyImageClass Logo { get; set;}
Change action bar color in android
If you use Android default action bar then. If you change from java then some time show previous color.
Example
Then your action bar code inside "app_bar_main". So go inside app_bar_main.xml and just add Background.
Example
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#33691e" <!--use your color -->
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main1" />
Set background color of WPF Textbox in C# code
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;
WPF Foreground and Background is of type System.Windows.Media.Brush
. You can set another color like this:
using System.Windows.Media;
textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;
Get MIME type from filename extension
You can use MimeMappings class. I think this is the easiest way. I give import of MimeMappings too. because I felt lots of trouble to find import of those classes.
import org.springframework.boot.web.server.MimeMappings;
MimeMappings mm=new MimeMappings();
String mimetype = mm.get(fileExtension);
System.out.println(mimetype);
Pure CSS scroll animation
And for webkit enabled browsers I've had good results with:
.myElement {
-webkit-overflow-scrolling: touch;
scroll-behavior: smooth; // Added in from answer from Felix
overflow-x: scroll;
}
This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!
Hope that helps,
Ed
Setting environment variable in react-native?
i have created a pre build script for the same problem because i need some differents api endpoints for the differents environments
const fs = require('fs')
let endPoint
if (process.env.MY_ENV === 'dev') {
endPoint = 'http://my-api-dev/api/v1'
} else if (process.env.MY_ENV === 'test') {
endPoint = 'http://127.0.0.1:7001'
} else {
endPoint = 'http://my-api-pro/api/v1'
}
let template = `
export default {
API_URL: '${endPoint}',
DEVICE_FINGERPRINT: Math.random().toString(36).slice(2)
}
`
fs.writeFile('./src/constants/config.js', template, function (err) {
if (err) {
return console.log(err)
}
console.log('Configuration file has generated')
})
And i have created a custom npm run scripts
to execute react-native run..
My package-json
"scripts": {
"start-ios": "node config-generator.js && react-native run-ios",
"build-ios": "node config-generator.js && react-native run-ios --configuration Release",
"start-android": "node config-generator.js && react-native run-android",
"build-android": "node config-generator.js && cd android/ && ./gradlew assembleRelease",
...
}
Then in my services components simply import the auto generated file:
import config from '../constants/config'
fetch(`${config.API_URL}/login`, params)
Convert YYYYMMDD string date to a datetime value
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
HAX kernel module is not installed
After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)
Detect if range is empty
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx) . So you must check every cell in range separately:
Dim thisColumn as Byte, thisRow as Byte
For thisColumn = 1 To 5
For ThisRow = 1 To 6
If IsEmpty(Cells(thisRow, thisColumn)) = False Then
GoTo RangeIsNotEmpty
End If
Next thisRow
Next thisColumn
...........
RangeIsNotEmpty:
Of course here are more code than in solution with CountA function which count not empty cells, but GoTo can interupt loops if at least one not empty cell is found and do your code faster especially if range is large and you need to detect this case. Also this code for me is easier to understand what it is doing, than with Excel CountA function which is not VBA function.
Enter key in textarea
You could do something like this:
_x000D_
_x000D_
$("#txtArea").on("keypress",function(e) {_x000D_
var key = e.keyCode;_x000D_
_x000D_
// If the user has pressed enter_x000D_
if (key == 13) {_x000D_
document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
return true;_x000D_
}_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
_x000D_
_x000D_
Changing background color of ListView items on Android
I tried all answers above .. none worked for me .. this is what worked eventually and is used in my application .. it will provide read/unread list items colors while maintaining listselector styles for both states :
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/selectable_item_background_general"
android:drawSelectorOnTop="true"
android:fadingEdge="none"
android:scrollbarStyle="outsideOverlay"
android:choiceMode="singleChoice" />
selectable_item_background_general.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<item android:state_pressed="false" android:state_focused="true" android:drawable="@drawable/bg_item_selected_drawable" />
<item android:state_pressed="true" android:drawable="@drawable/bg_item_selected_drawable" />
<item android:drawable="@android:color/transparent" />
</selector>
bg_item_selected_drawable.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#12000000" />
</shape>
notification_list_itemlayout.xml :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowItemContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:paddingLeft="16dp"
android:paddingStart="16dp"
android:paddingRight="16dp"
android:paddingEnd="16dp">
<ImageView
android:id="@+id/imgViewIcon"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/cura_logo_symbol_small"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginRight="8dp"
android:layout_marginEnd="8dp" />
<TextView
android:id="@+id/tvNotificationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imgViewIcon"
android:layout_toRightOf="@+id/imgViewIcon"
android:layout_toEndOf="@+id/imgViewIcon"
android:textSize="@dimen/subtitle"
android:textStyle="normal" />
<TextView
android:id="@+id/tvNotificationTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dip"
android:layout_below="@+id/tvNotificationText"
android:layout_toRightOf="@+id/imgViewIcon"
android:layout_toEndOf="@+id/imgViewIcon"
android:textSize="@dimen/subtitle" />
</RelativeLayout>
</RelativeLayout>
Finally, in your adapter :
if (!Model.Read)
rowItemContainer.SetBackgroundColor (Android.Graphics.Color.ParseColor ("#FFFDD0")); // unread color
else
rowItemContainer.SetBackgroundColor (Android.Graphics.Color.White); // read color
Is there a CSS parent selector?
Although there is no parent selector in standard CSS at present, I am working on a (personal) project called axe (ie. Augmented CSS Selector Syntax / ACSSSS) which, among its 7 new selectors, includes both:
- an immediate parent selector
<
(which enables the opposite selection to >
)
- an any ancestor selector
^
(which enables the opposite selection to [SPACE]
)
axe is presently in a relatively early BETA stage of development.
See a demo here:
_x000D_
_x000D_
.parent {
float: left;
width: 180px;
height: 180px;
margin-right: 12px;
background-color: rgb(191, 191, 191);
}
.child {
width: 90px;
height: 90px;
margin: 45px;
background-color: rgb(255, 255, 0);
}
.child.using-axe < .parent {
background-color: rgb(255, 0, 0);
}
_x000D_
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child using-axe"></div>
</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
_x000D_
_x000D_
In the example above <
is the immediate parent selector, so
.child.using-axe < .parent
means:
any immediate parent of .child.using-axe
which is .parent
You could alternatively use:
which would mean:
any immediate parent of .child.using-axe
which is a div
Is it safe to shallow clone with --depth 1, create commits, and pull updates again?
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Twitter bootstrap hide element on small devices
<div class="small hidden-xs">
Some Content Here
</div>
This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.
This answer satisfies the question in the OP title (which is how I found this Q/A).
Plot Normal distribution with Matplotlib
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
How to programmatically set the Image source
myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute));
Don't forget to set Build Action to "Content", and Copy to output directory to "Always".
Obtain form input fields using jQuery?
Late to the party on this question, but this is even easier:
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $(this).serialize();
});
Java Comparator class to sort arrays
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
"Cross origin requests are only supported for HTTP." error when loading a local file
For those on Windows without Python or Node.js, there is still a lightweight solution: Mongoose.
All you do is drag the executable to wherever the root of the server should be, and run it. An icon will appear in the taskbar and it'll navigate to the server in the default browser.
Also, Z-WAMP is a 100% portable WAMP that runs in a single folder, it's awesome. That's an option if you need a quick PHP and MySQL server.
bootstrap responsive table content wrapping
_x000D_
_x000D_
.table td.abbreviation {_x000D_
max-width: 30px;_x000D_
}_x000D_
.table td.abbreviation p {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
_x000D_
}
_x000D_
<table class="table">_x000D_
<tr>_x000D_
<td class="abbreviation"><p>ABC DEF</p></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
Get value from a string after a special character
Here's a way:
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var value = $('input[type="hidden"]')[0].value;
alert(value.split(/\?/)[1]);
});
</script>
</head>
<body>
<input type="hidden" value="/TEST/Name?3" />
</body>
</html>
Execute PHP function with onclick
Solution without page reload
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
<a href="" onclick="removeday(event)" class="deletebtn">Delete</a>
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>
Multiple submit buttons in the same form calling different Servlets
There are several ways to achieve this.
Probably the easiest would be to use JavaScript to change the form's action.
<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">
But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).
Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.
<form action="FirstServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
<input type="submit"value="SecondServlet">
</form>
Note that a form would on submit only send the input data contained in the very same form, not in the other form.
Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name
):
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="action" value="FirstServlet">
<input type="submit" name="action" value="SecondServlet">
</form>
with the following in MainServlet
String action = request.getParameter("action");
if ("FirstServlet".equals(action)) {
// Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
// Invoke SecondServlet's job here.
}
This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?
A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="first" value="FirstServlet">
<input type="submit" name="second" value="SecondServlet">
</form>
with the following in MainServlet
if (request.getParameter("first") != null) {
// Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
// Invoke SecondServlet's job here.
}
Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.
<h:form>
Last Name: <h:inputText value="#{bean.lastName}" size="20" />
<br/><br/>
<h:commandButton value="First" action="#{bean.first}" />
<h:commandButton value="Second" action="#{bean.Second}" />
</h:form>
with just the following javabean instead of a servlet
@ManagedBean
@RequestScoped
public class Bean {
private String lastName; // +getter+setter
public void first() {
// Invoke original FirstServlet's job here.
}
public void second() {
// Invoke original SecondServlet's job here.
}
}
Add a reference column migration in Rails 4
Create a migration file
rails generate migration add_references_to_uploads user:references
Default foreign key name
This would create a user_id column in uploads table as a foreign key
class AddReferencesToUploads < ActiveRecord::Migration[5.2]
def change
add_reference :uploads, :user, foreign_key: true
end
end
user model:
class User < ApplicationRecord
has_many :uploads
end
upload model:
class Upload < ApplicationRecord
belongs_to :user
end
Customize foreign key name:
add_reference :uploads, :author, references: :user, foreign_key: true
This would create an author_id column in the uploads tables as the foreign key.
user model:
class User < ApplicationRecord
has_many :uploads, foreign_key: 'author_id'
end
upload model:
class Upload < ApplicationRecord
belongs_to :user
end
Uncaught TypeError: Cannot read property 'value' of null
I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:
var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
var str2 = document.getElementById("holiday").value;
var str3 = document.getElementById("cal_option").value;
There is either no element with the id cal_preview
, year
, holiday
, cal_option
, or some combination.
Therefore, JavaScript is unable to read the value of something that does not exist.
EDIT:
If you want to check that the element exists first, you could use an if statement for each:
var str,
element = document.getElementById('cal_preview');
if (element != null) {
str = element.value;
}
else {
str = null;
}
You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.
SVG: text inside rect
Programmatically display text over rect using basic Javascript
_x000D_
_x000D_
var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];_x000D_
_x000D_
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text.setAttribute('x', 20);_x000D_
text.setAttribute('y', 50);_x000D_
text.setAttribute('width', 500);_x000D_
text.style.fill = 'red';_x000D_
text.style.fontFamily = 'Verdana';_x000D_
text.style.fontSize = '35';_x000D_
text.innerHTML = "Some text line";_x000D_
_x000D_
svg.appendChild(text);_x000D_
_x000D_
var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text2.setAttribute('x', 20);_x000D_
text2.setAttribute('y', 100);_x000D_
text2.setAttribute('width', 500);_x000D_
text2.style.fill = 'green';_x000D_
text2.style.fontFamily = 'Calibri';_x000D_
text2.style.fontSize = '35';_x000D_
text2.style.fontStyle = 'italic';_x000D_
text2.innerHTML = "Some italic line";_x000D_
_x000D_
_x000D_
svg.appendChild(text2);_x000D_
_x000D_
var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text3.setAttribute('x', 20);_x000D_
text3.setAttribute('y', 150);_x000D_
text3.setAttribute('width', 500);_x000D_
text3.style.fill = 'green';_x000D_
text3.style.fontFamily = 'Calibri';_x000D_
text3.style.fontSize = '35';_x000D_
text3.style.fontWeight = 700;_x000D_
text3.innerHTML = "Some bold line";_x000D_
_x000D_
_x000D_
svg.appendChild(text3);
_x000D_
<svg width="510" height="250" xmlns="http://www.w3.org/2000/svg">_x000D_
<rect x="0" y="0" width="510" height="250" fill="aquamarine" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_
What is the role of the bias in neural networks?
Modification of neuron WEIGHTS alone only serves to manipulate the shape/curvature of your transfer function, and not its equilibrium/zero crossing point.
The introduction of bias neurons allows you to shift the transfer function curve horizontally (left/right) along the input axis while leaving the shape/curvature unaltered.
This will allow the network to produce arbitrary outputs different from the defaults and hence you can customize/shift the input-to-output mapping to suit your particular needs.
See here for graphical explanation:
http://www.heatonresearch.com/wiki/Bias
Difference between text and varchar (character varying)
On PostgreSQL manual
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.
I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html
What's the difference between "end" and "exit sub" in VBA?
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears
all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop
statement instead. You can then resume execution while preserving the value of those variables.
Note The End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears.
Execution continues with the statement following the statement that
called the Sub procedure. Exit Sub can be used only inside a Sub
procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
Using 'sudo apt-get install build-essentials'
In my case, simply "dropping the s" was not the problem (although it is of course a step in the right direction to use the correct package name).
I had to first update the package manager indexes like this:
sudo apt-get update
Then after that the installation worked fine:
sudo apt-get install build-essential
Do Git tags only apply to the current branch?
If you create a tag by e.g.
git tag v1.0
the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.
You can also just refer to the other branch while tagging,
git tag v1.0 name_of_other_branch
which will create the tag to the most recent commit of the other branch.
Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit
git tag v1.0 <sha1>
Animate a custom Dialog
Try below code:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background
View _v = inflater.inflate(R.layout.some_you_layout, container, false);
//load animation
//Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance
_v.setAnimation( transition_in_view );
_v.startAnimation( transition_in_view );
//really beautiful
return _v;
}
Create the custom Anim.: res/anim/customer_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromYDelta="100%"
android:toYDelta="-7%"/>
<translate
android:duration="300"
android:startOffset="500"
android:toYDelta="7%" />
<translate
android:duration="200"
android:startOffset="800"
android:toYDelta="0%" />
</set>
How to remove all namespaces from XML with C#?
And this is the perfect solution that will also remove XSI elements.
(If you remove the xmlns and don't remove XSI, .Net shouts at you...)
string xml = node.OuterXml;
//Regex below finds strings that start with xmlns, may or may not have :and some text, then continue with =
//and ", have a streach of text that does not contain quotes and end with ". similar, will happen to an attribute
// that starts with xsi.
string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
xml = Regex.Replace(xml, strXMLPattern, "");
curl -GET and -X GET
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
Asp.Net MVC with Drop Down List, and SelectListItem Assistance
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
How to use QueryPerformanceCounter?
I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;
The example is just as simple:
LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)
where divisor is 10^3, or 10^6 depending on required resolution.
TypeScript: correct way to do string equality?
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs
One more possible solution: I have a staging server that serves the site and the Cloudfront assets over HTTP. I had my origin set to "Match Viewer" instead of "HTTP Only". I also use the HTTPS Everywhere extension, which redirected all the http://*.cloudfront.net
URLs to the https://*
version. Since the staging server isn't available over SSL and Cloudfront was matching the viewer, it couldn't find the assets at https://example.com
and cached a bunch of 502s instead.
Ajax call Into MVC Controller- Url Issue
starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:
$.ajax({
type: "POST",
url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
how to execute php code within javascript
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
If else on WHERE clause
Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2
if email
is NULL. Mine assumes you want to use email2
if email
is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).
SELECT `id` , `naam`
FROM `klanten`
WHERE `email` LIKE '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE '%[email protected]%')
Best way to restrict a text field to numbers only?
This JavaScript function will be used to restrict alphabets and
special characters in Textbox , only numbers, delete, arrow keys and
backspace will be allowed. JavaScript Code Snippet - Allow Numbers
in TextBox, Restrict Alphabets and Special Characters
Tested in IE & Chrome.
JavaScript function
<script type="text/javascript">
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
</script>
HTML Source Code with JavaScript
<html>
<head>
<title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
<script type="text/javascript">
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
</script>
</head>
<body style="text-align: center;">
<h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
<big>Enter numbers only: </big>
<input type="text" onkeypress='return restrictAlphabets(event)'/>
</body>
</html>
Refrence
How to dynamically add a style for text-align using jQuery
You have the right idea, as documentation shows:
http://docs.jquery.com/CSS/css#namevalue
Are you sure you're correctly identify this with class or id?
For example, if your class is myElementClass
$('.myElementClass').css('text-align','center');
Also, I haven't worked with Firebug in a while, but are you looking at the dom and not the html? Your source isn't changed by javascript, but the dom is. Look in the dom tab and see if the change was applied.
Get the closest number out of an array
For a small range, the simplest thing is to have a map array, where, eg, the 80th entry would have the value 82 in it, to use your example. For a much larger, sparse range, probably the way to go is a binary search.
With a query language you could query for values some distance either side of your input number and then sort through the resulting reduced list. But SQL doesn't have a good concept of "next" or "previous", to give you a "clean" solution.
Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'
open looks in the current working directory, which in your case is ~
, since you are calling your script from the ~
directory.
You can fix the problem by either
cd
ing to the directory containing data.csv
before executing the script, or
by using the full path to data.csv
in your script, or
- by calling os.chdir(...) to change the current working directory from within your script. Note that all subsequent commands that use the current working directory (e.g.
open
and os.listdir
) may be affected by this.
ES6 map an array of objects, to return an array of objects with new keys
You just need to wrap object in ()
_x000D_
_x000D_
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_
Creating CSS Global Variables : Stylesheet theme management
I do it this way:
The html:
<head>
<style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>
The xCss.php:
<? // place here your vars
$fntBtn = 'bold 14px Arial'
$colBorder = '#556677' ;
$colBG0 = '#dddddd' ;
$colBG1 = '#44dddd' ;
$colBtn = '#aadddd' ;
// here goes your css after the php-close tag:
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }
How can I view all historical changes to a file in SVN
Slightly different from what you described, but I think this might be what you actually need:
svn blame filename
It will print the file with each line prefixed by the time and author of the commit that last changed it.
How can I remove duplicate rows?
Create new blank table with the same structure
Execute query like this
INSERT INTO tc_category1
SELECT *
FROM tc_category
GROUP BY category_id, application_id
HAVING count(*) > 1
Then execute this query
INSERT INTO tc_category1
SELECT *
FROM tc_category
GROUP BY category_id, application_id
HAVING count(*) = 1
Side-by-side list items as icons within a div (css)
Use the following code to float the items and make sure they are displayed inline.
ul.myclass li{float:left;display:inline}
Also make sure that the container you put them in is floated with width 100% or some other technique to ensure the floated items are contained within it and following items below it.
ngrok command not found
This is how I got it to work..
For Mac
- If you downloaded via a download link, you need to add ngrok path to your .bash_profile or .bashrc whichever one you are using.
For Windows 10 bash:
- Download ngrok from https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip
- Move executable file ngrok.exe to C:\Windows\system32\ngrok.exe
- Add Environment Variables via UI (search for "Edit the environment variables for your account" in the search bar next to windows logo => double click on Path under Users Variables for yourusername => Click New => add your path C:\Windows\system32\ngrok.exe => click OK.
- Restart your bash and you should be able to run "ngrok http 80" command.
Javascript: 'window' is not defined
The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.
How to generate gcc debug symbol outside the build target?
You need to use objcopy to separate the debug information:
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.
This is the bash script:
#!/bin/bash
scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`
set -e
function errorexit()
{
errorcode=${1}
shift
echo $@
exit ${errorcode}
}
function usage()
{
echo "USAGE ${scriptname} <tostrip>"
}
tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`
if [ -z ${tostripfile} ] ; then
usage
errorexit 0 "tostrip must be specified"
fi
cd "${tostripdir}"
debugdir=.debug
debugfile="${tostripfile}.debug"
if [ ! -d "${debugdir}" ] ; then
echo "creating dir ${tostripdir}/${debugdir}"
mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"
Difference between $(document.body) and $('body')
The answers here are not actually completely correct. Close, but there's an edge case.
The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.
That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.
I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.
eval command in Bash and its typical uses
Update: Some people say one should -never- use eval. I disagree. I think the risk arises when corrupt input can be passed to eval
. However there are many common situations where that is not a risk, and therefore it is worth knowing how to use eval in any case. This stackoverflow answer explains the risks of eval and alternatives to eval. Ultimately it is up to the user to determine if/when eval is safe and efficient to use.
The bash eval
statement allows you to execute lines of code calculated or acquired, by your bash script.
Perhaps the most straightforward example would be a bash program that opens another bash script as a text file, reads each line of text, and uses eval
to execute them in order. That's essentially the same behavior as the bash source
statement, which is what one would use, unless it was necessary to perform some kind of transformation (e.g. filtering or substitution) on the content of the imported script.
I rarely have needed eval
, but I have found it useful to read or write variables whose names were contained in strings assigned to other variables. For example, to perform actions on sets of variables, while keeping the code footprint small and avoiding redundancy.
eval
is conceptually simple. However, the strict syntax of the bash language, and the bash interpreter's parsing order can be nuanced and make eval
appear cryptic and difficult to use or understand. Here are the essentials:
The argument passed to eval
is a string expression that is calculated at runtime. eval
will execute the final parsed result of its argument as an actual line of code in your script.
Syntax and parsing order are stringent. If the result isn't an executable line of bash code, in scope of your script, the program will crash on the eval
statement as it tries to execute garbage.
When testing you can replace the eval
statement with echo
and look at what is displayed. If it is legitimate code in the current context, running it through eval
will work.
The following examples may help clarify how eval works...
Example 1:
eval
statement in front of 'normal' code is a NOP
$ eval a=b
$ eval echo $a
b
In the above example, the first eval
statements has no purpose and can be eliminated. eval
is pointless in the first line because there is no dynamic aspect to the code, i.e. it already parsed into the final lines of bash code, thus it would be identical as a normal statement of code in the bash script. The 2nd eval
is pointless too, because, although there is a parsing step converting $a
to its literal string equivalent, there is no indirection (e.g. no referencing via string value of an actual bash noun or bash-held script variable), so it would behave identically as a line of code without the eval
prefix.
Example 2:
Perform var assignment using var names passed as string values.
$ key="mykey"
$ val="myval"
$ eval $key=$val
$ echo $mykey
myval
If you were to echo $key=$val
, the output would be:
mykey=myval
That, being the final result of string parsing, is what will be executed by eval, hence the result of the echo statement at the end...
Example 3:
Adding more indirection to Example 2
$ keyA="keyB"
$ valA="valB"
$ keyB="that"
$ valB="amazing"
$ eval eval \$$keyA=\$$valA
$ echo $that
amazing
The above is a bit more complicated than the previous example, relying more heavily on the parsing-order and peculiarities of bash. The eval
line would roughly get parsed internally in the following order (note the following statements are pseudocode, not real code, just to attempt to show how the statement would get broken down into steps internally to arrive at the final result).
eval eval \$$keyA=\$$valA # substitution of $keyA and $valA by interpreter
eval eval \$keyB=\$valB # convert '$' + name-strings to real vars by eval
eval $keyB=$valB # substitution of $keyB and $valB by interpreter
eval that=amazing # execute string literal 'that=amazing' by eval
If the assumed parsing order doesn't explain what eval is doing enough, the third example may describe the parsing in more detail to help clarify what is going on.
Example 4:
Discover whether vars, whose names are contained in strings, themselves contain string values.
a="User-provided"
b="Another user-provided optional value"
c=""
myvarname_a="a"
myvarname_b="b"
myvarname_c="c"
for varname in "myvarname_a" "myvarname_b" "myvarname_c"; do
eval varval=\$$varname
if [ -z "$varval" ]; then
read -p "$varname? " $varname
fi
done
In the first iteration:
varname="myvarname_a"
Bash parses the argument to eval
, and eval
sees literally this at runtime:
eval varval=\$$myvarname_a
The following pseudocode attempts to illustrate how bash interprets the above line of real code, to arrive at the final value executed by eval
. (the following lines descriptive, not exact bash code):
1. eval varval="\$" + "$varname" # This substitution resolved in eval statement
2. .................. "$myvarname_a" # $myvarname_a previously resolved by for-loop
3. .................. "a" # ... to this value
4. eval "varval=$a" # This requires one more parsing step
5. eval varval="User-provided" # Final result of parsing (eval executes this)
Once all the parsing is done, the result is what is executed, and its effect is obvious, demonstrating there is nothing particularly mysterious about eval
itself, and the complexity is in the parsing of its argument.
varval="User-provided"
The remaining code in the example above simply tests to see if the value assigned to $varval is null, and, if so, prompts the user to provide a value.
How to display my application's errors in JSF?
I tried this as a best guess, but no luck:
It looks right to me. Have you tried setting a message severity explicitly? Also I believe the ID needs to be the same as that of a component (i.e., you'd need to use newPassword1 or newPassword2, if those are your IDs, and not newPassword as you had in the example).
FacesContext.getCurrentInstance().addMessage("newPassword1",
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Message"));
Then use <h:message for="newPassword1" />
to display the error message on the JSF page.
bootstrap popover not showing on top of all elements
In my case I had to use the popover template option and add my own css class to the template html:
$("[data-toggle='popover']").popover(
{
container: 'body',
template: '<div class="popover top-modal" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
});
Css:
.top-modal {
z-index: 99999;
}
How do I escape spaces in path for scp copy in Linux?
works
scp localhost:"f/a\ b\ c" .
scp localhost:'f/a\ b\ c' .
does not work
scp localhost:'f/a b c' .
The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails
To see this in action, start a shell with the -vx options ie bash -vx
and it will display the interpolated version of the command as it runs it.
Declaring and initializing arrays in C
This is an addendum to the accepted answer by AndreyT, with Nyan's comment on mismatched array sizes. I disagree with their automatic setting of the fifth element to zero. It should likely be 5 --the number after 1,2,3,4. So I would suggest a wrapper to memcpy() to produce a compile-time error when we try to copy arrays of different sizes:
#define Memcpy(a,b) do { /* copy arrays */ \
ASSERT(sizeof(a) == sizeof(b) && /* a static assert */ \
sizeof(a) != sizeof((a) + 0)); /* no pointers */ \
memcpy((a), (b), sizeof (b)); /* & unnecesary */ \
} while (0) /* no return value */
This macro will generate a compile-time error if your array is of length 1. Which is perhaps a feature.
Because we are using a macro, the C99 compound literal seems to need an extra pair of parentheses:
Memcpy(myarray, ((int[]) { 1, 2, 3, 4 }));
Here ASSERT() is a 'static assert'. If you don't already have your own, I use the following on a number of platforms:
#define CONCAT_TOKENS(a, b) a ## b
#define EXPAND_THEN_CONCAT(a,b) CONCAT_TOKENS(a, b)
#define ASSERT(e) enum {EXPAND_THEN_CONCAT(ASSERT_line_,__LINE__) = 1/!!(e)}
#define ASSERTM(e,m) /* version of ASSERT() with message */ \
enum{EXPAND_THEN_CONCAT(m##_ASSERT_line_,__LINE__)=1/!!(e)}
How do you remove an array element in a foreach loop?
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);