IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
React - changing an uncontrolled input
Simply create a fallback to '' if the this.state.name is null.
<input name="name" type="text" value={this.state.name || ''} onChange={this.onFieldChange('name').bind(this)}/>
This also works with the useState variables.
Open Source Javascript PDF viewer
You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.
I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.
How can I set the font-family & font-size inside of a div?
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
sendUserActionEvent() is null
This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project
Output data with no column headings using PowerShell
A better answer is to leave your script as it was. When doing the Select name
, follow it by -ExpandProperty Name
like so:
Get-ADGroupMember 'Domain Admins' | Select Name -ExpandProperty Name | out-file Admins.txt
Abstract variables in Java?
The best you could do is have accessor/mutators for the variable.
Something like getTAG()
That way all implementing classes would have to implement them.
Abstract classes are used to define abstract behaviour not data.
Pass data from Activity to Service using an Intent
Activity:
int number = 5;
Intent i = new Intent(this, MyService.class);
i.putExtra("MyNumber", number);
startService(i);
Service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null){
int number = intent.getIntExtra("MyNumber", 0);
}
}
Is it valid to define functions in JSON results?
Let's quote one of the spec's - http://tools.ietf.org/html/rfc7159#section-12
The The JavaScript Object Notation (JSON) Data Interchange Format Specification states:
JSON is a subset of JavaScript but excludes assignment and invocation.
Since JSON's syntax is borrowed from JavaScript, it is possible to
use that language's "eval()" function to parse JSON texts. This
generally constitutes an unacceptable security risk, since the text
could contain executable code along with data declarations. The same
consideration applies to the use of eval()-like functions in any
other programming language in which JSON texts conform to that
language's syntax.
So all answers which state, that functions are not part of the JSON standard are correct.
The official answer is: No, it is not valid to define functions in JSON results!
The answer could be yes, because "code is data" and "data is code".
Even if JSON is used as a language independent data serialization format, a tunneling of "code" through other types will work.
A JSON string might be used to pass a JS function to the client-side browser for execution.
[{"data":[["1","2"],["3","4"]],"aFunction":"function(){return \"foo bar\";}"}]
This leads to question's like: How to "Execute JavaScript code stored as a string".
Be prepared, to raise your "eval() is evil" flag and stick your "do not tunnel functions through JSON" flag next to it.
Html/PHP - Form - Input as array
in addition:
for those who have a empty POST variable, don't use this:
name="[levels][level][]"
rather use this (as it is already here in this example):
name="levels[level][]"
How to convert a string or integer to binary in Ruby?
You have Integer#to_s(base)
and String#to_i(base)
available to you.
Integer#to_s(base)
converts a decimal number to a string representing the number in the base specified:
9.to_s(2) #=> "1001"
while the reverse is obtained with String#to_i(base)
:
"1001".to_i(2) #=> 9
JComboBox Selection Change Listener?
I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.
How do I get the previous or last item?
Why doesn't git recognize that my file has been changed, therefore git add not working
My Git client (Gitg) caused this issue for me. Normal commands that I would usually run weren't working. Even touching every file in the project didn't work.
I found a way to fix it and I'm still not sure what caused it. Copy your project directory. The missing files will show up in the copied directory's git status
. Renaming might do the same thing.
How to duplicate a whole line in Vim?
For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".
yy or Y to copy the line
or
dd to delete the line
then
p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor
For more key bindings, you can visit this site: vi Complete Key Binding List
How can I send an email through the UNIX mailx command?
Here is a multifunctional function to tackle mail sending with several attachments:
enviaremail() {
values=$(echo "$@" | tr -d '\n')
listargs=()
listargs+=($values)
heirloom-mailx $( attachment=""
for (( a = 5; a < ${#listargs[@]}; a++ )); do
attachment=$(echo "-a ${listargs[a]} ")
echo "${attachment}"
done) -v -s "${titulo}" \
-S smtp-use-starttls \
-S ssl-verify=ignore \
-S smtp-auth=login \
-S smtp=smtp://$1 \
-S from="${2}" \
-S smtp-auth-user=$3 \
-S smtp-auth-password=$4 \
-S ssl-verify=ignore \
$5 < ${cuerpo}
}
function call:
enviaremail "smtp.mailserver:port" "from_address" "authuser" "'pass'" "destination" "list of attachments separated by space"
Note: Remove the double quotes in the call
In addition please remember to define externally the $titulo (subject) and $cuerpo (body) of the email prior to using the function
How to change Elasticsearch max memory size
For anyone looking to do this on Centos 7 or with another system running SystemD, you change it in
/etc/sysconfig/elasticsearch
Uncomment the ES_HEAP_SIZE line, and set a value, eg:
# Heap Size (defaults to 256m min, 1g max)
ES_HEAP_SIZE=16g
(Ignore the comment about 1g max - that's the default)
Call PowerShell script PS1 from another PS1 script inside Powershell ISE
I submit my example for consideration. This is how I call some code from a controller script in the tools I make. The scripts that do the work also need to accept parameters as well, so this example shows how to pass them. It does assume the script being called is in the same directory as the controller script (script making the call).
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,
[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,
[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)
$ZAEventLogDataSplat = @{
"Computername" = $Computername
"StartTime" = $StartTime
"EndTime" = $EndTime
}
& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat
The above is a controller script that accepts 3 parameters. These are defined in the param block. The controller script then calls the script named Get-ZAEventLogData.ps1. For the sake of example, this script also accepts the same 3 parameters. When the controller script calls to the script that does the work, it needs to call it and pass the parameters. The above shows how I do it by splatting.
PHP array value passes to next row
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
How to asynchronously call a method in Java
Java also provides a nice way of calling async methods. in java.util.concurrent we have ExecutorService that helps in doing the same. Initialize your object like this -
private ExecutorService asyncExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
and then call the function like-
asyncExecutor.execute(() -> {
TimeUnit.SECONDS.sleep(3L);}
Gradle to execute Java class (without modifying build.gradle)
Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build
without errors.
Both gradle build
and gradle -PmainClass=foo runApp
work with this:
task runApp(type:JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}
where you set your default main class.
How to implement a secure REST API with node.js
I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.
Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using node-uuid and the password can be hashed using pbkdf2
Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.
When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.
Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.
If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.
The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.
If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.
Summary:
An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.
Cluster analysis in R: determine the optimal number of clusters
If your question is how can I determine how many clusters are appropriate for a kmeans analysis of my data?
, then here are some options. The wikipedia article on determining numbers of clusters has a good review of some of these methods.
First, some reproducible data (the data in the Q are... unclear to me):
n = 100
g = 6
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))),
y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))
plot(d)
One. Look for a bend or elbow in the sum of squared error (SSE) scree plot. See http://www.statmethods.net/advstats/cluster.html & http://www.mattpeeples.net/kmeans.html for more. The location of the elbow in the resulting plot suggests a suitable number of clusters for the kmeans:
mydata <- d
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
for (i in 2:15) wss[i] <- sum(kmeans(mydata,
centers=i)$withinss)
plot(1:15, wss, type="b", xlab="Number of Clusters",
ylab="Within groups sum of squares")
We might conclude that 4 clusters would be indicated by this method:
Two. You can do partitioning around medoids to estimate the number of clusters using the pamk
function in the fpc package.
library(fpc)
pamk.best <- pamk(d)
cat("number of clusters estimated by optimum average silhouette width:", pamk.best$nc, "\n")
plot(pam(d, pamk.best$nc))
# we could also do:
library(fpc)
asw <- numeric(20)
for (k in 2:20)
asw[[k]] <- pam(d, k) $ silinfo $ avg.width
k.best <- which.max(asw)
cat("silhouette-optimal number of clusters:", k.best, "\n")
# still 4
Three. Calinsky criterion: Another approach to diagnosing how many clusters suit the data. In this case we try 1 to 10 groups.
require(vegan)
fit <- cascadeKM(scale(d, center = TRUE, scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE)
calinski.best <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
# 5 clusters!
Four. Determine the optimal model and number of clusters according to the Bayesian Information Criterion for expectation-maximization, initialized by hierarchical clustering for parameterized Gaussian mixture models
# See http://www.jstatsoft.org/v18/i06/paper
# http://www.stat.washington.edu/research/reports/2006/tr504.pdf
#
library(mclust)
# Run the function to see how many clusters
# it finds to be optimal, set it to search for
# at least 1 model and up 20.
d_clust <- Mclust(as.matrix(d), G=1:20)
m.best <- dim(d_clust$z)[2]
cat("model-based optimal number of clusters:", m.best, "\n")
# 4 clusters
plot(d_clust)
Five. Affinity propagation (AP) clustering, see http://dx.doi.org/10.1126/science.1136800
library(apcluster)
d.apclus <- apcluster(negDistMat(r=2), d)
cat("affinity propogation optimal number of clusters:", length(d.apclus@clusters), "\n")
# 4
heatmap(d.apclus)
plot(d.apclus, d)
Six. Gap Statistic for Estimating the Number of Clusters. See also some code for a nice graphical output. Trying 2-10 clusters here:
library(cluster)
clusGap(d, kmeans, 10, B = 100, verbose = interactive())
Clustering k = 1,2,..., K.max (= 10): .. done
Bootstrapping, b = 1,2,..., B (= 100) [one "." per sample]:
.................................................. 50
.................................................. 100
Clustering Gap statistic ["clusGap"].
B=100 simulated reference sets, k = 1..10
--> Number of clusters (method 'firstSEmax', SE.factor=1): 4
logW E.logW gap SE.sim
[1,] 5.991701 5.970454 -0.0212471 0.04388506
[2,] 5.152666 5.367256 0.2145907 0.04057451
[3,] 4.557779 5.069601 0.5118225 0.03215540
[4,] 3.928959 4.880453 0.9514943 0.04630399
[5,] 3.789319 4.766903 0.9775842 0.04826191
[6,] 3.747539 4.670100 0.9225607 0.03898850
[7,] 3.582373 4.590136 1.0077628 0.04892236
[8,] 3.528791 4.509247 0.9804556 0.04701930
[9,] 3.442481 4.433200 0.9907197 0.04935647
[10,] 3.445291 4.369232 0.9239414 0.05055486
Here's the output from Edwin Chen's implementation of the gap statistic:
Seven. You may also find it useful to explore your data with clustergrams to visualize cluster assignment, see http://www.r-statistics.com/2010/06/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-code/ for more details.
Eight. The NbClust package provides 30 indices to determine the number of clusters in a dataset.
library(NbClust)
nb <- NbClust(d, diss=NULL, distance = "euclidean",
method = "kmeans", min.nc=2, max.nc=15,
index = "alllong", alphaBeale = 0.1)
hist(nb$Best.nc[1,], breaks = max(na.omit(nb$Best.nc[1,])))
# Looks like 3 is the most frequently determined number of clusters
# and curiously, four clusters is not in the output at all!
If your question is how can I produce a dendrogram to visualize the results of my cluster analysis
, then you should start with these:
http://www.statmethods.net/advstats/cluster.html
http://www.r-tutor.com/gpu-computing/clustering/hierarchical-cluster-analysis
http://gastonsanchez.wordpress.com/2012/10/03/7-ways-to-plot-dendrograms-in-r/ And see here for more exotic methods: http://cran.r-project.org/web/views/Cluster.html
Here are a few examples:
d_dist <- dist(as.matrix(d)) # find distance matrix
plot(hclust(d_dist)) # apply hirarchical clustering and plot
# a Bayesian clustering method, good for high-dimension data, more details:
# http://vahid.probstat.ca/paper/2012-bclust.pdf
install.packages("bclust")
library(bclust)
x <- as.matrix(d)
d.bclus <- bclust(x, transformed.par = c(0, -50, log(16), 0, 0, 0))
viplot(imp(d.bclus)$var); plot(d.bclus); ditplot(d.bclus)
dptplot(d.bclus, scale = 20, horizbar.plot = TRUE,varimp = imp(d.bclus)$var, horizbar.distance = 0, dendrogram.lwd = 2)
# I just include the dendrogram here
Also for high-dimension data is the pvclust
library which calculates p-values for hierarchical clustering via multiscale bootstrap resampling. Here's the example from the documentation (wont work on such low dimensional data as in my example):
library(pvclust)
library(MASS)
data(Boston)
boston.pv <- pvclust(Boston)
plot(boston.pv)
Does any of that help?
Why doesn't the Scanner class have a nextChar method?
According to the javadoc a Scanner
does not seem to be intended for reading single characters. You attach a Scanner
to an InputStream
(or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.
How can a web application send push notifications to iOS devices?
You can use HTML5 Websockets to introduce your own push messages. From Wikipedia:
"For the client side, WebSocket was to be implemented in Firefox 4,
Google Chrome 4, Opera 11, and Safari 5, as well as the mobile version
of Safari in iOS 4.2. Also the BlackBerry Browser in OS7 supports
WebSockets."
To do this, you need your own provider server to push the messages to the clients.
If you want to use APN (Apple Push Notification) or C2DM (Cloud to Device Message), you must have a native application which must be downloaded through the online store.
How to stretch children to fill cross-axis?
_x000D_
_x000D_
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
- Specify
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space:
_x000D_
_x000D_
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
"Are you missing an assembly reference?" compile error - Visual Studio
In my case, I had to change the Copy Local setting to true (right-click assembly in solution explorer, select properties, locate and change value of Copy Local property). Once this setting was changed, publication of my WCF service copied the file to the server and the error went away.
Google Android USB Driver and ADB
instead of modifying adb_usb.ini file I made changes on the file android_winusb.inf under directory android-sdk\extras\google\usb_driver\ alone and it worked for the tablet MID Q88 but i copied both sections [Google.NTamd64] and [Google.NTx86]
;Google MID Q88
%SingleAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&MI_01
%CompositeAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&REV_0230&MI_01
How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
Retrieving a Foreign Key value with django-rest-framework serializers
Simple solution
source='category.name'
where category
is foreign key and .name
it's attribute.
from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item
class ItemSerializer(ModelSerializer):
category_name = ReadOnlyField(source='category.name')
class Meta:
model = Item
fields = "__all__"
Getting Django admin url for an object
from django.core.urlresolvers import reverse
def url_to_edit_object(obj):
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[obj.id] )
return u'<a href="%s">Edit %s</a>' % (url, obj.__unicode__())
This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.
Java - JPA - @Version annotation
Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:
@Entity
public class MyEntity implements Serializable {
// ...
@Version
@Column(name = "optlock", columnDefinition = "integer DEFAULT 0", nullable = false)
private long version = 0L;
// ...
}
Why? Because:
- Optimistic locking won't work if field annotated with
@Version
is accidentally set to null
.
- As this special field isn't necessarily a business version of the object, to avoid a misleading, I prefer to name such field to something like
optlock
rather than version
.
First point doesn't matter if application uses only JPA for inserting data into the database, as JPA vendor will enforce 0
for @version
field at creation time. But almost always plain SQL statements are also in use (at least during unit and integration testing).
How (and why) to use display: table-cell (CSS)
After days trying to find the answer, I finally found
display: table;
There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":
To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Similarly to get CSS to do it, you'd use the following:
HTML
<div id="table">
<div class="tr">
<div class="td"></div>
<div class="td"></div>
<div class="td"></div>
</div>
<div class="tr">
<div class="td"></div>
<div class="td"></div>
<div class="td"></div>
</div>
</div>
CSS
#table{
display: table;
}
.tr{
display: table-row;
}
.td{
display: table-cell; }
As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!
http://jsfiddle.net/blyzz/1djs97yv/1/
It's worth noting that display: table;
does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.
How to add multiple columns to pandas dataframe in one assignment?
You could use assign
with a dict of column names and values.
In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
col_1 col_2 col2_new_2 col3_new_3 col_new_1
0 0 4 dogs 3 NaN
1 1 5 dogs 3 NaN
2 2 6 dogs 3 NaN
3 3 7 dogs 3 NaN
Removing duplicates from a SQL query (not just "use distinct")
You need to tell the query what value to pick for the other columns, MIN
or MAX
seem like suitable choices.
SELECT
U.NAME, MIN(P.PIC_ID)
FROM
USERS U,
PICTURES P,
POSTINGS P1
WHERE
U.EMAIL_ID = P1.EMAIL_ID AND
P1.PIC_ID = P.PIC_ID AND
P.CAPTION LIKE '%car%'
GROUP BY
U.NAME;
Simple 3x3 matrix inverse code (C++)
I have just created a QMatrix class. It uses the built in vector > container. QMatrix.h
It uses the Jordan-Gauss method to compute the inverse of a square matrix.
You can use it as follows:
#include "QMatrix.h"
#include <iostream>
int main(){
QMatrix<double> A(3,3,true);
QMatrix<double> Result = A.inverse()*A; //should give the idendity matrix
std::cout<<A.inverse()<<std::endl;
std::cout<<Result<<std::endl; // for checking
return 0;
}
The inverse function is implemented as follows:
Given a class with the following fields:
template<class T> class QMatrix{
public:
int rows, cols;
std::vector<std::vector<T> > A;
the inverse() function:
template<class T>
QMatrix<T> QMatrix<T>:: inverse(){
Identity<T> Id(rows); //the Identity Matrix as a subclass of QMatrix.
QMatrix<T> Result = *this; // making a copy and transforming it to the Identity matrix
T epsilon = 0.000001;
for(int i=0;i<rows;++i){
//check if Result(i,i)==0, if true, switch the row with another
for(int j=i;j<rows;++j){
if(std::abs(Result(j,j))<epsilon) { //uses Overloading()(int int) to extract element from Result Matrix
Result.replace_rows(i,j+1); //switches rows i with j+1
}
else break;
}
// main part, making a triangular matrix
Id(i)=Id(i)*(1.0/Result(i,i));
Result(i)=Result(i)*(1.0/Result(i,i)); // Using overloading ()(int) to get a row form the matrix
for(int j=i+1;j<rows;++j){
T temp = Result(j,i);
Result(j) = Result(j) - Result(i)*temp;
Id(j) = Id(j) - Id(i)*temp; //doing the same operations to the identity matrix
Result(j,i)=0; //not necessary, but looks nicer than 10^-15
}
}
// solving a triangular matrix
for(int i=rows-1;i>0;--i){
for(int j=i-1;j>=0;--j){
T temp = Result(j,i);
Id(j) = Id(j) - temp*Id(i);
Result(j)=Result(j)-temp*Result(i);
}
}
return Id;
}
How to get the input from the Tkinter Text Widget?
To get Tkinter input from the text box in python 3 the complete student level program used by me is as under:
#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace
from tkinter import *
#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.
root = Tk()
root.title('how to get text from textbox')
#**********************************
mystring = StringVar()
####define the function that the signup button will do
def getvalue():
## print(mystring.get())
#*************************************
Label(root, text="Text to get").grid(row=0, sticky=W) #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox
WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button
############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()
Why can't I declare static methods in an interface?
Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .
How do I parse JSON from a Java HTTPResponse?
You can use the Gson library for parsing
void getJson() throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("some url of json");
HttpResponse httpResponse = httpClient.execute(httpGet);
String response = EntityUtils.toString(httpResponse.getEntity());
Gson gson = new Gson();
MyClass myClassObj = gson.fromJson(response, MyClass.class);
}
here is sample json file which is fetchd from server
{
"id":5,
"name":"kitkat",
"version":"4.4"
}
here is my class
class MyClass{
int id;
String name;
String version;
}
refer this
How do I find out which DOM element has the focus?
document.activeElement
may default to the <body>
element if no focusable elements are in focus. Additionally, if an element is focused and the browser window is blurred, activeElement
will continue to hold the focused element.
If either of these two behaviors are not desirable, consider a CSS-based approach: document.querySelector( ':focus' )
.
Visual Studio "Could not copy" .... during build
If you're running into this issue using Visual Studio Code (vsCode) and/or you're sticking to terminal commands, the clean command will delete the build files and typically fix the issue described:
dotnet clean
Then, you can return to running:
dotnet build
or
dotnet run
update one table with data from another
For MySql:
UPDATE table1 JOIN table2
ON table1.id = table2.id
SET table1.name = table2.name,
table1.`desc` = table2.`desc`
For Sql Server:
UPDATE table1
SET table1.name = table2.name,
table1.[desc] = table2.[desc]
FROM table1 JOIN table2
ON table1.id = table2.id
How can I access Oracle from Python?
In addition to the Oracle instant client, you may also need to install the Oracle ODAC components and put the path to them into your system path. cx_Oracle seems to need access to the oci.dll file that is installed with them.
Also check that you get the correct version (32bit or 64bit) of them that matches your: python, cx_Oracle, and instant client versions.
PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL
This: http://archives.postgresql.org/pgsql-bugs/2007-10/msg00234.php is also a nice and fast solution, and works for multiple schemas in one database:
Tables
SELECT 'ALTER TABLE '|| schemaname || '."' || tablename ||'" OWNER TO my_new_owner;'
FROM pg_tables WHERE NOT schemaname IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;
Sequences
SELECT 'ALTER SEQUENCE '|| sequence_schema || '."' || sequence_name ||'" OWNER TO my_new_owner;'
FROM information_schema.sequences WHERE NOT sequence_schema IN ('pg_catalog', 'information_schema')
ORDER BY sequence_schema, sequence_name;
Views
SELECT 'ALTER VIEW '|| table_schema || '."' || table_name ||'" OWNER TO my_new_owner;'
FROM information_schema.views WHERE NOT table_schema IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;
Materialized Views
Based on this answer
SELECT 'ALTER TABLE '|| oid::regclass::text ||' OWNER TO my_new_owner;'
FROM pg_class WHERE relkind = 'm'
ORDER BY oid;
This generates all the required ALTER TABLE
/ ALTER SEQUENCE
/ ALTER VIEW
statements, copy these and paste them back into plsql to run them.
Check your work in psql by doing:
\dt *.*
\ds *.*
\dv *.*
Replace new lines with a comma delimiter with Notepad++?
fapDaddy's answer using a macro pointed me in the right direction.
Here's precisely what worked for me.
Place the cursor after the first data item.
Click 'Macro > Start Recording' in the menu.
Type this sequence: Comma, Space, Delete, End.
Click 'Macro > Stop recording' in the menu.
Click 'Macro > Run a Macro Multiple Times...' in the menu.
Click 'Run until the end of file' and click 'Run'.
Remove any trailing characters.
Done!
How to add an extra column to a NumPy array
Assuming M
is a (100,3) ndarray and y
is a (100,) ndarray append
can be used as follows:
M=numpy.append(M,y[:,None],1)
The trick is to use
y[:, None]
This converts y
to a (100, 1) 2D array.
M.shape
now gives
(100, 4)
Is the practice of returning a C++ reference variable evil?
"returning a reference is evil because,
simply [as I understand] it makes it
easier to miss deleting it"
Not true. Returning a reference does not imply ownership semantics. That is, just because you do this:
Value& v = thing->getTheValue();
...does not mean you now own the memory referred to by v;
However, this is horrible code:
int& getTheValue()
{
return *new int;
}
If you are doing something like this because "you don't require a pointer on that instance" then: 1) just dereference the pointer if you need a reference, and 2) you will eventually need the pointer, because you have to match a new with a delete, and you need a pointer to call delete.
How line ending conversions work with git core.autocrlf between different operating systems
The best explanation of how core.autocrlf
works is found on the gitattributes man page, in the text
attribute section.
This is how core.autocrlf
appears to work currently (or at least since v1.7.2 from what I am aware):
- Text files checked-out from the repository that have only
LF
characters are normalized to CRLF
in your working tree; files that contain CRLF
in the repository will not be touched
- Text files that have only
LF
characters in the repository, are normalized from CRLF
to LF
when committed back to the repository. Files that contain CRLF
in the repository will be committed untouched.
- Text files checked-out from the repository will keep original EOL characters in your working tree.
- Text files in your working tree with
CRLF
characters are normalized to LF
when committed back to the repository.
core.eol
dictates EOL characters in the text files of your working tree.
core.eol = native
by default, which means Windows EOLs are CRLF
and *nix EOLs are LF
in working trees.
- Repository
gitattributes
settings determines EOL character normalization for commits to the repository (default is normalization to LF
characters).
I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol
setting definitely helped clarify how EOL characters are handled by git.
How to uninstall a package installed with pip install --user
Having tested this using Python 3.5 and pip 7.1.2 on Linux, the situation appears to be this:
pip install --user somepackage
installs to $HOME/.local
, and uninstalling it does work using pip uninstall somepackage
.
This is true whether or not somepackage
is also installed system-wide at the same time.
If the package is installed at both places, only the local one will be uninstalled. To uninstall the package system-wide using pip
, first uninstall it locally, then run the same uninstall command again, with root
privileges.
In addition to the predefined user install directory, pip install --target somedir somepackage
will install the package into somedir
. There is no way to uninstall a package from such a place using pip
. (But there is a somewhat old unmerged pull request on Github that implements pip uninstall --target
.)
Since the only places pip
will ever uninstall from are system-wide and predefined user-local, you need to run pip uninstall
as the respective user to uninstall from a given user's local install directory.
Parse String date in (yyyy-MM-dd) format
tl;dr
LocalDate.parse( "2013-09-18" )
… and …
myLocalDate.toString() // Example: 2013-09-18
java.time
The Question and other Answers are out-of-date. The troublesome old legacy date-time classes are now supplanted by the java.time classes.
ISO 8601
Your input string happens to comply with standard ISO 8601 format, YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing and generating string representations of date-time values. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2013-09-18" );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upload artifacts to Nexus, without Maven
If you need a convenient command line interface or python API, look at repositorytools
Using it, you can upload artifact to nexus with command
artifact upload foo-1.2.3.ext releases com.fooware
To make it work, you will also need to set some environment variables
export REPOSITORY_URL=https://repo.example.com
export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword
How to concatenate strings with padding in sqlite
The ||
operator is "concatenate" - it joins together the two strings of
its operands.
From http://www.sqlite.org/lang_expr.html
For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.
Update: Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/
-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable
select substr('0000000000' || mycolumn, -10, 10) from mytable
-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable
select substr(mycolumn || '0000000000', 1, 10) from mytable
Here's how it looks:
SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)
it yields
"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"
How to show progress bar while loading, using ajax
<script>
$(function() {
$("#client").on("change", function() {
var clientid=$("#client").val();
//show the loading div here
$.ajax({
type:"post",
url:"clientnetworkpricelist/yourfile.php",
data:"title="+clientid,
success:function(data){
$("#result").html(data);
//hide the loading div here
}
});
});
});
</script>
Or you can also do this:
$(document).ajaxStart(function() {
// show loader on start
$("#loader").css("display","block");
}).ajaxSuccess(function() {
// hide loader on success
$("#loader").css("display","none");
});
Changing the selected option of an HTML Select element
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
Batch file include external file for variables
:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.
@ECHO OFF
SETLOCAL
REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"
REM Change variables
IF NOT DEFINED $RunCount (
SET $RunCount=1
) ELSE SET /A $RunCount+=1
REM Display variables
SET $
REM Save variables
SET $>config.txt
ENDLOCAL
PAUSE
EXIT /B
Output:
$RunCount=1
$RunCount=2
$RunCount=3
The technique outlined above can also be used to share variables among multiple batch files.
Source: http://www.incodesystems.com/products/batchfi1.htm
Redraw datatables after using ajax to refresh the table content?
It looks as if you could use the API functions to
- clear the table ( fnClearTable )
- add new data to the table ( fnAddData)
- redraw the table ( fnDraw )
http://datatables.net/api
UPDATE
I guess you're using the DOM Data Source (for server-side processing) to generate your table. I didn't really get that at first, so my previous answer won't work for that.
To get it to work without rewriting your server side code:
What you'll need to do is totally remove the old table (in the dom) and replace it with the ajax result content, then reinitialize the datatable:
// in your $.post callback:
function (data) {
// remove the old table
$("#ajaxresponse").children().remove();
// replace with the new table
$("#ajaxresponse").html(data);
// reinitialize the datatable
$('#rankings').dataTable( {
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}
);
}
Naming Conventions: What to name a boolean variable?
How about:
hasSiblings
or isFollowedBySiblings (or isFolloedByItems, or isFollowedByOtherItems etc.)
or moreItems
Although I think that even though you shouldn't make a habit of braking 'the rules' sometimes the best way to accomplish something may be to make an exception of the rule (Code Complete guidelines), and in your case, name the variable isNotLast
The listener supports no services
you need to reconfigure your tnsnames.ora so that it can point to your hostname
after that listener will be able to pick the new hostname. after which check the status of your listener lsnrctl status and start listener lsnrctl start
then register your listener. Alter system register
Injection of autowired dependencies failed;
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Background image jumps when address bar hides iOS/Android/Mobile Chrome
Simple answer if your background allows, why not set background-size: to something just covering device width with media queries and use alongside the :after position: fixed; hack here.
IE: background-size: 901px; for any screens <900px? Not perfect or responsive but worked a charm for me on mobile <480px as i'm using an abstract BG.
Using RegEx in SQL Server
A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;
using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Regex(string input, string regex)
{
var match = RX.Regex.Match(input, regex).Groups[1].Value;
return new SqlString (match);
}
}
Installation instructions can be found here
How to validate an email address in PHP
If you're just looking for an actual regex that allows for various dots, underscores and dashes, it as follows: [a-zA-z0-9.-]+\@[a-zA-z0-9.-]+.[a-zA-Z]+
. That will allow a fairly stupid looking email like tom_anderson.1-neo@my-mail_matrix.com
to be validated.
how to use substr() function in jquery?
Extract characters from a string:
var str = "Hello world!";
var res = str.substring(1,4);
The result of res
will be:
ell
http://www.w3schools.com/jsref/jsref_substring.asp
$('.dep_buttons').mouseover(function(){
$(this).text().substring(0,25);
if($(this).text().length > 30) {
$(this).stop().animate({height:"150px"},150);
}
$(".dep_buttons").mouseout(function(){
$(this).stop().animate({height:"40px"},150);
});
});
Fast Linux file count for a large number of files
By default ls
sorts the names, which can take a while if there are a lot of them. Also there will be no output until all of the names are read and sorted. Use the ls -f
option to turn off sorting.
ls -f | wc -l
Note that this will also enable -a
, so .
, ..
, and other files starting with .
will be counted.
You can't specify target table for update in FROM clause
The Approach posted by BlueRaja is slow I modified it as
I was using to delete duplicates from the table. In case it helps anyone with large tables
Original Query
delete from table where id not in (select min(id) from table group by field 2)
This is taking more time:
DELETE FROM table where ID NOT IN(
SELECT MIN(t.Id) from (select Id,field2 from table) AS t GROUP BY field2)
Faster Solution
DELETE FROM table where ID NOT IN(
SELECT x.Id from (SELECT MIN(Id) as Id from table GROUP BY field2) AS t)
how to add a day to a date using jquery datepicker
The datepicker('setDate') sets the date in the datepicket not in the input.
You should add the date and set it in the input.
var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);
Stored procedure - return identity as output parameter or scalar
Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.
If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.
If you prefer a result set return, then again is arguable better to use the OUTPUT clause:
INSERT INTO MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);
This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.
Overall, I can't see a single case when returning SCOPE_IDENTITY()
as a result set would be a good practice.
Setting PHP tmp dir - PHP upload not working
I was also facing the same issue for 2 days but now finally it is working.
Step 1 : create a php script file with this content.
<?php
echo 'username : ' . `whoami`;
phpinfo();
?>
note down the username.
note down open_basedir under core section of phpinfo.
also note down upload_tmp_dir under core section of phpinfo.
Here two things are important ,
see if upload_tmp_dir value is inside one of open_basedir directory.
( php can not upload files outside open_basedir directory ).
Step 2 : Open terminal with root access and go to upload_tmp_dir location.
( In my case "/home/admin/tmp". )
=> cd /home/admin/tmp
But it was not found in my case so I created it and added chown for php user which I get in step 1 ( In my case "admin" ).
=> mkdir /home/admin/tmp
=> chown admin /home/admin/tmp
That is all you have to do to fix the file upload problem.
How can I check if a scrollbar is visible?
a little plugin for it.
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
}
})(jQuery);
use it like this,
$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise..
tested working on Firefox, Chrome, IE6,7,8
but not working properly on body
tag selector
Edit
I found out that when you have horizontal scrollbar that causes vertical scrollbar to appear, this function does not work....
I found out another solution... use clientHeight
return this.get(0).scrollHeight > this.get(0).clientHeight;
Set background image on grid in WPF using C#
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(
"pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
myBrush.ImageSource = image.Source;
Grid grid = new Grid();
grid.Background = myBrush;
"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP
Responding because this answer came up first for search when I was having the same issue:
[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist
MSSQL named instances have to be configured properly without setting the port. (documentation on the freetds config says set instance or port NOT BOTH)
freetds.conf
[Name]
host = Server.com
instance = instance_name
#port = port is found automatically, don't define explicitly
tds version = 8.0
client charset = UTF-8
And in odbc.ini just because you can set Port, DON'T when you are using a named instance.
How do I combine a background-image and CSS3 gradient on the same element?
One thing to realize is that the first defined background image is topmost in the stack. The last defined image will be bottommost. That means, to have a background gradient behind an image, you would need:
_x000D_
_x000D_
body {_x000D_
background-image: url("http://www.skrenta.com/images/stackoverflow.jpg"), linear-gradient(red, yellow);_x000D_
background-image: url("http://www.skrenta.com/images/stackoverflow.jpg"), -webkit-gradient(linear, left top, left bottom, from(red), to(yellow));_x000D_
background-image: url("http://www.skrenta.com/images/stackoverflow.jpg"), -moz-linear-gradient(top, red, yellow);_x000D_
}
_x000D_
_x000D_
_x000D_
You could also define background positions and background size for the images.
I put together a blog post about some interesting things you can do with CSS3 gradients
What does [STAThread] do?
The STAThreadAttribute marks a thread
to use the Single-Threaded COM
Apartment if COM is needed. By
default, .NET won't initialize COM at
all. It's only when COM is needed,
like when a COM object or COM Control
is created or when drag 'n' drop is
needed, that COM is initialized. When
that happens, .NET calls the
underlying CoInitializeEx function,
which takes a flag indicating whether
to join the thread to a multi-threaded
or single-threaded apartment.
Read more info here (Archived, June 2009)
and
Why is STAThread required?
How to check if running as root in a bash script
0- Read official GNU Linux documentation, there are many ways to do it correctly.
1- make sure you put the shell signature to avoid errors in interpretation:
#!/bin/bash
2- this is my script
#!/bin/bash
if [[ $EUID > 0 ]]; then # we can compare directly with this syntax.
echo "Please run as root/sudo"
exit 1
else
#do your stuff
fi
How do I send a file in Android from a mobile device to server using http?
This can be done with a HTTP Post request to the server:
HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");
method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));
HttpResponse response = http.execute(method);
Using CSS in Laravel views?
put your css File in public folder . (public/css/bootstrap-responsive.css)
and <link href="./css/bootstrap-responsive.css" rel="stylesheet">
Why do I get permission denied when I try use "make" to install something?
The problem is frequently with 'secure' setup of mountpoints, such as /tmp
If they are mounted noexec
(check with cat /etc/mtab
and or sudo mount
) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.
E.g. to remount temporarily:
sudo mount -o remount,exec /tmp
Or to change permanently, remove noexec
in /etc/fstab
Correct way to initialize HashMap and can HashMap hold different value types?
In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.
That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap
std::queue iteration
you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:
queue tmp_q = original_q; //copy the original queue to the temporary queue
while (!tmp_q.empty())
{
q_element = tmp_q.front();
std::cout << q_element <<"\n";
tmp_q.pop();
}
At the end, the tmp_q will be empty but the original queue is untouched.
How to add files/folders to .gitignore in IntelliJ IDEA?
IntelliJ has no option to click on a file and choose "Add to .gitignore" like Eclipse has.
The quickest way to add a file or folder to .gitignore without typos is:
- Right-click on the file in the project browser and choose "Copy Path" (or use the keyboard shortcut that is displayed there).
- Open the .gitignore file in your project, and paste.
- Adjust the pasted line so that it is relative to the location of the .gitignore file.
Additional info: There is a .ignore plugin available for IntelliJ which adds a "Add to .gitignore" item to the popup menu when you right-click a file. It works like a charm.
What does ENABLE_BITCODE do in xcode 7?
Since the exact question is "what does enable bitcode do", I'd like to give a few thin technical details I've figured out thus far. Most of this is practically impossible to figure out with 100% certainty until Apple releases the source code for this compiler
First, Apple's bitcode does not appear to be the same thing as LLVM bytecode. At least, I've not been able to figure out any resemblance between them. It appears to have a proprietary header (always starts with "xar!") and probably some link-time reference magic that prevents data duplications. If you write out a hardcoded string, this string will only be put into the data once, rather than twice as would be expected if it was normal LLVM bytecode.
Second, bitcode is not really shipped in the binary archive as a separate architecture as might be expected. It is not shipped in the same way as say x86 and ARM are put into one binary (FAT archive). Instead, they use a special section in the architecture specific MachO binary named "__LLVM" which is shipped with every architecture supported (ie, duplicated). I assume this is a short coming with their compiler system and may be fixed in the future to avoid the duplication.
C code (compiled with clang -fembed-bitcode hi.c -S -emit-llvm
):
#include <stdio.h>
int main() {
printf("hi there!");
return 0;
}
LLVM IR output:
; ModuleID = '/var/folders/rd/sv6v2_f50nzbrn4f64gnd4gh0000gq/T/hi-a8c16c.bc'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
@llvm.embedded.module = appending constant [1600 x i8] c"\DE\C0\17\0B\00\00\00\00\14\00\00\00$\06\00\00\07\00\00\01BC\C0\DE!\0C\00\00\86\01\00\00\0B\82 \00\02\00\00\00\12\00\00\00\07\81#\91A\C8\04I\06\1029\92\01\84\0C%\05\08\19\1E\04\8Bb\80\10E\02B\92\0BB\84\102\148\08\18I\0A2D$H\0A\90!#\C4R\80\0C\19!r$\07\C8\08\11b\A8\A0\A8@\C6\F0\01\00\00\00Q\18\00\00\C7\00\00\00\1Bp$\F8\FF\FF\FF\FF\01\90\00\0D\08\03\82\1D\CAa\1E\E6\A1\0D\E0A\1E\CAa\1C\D2a\1E\CA\A1\0D\CC\01\1E\DA!\1C\C8\010\87p`\87y(\07\80p\87wh\03s\90\87ph\87rh\03xx\87tp\07z(\07yh\83r`\87th\07\80\1E\E4\A1\1E\CA\01\18\DC\E1\1D\DA\C0\1C\E4!\1C\DA\A1\1C\DA\00\1E\DE!\1D\DC\81\1E\CAA\1E\DA\A0\1C\D8!\1D\DA\A1\0D\DC\E1\1D\DC\A1\0D\D8\A1\1C\C2\C1\1C\00\C2\1D\DE\A1\0D\D2\C1\1D\CCa\1E\DA\C0\1C\E0\A1\0D\DA!\1C\E8\01\1D\00s\08\07v\98\87r\00\08wx\876p\87pp\87yh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \E6\81\1E\C2a\1C\D6\A1\0D\E0A\1E\DE\81\1E\CAa\1C\E8\E1\1D\E4\A1\0D\C4\A1\1E\CC\C1\1C\CAA\1E\DA`\1E\D2A\1F\CA\01\C0\03\80\A0\87p\90\87s(\07zh\83q\80\87z\00\C6\E1\1D\E4\A1\1C\E4\00 \E8!\1C\E4\E1\1C\CA\81\1E\DA\C0\1C\CA!\1C\E8\A1\1E\E4\A1\1C\E6\01X\83y\98\87y(\879`\835\18\07|\88\03;`\835\98\87y(\076X\83y\98\87r\90\036X\83y\98\87r\98\03\80\A8\07w\98\87p0\87rh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \EAa\1E\CA\A1\0D\E6\E1\1D\CC\81\1E\DA\C0\1C\D8\E1\1D\C2\81\1E\00s\08\07v\98\87r\006\C8\88\F0\FF\FF\FF\FF\03\C1\0E\E50\0F\F3\D0\06\F0 \0F\E50\0E\E90\0F\E5\D0\06\E6\00\0F\ED\10\0E\E4\00\98C8\B0\C3<\94\03@\B8\C3;\B4\819\C8C8\B4C9\B4\01<\BCC:\B8\03=\94\83<\B4A9\B0C:\B4\03@\0F\F2P\0F\E5\00\0C\EE\F0\0Em`\0E\F2\10\0E\EDP\0Em\00\0F\EF\90\0E\EE@\0F\E5 \0FmP\0E\EC\90\0E\ED\D0\06\EE\F0\0E\EE\D0\06\ECP\0E\E1`\0E\00\E1\0E\EF\D0\06\E9\E0\0E\E60\0Fm`\0E\F0\D0\06\ED\10\0E\F4\80\0E\809\84\03;\CCC9\00\84;\BCC\1B\B8C8\B8\C3<\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F3@\0F\E10\0E\EB\D0\06\F0 \0F\EF@\0F\E50\0E\F4\F0\0E\F2\D0\06\E2P\0F\E6`\0E\E5 \0Fm0\0F\E9\A0\0F\E5\00\E0\01@\D0C8\C8\C39\94\03=\B4\C18\C0C=\00\E3\F0\0E\F2P\0Er\00\10\F4\10\0E\F2p\0E\E5@\0Fm`\0E\E5\10\0E\F4P\0F\F2P\0E\F3\00\AC\C1<\CC\C3<\94\C3\1C\B0\C1\1A\8C\03>\C4\81\1D\B0\C1\1A\CC\C3<\94\03\1B\AC\C1<\CCC9\C8\01\1B\AC\C1<\CCC9\CC\01@\D4\83;\CCC8\98C9\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F50\0F\E5\D0\06\F3\F0\0E\E6@\0Fm`\0E\EC\F0\0E\E1@\0F\809\84\03;\CCC9\00\00I\18\00\00\02\00\00\00\13\82`B \00\00\00\89 \00\00\0D\00\00\002\22\08\09 d\85\04\13\22\A4\84\04\13\22\E3\84\A1\90\14\12L\88\8C\0B\84\84L\100s\04H*\00\C5\1C\01\18\94`\88\08\AA0F7\10@3\02\00\134|\C0\03;\F8\05;\A0\836\08\07x\80\07v(\876h\87p\18\87w\98\07|\88\038p\838\80\037\80\83\0DeP\0Em\D0\0Ez\F0\0Em\90\0Ev@\07z`\07t\D0\06\E6\80\07p\A0\07q \07x\D0\06\EE\80\07z\10\07v\A0\07s \07z`\07t\D0\06\B3\10\07r\80\07:\0FDH #EB\80\1D\8C\10\18I\00\00@\00\00\C0\10\A7\00\00 \00\00\00\00\00\00\00\868\08\10\00\02\00\00\00\00\00\00\90\05\02\00\00\08\00\00\002\1E\98\0C\19\11L\90\8C\09&G\C6\04C\9A\22(\01\0AM\D0i\10\1D]\96\97C\00\00\00y\18\00\00\1C\00\00\00\1A\03L\90F\02\134A\18\08&PIC Level\13\84a\D80\04\C2\C05\08\82\83c+\03ab\B2j\02\B1+\93\9BK{s\03\B9q\81q\81\01A\19c\0Bs;k\B9\81\81q\81q\A9\99q\99I\D9\10\14\8D\D8\D8\EC\DA\5C\DA\DE\C8\EA\D8\CA\5C\CC\D8\C2\CE\E6\A6\04C\1566\BB6\974\B227\BA)A\01\00y\18\00\002\00\00\003\08\80\1C\C4\E1\1Cf\14\01=\88C8\84\C3\8CB\80\07yx\07s\98q\0C\E6\00\0F\ED\10\0E\F4\80\0E3\0CB\1E\C2\C1\1D\CE\A1\1Cf0\05=\88C8\84\83\1B\CC\03=\C8C=\8C\03=\CCx\8Ctp\07{\08\07yH\87pp\07zp\03vx\87p \87\19\CC\11\0E\EC\90\0E\E10\0Fn0\0F\E3\F0\0E\F0P\0E3\10\C4\1D\DE!\1C\D8!\1D\C2a\1Ef0\89;\BC\83;\D0C9\B4\03<\BC\83<\84\03;\CC\F0\14v`\07{h\077h\87rh\077\80\87p\90\87p`\07v(\07v\F8\05vx\87w\80\87_\08\87q\18\87r\98\87y\98\81,\EE\F0\0E\EE\E0\0E\F5\C0\0E\EC\00q \00\00\05\00\00\00&`<\11\D2L\85\05\10\0C\804\06@\F8\D2\14\01\00\00a \00\00\0B\00\00\00\13\04A,\10\00\00\00\03\00\00\004#\00dC\19\020\18\83\01\003\11\CA@\0C\83\11\C1\00\00#\06\04\00\1CB\12\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00", section "__LLVM,__bitcode"
@llvm.cmdline = appending constant [67 x i8] c"-triple\00x86_64-apple-macosx10.10.0\00-emit-llvm\00-disable-llvm-optzns\00", section "__LLVM,__cmdline"
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.0.53.3)"}
The data array that is in the IR also changes depending on the optimization and other code generation settings of clang. It's completely unknown to me what format or anything that this is in.
EDIT:
Following the hint on Twitter, I decided to revisit this and to confirm it. I followed this blog post and used his bitcode extractor tool to get the Apple Archive binary out of the MachO executable. And after extracting the Apple Archive with the xar utility, I got this (converted to text with llvm-dis of course)
; ModuleID = '1'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.1.76)"}
The only notable difference really between the non-bitcode IR and the bitcode IR is that filenames have been stripped to just 1, 2, etc for each architecture.
I also confirmed that the bitcode embedded in a binary is generated after optimizations. If you compile with -O3 and extract out the bitcode, it'll be different than if you compile with -O0.
And just to get extra credit, I also confirmed that Apple does not ship bitcode to devices when you download an iOS 9 app. They include a number of other strange sections that I don't recognized like __LINKEDIT, but they do not include __LLVM.__bundle, and thus do not appear to include bitcode in the final binary that runs on a device. Oddly enough, Apple still ships fat binaries with separate 32/64bit code to iOS 8 devices though.
How to give a delay in loop execution using Qt
So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.
A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.
QTimer
A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.
Qt State Machine
Get top most UIViewController
Based on Bob -c above:
Swift 3.0
extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(vc: rootViewController)
}
return nil
}
class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
if vc.isKind(of: UINavigationController.self) {
let navigationController = vc as! UINavigationController
return UIWindow.getVisibleViewControllerFrom( vc: navigationController.visibleViewController!)
} else if vc.isKind(of: UITabBarController.self) {
let tabBarController = vc as! UITabBarController
return UIWindow.getVisibleViewControllerFrom(vc: tabBarController.selectedViewController!)
} else {
if let presentedViewController = vc.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController)
} else {
return vc;
}
}
}
}
How to change DatePicker dialog color for Android 5.0
Create a new style
<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/blue_500</item>
</style>
Java code:
The parent theme is the key here.
Choose your colorAccent
DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);
Result:
How to Cast Objects in PHP
If the object you are trying to cast from or to has properties that are also user-defined classes, and you don't want to go through reflection, you can use this.
<?php
declare(strict_types=1);
namespace Your\Namespace\Here
{
use Zend\Logger; // or your logging mechanism of choice
final class OopFunctions
{
/**
* @param object $from
* @param object $to
* @param Logger $logger
*
* @return object
*/
static function Cast($from, $to, $logger)
{
$logger->debug($from);
$fromSerialized = serialize($from);
$fromName = get_class($from);
$toName = get_class($to);
$toSerialized = str_replace($fromName, $toName, $fromSerialized);
$toSerialized = preg_replace("/O:\d*:\"([^\"]*)/", "O:" . strlen($toName) . ":\"$1", $toSerialized);
$toSerialized = preg_replace_callback(
"/s:\d*:\"[^\"]*\"/",
function ($matches)
{
$arr = explode(":", $matches[0]);
$arr[1] = mb_strlen($arr[2]) - 2;
return implode(":", $arr);
},
$toSerialized
);
$to = unserialize($toSerialized);
$logger->debug($to);
return $to;
}
}
}
Convert double to float in Java
Use dataType casting. For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;
Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?
Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.
You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.
In your settings.xml you would add something like this to set your internal repository as as mirror for central:
<mirrors>
<mirror>
<id>ibiblio.org</id>
<name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
<url>http://path/to/my/repository</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.
A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.
You would configure the repository (in your pom or a profile in the settings.xml) as follows:
<repository>
<id>central</id>
<url>http://repo1.maven.org/maven2</url>
<updatePolicy>never</updatePolicy>
</repository>
How to check for an empty object in an AngularJS view
I had to validate an empty object check as below
ex:
<div data-ng-include="'/xx/xx/xx/regtabs.html'" data-ng-if =
"$parent.$eval((errors | json) != '{}')" >
</div>
The error is my scope object, it is being defined in my controller as $scope.error = {};
Parsing JSON from XmlHttpRequest.responseJSON
I think you have to include jQuery to use responseJSON
.
Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");
UPDATE:Please read the comment regarding eval
, you can test with eval, but don't use it in working extension.
OR
use json_parse : it does not use eval
How to convert string to Date in Angular2 \ Typescript?
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
What is the easiest way to initialize a std::vector with hardcoded elements?
If your compiler supports Variadic macros (which is true for most modern compilers), then you can use the following macro to turn vector initialization into a one-liner:
#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
With this macro, you can define an initialized vector with code like this:
INIT_VECTOR(int, my_vector, {1, 2, 3, 4});
This would create a new vector of ints named my_vector with the elements 1, 2, 3, 4.
MIN and MAX in C
I don't think that they are standardised macros. There are standardised functions for floating point already, fmax
and fmin
(and fmaxf
for floats, and fmaxl
for long doubles).
You can implement them as macros as long as you are aware of the issues of side-effects/double-evaluation.
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
In most cases, you can leave it to the compiler to determine what you're trying to do and optimise it as best it can. While this causes problems when used like MAX(i++, j++)
, I doubt there is ever much need in checking the maximum of incremented values in one go. Increment first, then check.
Make div fill remaining space along the main axis in flexbox
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
Maximum call stack size exceeded on npm install
The one thing that finally worked for me on Mac was upgrading from node 8.12 to 10.x using NVM.
I uninstalled all other versions of Node with NVM, then installed 10.x, then ran nvm alias default node
, which tells NVM to always default to the latest available node version on a shell.
After that, my live reloading issue went away!
Best way to reset an Oracle sequence to the next value in an existing column?
With oracle 10.2g:
select level, sequence.NEXTVAL
from dual
connect by level <= (select max(pk) from tbl);
will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows).
Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL.
Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.
Configuring IntelliJ IDEA for unit testing with JUnit
One way of doing this is to do add junit.jar to your $CLASSPATH
as an external dependency.
So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.
In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.
How do I use JDK 7 on Mac OSX?
Get cask
brew tap caskroom/cask
Install java7:
brew tap caskroom/versions
brew cask install java7
(I had difficulty finding the download link of java7 on oracle website, as they're just "recommending" java8 )
EDIT January 2018 (As pointed by Ankur):
Use zulu7 cask. Zulu is a certified build of OpenJDK produced by Azul Systems that should be around for a long time (they even offer JDK6 builds still).
brew cask install caskroom/versions/zulu7
How to loop through a HashMap in JSP?
Below code works for me
first I defined the partnerTypesMap
like below in the server side,
Map<String, String> partnerTypes = new HashMap<>();
after adding values to it I added the object to model
,
model.addAttribute("partnerTypesMap", partnerTypes);
When rendering the page I use below foreach
to print them one by one.
<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
<form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>
Difference between volatile and synchronized in Java
volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1;
int geti1() {return i1;}
volatile int i2;
int geti2() {return i2;}
int i3;
synchronized int geti3() {return i3;}
geti1()
accesses the value currently stored in i1
in the current thread.
Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updated i1
in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1
, for thread1 to have a value of 2 for i1
and for thread2 to have a value of 3 for i1
if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
On the other hand, geti2()
effectively accesses the value of i2
from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.
There are two differences between volitile and synchronized.
Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3()
does the following:
- The thread acquires the lock on the monitor for object this .
- The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
- The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
- (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
- The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html
long long in C/C++
It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).
The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.
Can you force Visual Studio to always run as an Administrator in Windows 8?
I know this is a little late, but I just figured out how to do this by modifying (read, "hacking") the manifest of the devenv.exe file. I should have come here first because the stated solutions seem a little easier, and probably more supported by Microsoft. :)
Here's how I did it:
- Create a project in VS called "Exe Manifests". (I think any version will work, but I used 2013 Pro. Also, it doesn't really matter what you name it.)
- "Add existing item" to the project, browse to the Visual Studio exe, and click Okay. In my case, it was "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe".
- Double-click on the "devenv.exe" file that should now be listed as a file in your project. It should bring up the exe in a resource editor.
- Expand the "RT_MANIFEST" node, then double-click on "1" under that. This will open up the executable's manifest in the binary editor.
- Find the requestedExecutionLevel tag and replace "asInvoker" with "requireAdministrator". A la:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>
- Save the file.
You've just saved the copy of the executable that was added to your project. Now you need to back up the original and copy your modified exe to your installation directory.
As I said, this is probably not the right way to do it, but it seems to work. If anyone knows of any negative fallout or requisite wrist-slapping that needs to happen, please chime in!
Converting char[] to byte[]
You could make a method:
public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}
Hope this helps
Is there any way to start with a POST request using Selenium?
One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"
... elements with the appropriate post data.
For example you might create a SeleniumTestStart.html
page with these contents:
<body>
<form action="/index.php" method="post">
<input id="starttestbutton" type="submit" value="starttest"/>
<input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
</form>
</body>
In this example, index.php is where your normal web app is located.
The Selenium code at the start of your tests would then include:
open /SeleniumTestStart.html
clickAndWait starttestbutton
This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.
Obviously there are some limitations to this approach:
- data cannot be too large (e.g. image data)
- security might be an issue so you need to make sure that these test files don't end up on your production server
- you may need to make your entry points with something like php instead of html if you need to set cookies before the Selenium test gets going
- some web apps check the referrer to make sure someone isn't hacking the app - in this case this approach probably won't work - you may be able to loosen this checking in a dev environment so it allows referrers from trusted hosts (not self, but the actual test host)
Please consider reading my article about the Qualities of an Ideal Test
ImportError: No module named pandas
You're missing a few (not terribly clear) steps. Pandas is distributed through pip as a wheel, which means you need to do:
pip install wheel
pip install pandas
You're probably going to run into other issues after this - it looks like you're installing on Windows which isn't the most friendly of targets for numpy/scipy/pandas. Alternatively, you could pickup a binary installer from here.
You also had an error installing numpy. Like before, I recommend grabbing a binary installer for this, as it's not a simple process. However, you can resolve your current error by installing this package from Microsoft.
While it's completely possible to get a perfect environment setup on Windows, I have found the quality-of-life for a Python dev is vastly improved by setting up a debian VM. Especially with the scientific packages, you will run into many cases like this.
When to use StringBuilder in Java
The + operator uses public String concat(String str)
internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.
However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)
Fatal error: Call to undefined function mb_strlen()
In case Google search for this error
Call to undefined function mb_ereg_match()
takes somebody to this thread. Installing php-mbstring resolves it too.
Ubuntu 18.04.1, PHP 7.2.10
sudo apt-get install php7.2-mbstring
jQuery: get the file name selected from <input type="file" />
It is just such simple as writing:
$('input[type=file]').val()
Anyway, I suggest using name or ID attribute to select your input.
And with event, it should look like this:
$('input[type=file]').change(function(e){
$in=$(this);
$in.next().html($in.val());
});
Clearing state es6 React
You can clone your state object, loop through each one, and set it to undefined
. This method is not as good as the accepted answer, though.
const clonedState = this.state;
const keys = Object.keys(clonedState);
keys.forEach(key => (clonedState[key] = undefined));
this.setState(clonedState);
Google Maps shows "For development purposes only"
If your mapTypeId is SATELLITE
or HYBRID
well, it is just a watermark, you can hide it if you change the <div>
that has z-index=100
I use
setInterval(function(){
$("*").each(function() {
if ($(this).css("zIndex") == 100) {
$(this).css("zIndex", "-100");
}
})}
, 10);
or you can use
map.addListener('idle', function(e) {
//same function
}
but it is not as responsive as setInterval
Add custom icons to font awesome
Similar approach to @Samuel-bergström:
- Download Fontawesome SVG https://github.com/FortAwesome/Font-Awesome/blob/master/src/assets/font-awesome/fonts/fontawesome-webfont.svg
- Download FontForge http://fontforge.github.io/en-US/downloads/
- Download Inkscape
- Open Inskscape and create a single layer shape as your new font icon
- Save SVG file, Close Inkscape
- Open FontForge (If you have multiple monitors, use Windows-LeftArrow, to reposition as they have strange SWING java windows that go off monitor, and have modal problems with popups - I had to check my task bar for some)
- File | Open fontawesome-webfont.svg
- File | Import
- Scroll to the bottom, Right Click on Icon | Glyph Info
- Update Glyph Name to uniFXXX (XXX is something like 501, a higher number than the highest Unicode used in v4.5 of FontAwesome)
- Unicode Vlaue U+fXXX
- Click OK
- File | Save
- File | Generate Fonts ...
- Close FontForge
- Open your web project
- Copy your font files to the (in my project) "\Content\fonts\" folder.
- Edit "\Content\styles\fa\path.less" to be like:
_x000D_
_x000D_
@font-face {_x000D_
font-family: 'FontAwesome';_x000D_
//src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
src: _x000D_
//url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
//url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
// src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
font-weight: normal;_x000D_
font-style: normal;_x000D_
}
_x000D_
_x000D_
_x000D_
I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.
and finally, as Samuel mentions, update your CSS/LESS with:
.fa-XXX:before { content: "\f501"; }
.gitignore after commit
Even after you delete the file(s) and then commit, you will still have those files in history. To delete those, consider using BFG Repo-Cleaner. It is an alternative to git-filter-branch.
How do you fix the "element not interactable" exception?
For those discovering this now and the above answers didn't work, the issue I had was the screen wasn't big enough. I added this when initializing my ChromeDriver, and it fixed the problem:
options.add_argument("window-size=1200x600")
How do Python functions handle the types of the parameters that you pass in?
The other answers have done a good job at explaining duck typing and the simple answer by tzot:
Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.
However, one interesting thing has changed since 2010 (when the question was first asked), namely the implementation of PEP 3107 (implemented in Python 3). You can now actually specify the type of a parameter and the type of the return type of a function like this:
def pick(l: list, index: int) -> int:
return l[index]
We can here see that pick
takes 2 parameters, a list l
and an integer index
. It should also return an integer.
So here it is implied that l
is a list of integers which we can see without much effort, but for more complex functions it can be a bit confusing as to what the list should contain. We also want the default value of index
to be 0. To solve this you may choose to write pick
like this instead:
def pick(l: "list of ints", index: int = 0) -> int:
return l[index]
Note that we now put in a string as the type of l
, which is syntactically allowed, but it is not good for parsing programmatically (which we'll come back to later).
It is important to note that Python won't raise a TypeError
if you pass a float into index
, the reason for this is one of the main points in Python's design philosophy: "We're all consenting adults here", which means you are expected to be aware of what you can pass to a function and what you can't. If you really want to write code that throws TypeErrors you can use the isinstance
function to check that the passed argument is of the proper type or a subclass of it like this:
def pick(l: list, index: int = 0) -> int:
if not isinstance(l, list):
raise TypeError
return l[index]
More on why you should rarely do this and what you should do instead is talked about in the next section and in the comments.
PEP 3107 does not only improve code readability but also has several fitting use cases which you can read about here.
Type annotation got a lot more attention in Python 3.5 with the introduction of PEP 484 which introduces a standard module for type hints.
These type hints came from the type checker mypy (GitHub), which is now PEP 484 compliant.
With the typing module comes with a pretty comprehensive collection of type hints, including:
List
, Tuple
, Set
, Map
- for list
, tuple
, set
and map
respectively.
Iterable
- useful for generators.
Any
- when it could be anything.
Union
- when it could be anything within a specified set of types, as opposed to Any
.
Optional
- when it might be None. Shorthand for Union[T, None]
.
TypeVar
- used with generics.
Callable
- used primarily for functions, but could be used for other callables.
These are the most common type hints. A complete listing can be found in the documentation for the typing module.
Here is the old example using the annotation methods introduced in the typing module:
from typing import List
def pick(l: List[int], index: int) -> int:
return l[index]
One powerful feature is the Callable
which allows you to type annotate methods that take a function as an argument. For example:
from typing import Callable, Any, Iterable
def imap(f: Callable[[Any], Any], l: Iterable[Any]) -> List[Any]:
"""An immediate version of map, don't pass it any infinite iterables!"""
return list(map(f, l))
The above example could become more precise with the usage of TypeVar
instead of Any
, but this has been left as an exercise to the reader since I believe I've already filled my answer with too much information about the wonderful new features enabled by type hinting.
Previously when one documented Python code with for example Sphinx some of the above functionality could be obtained by writing docstrings formatted like this:
def pick(l, index):
"""
:param l: list of integers
:type l: list
:param index: index at which to pick an integer from *l*
:type index: int
:returns: integer at *index* in *l*
:rtype: int
"""
return l[index]
As you can see, this takes a number of extra lines (the exact number depends on how explicit you want to be and how you format your docstring). But it should now be clear to you how PEP 3107 provides an alternative that is in many (all?) ways superior. This is especially true in combination with PEP 484 which, as we have seen, provides a standard module that defines a syntax for these type hints/annotations that can be used in such a way that it is unambiguous and precise yet flexible, making for a powerful combination.
In my personal opinion, this is one of the greatest features in Python ever. I can't wait for people to start harnessing the power of it. Sorry for the long answer, but this is what happens when I get excited.
An example of Python code which heavily uses type hinting can be found here.
How to "inverse match" with regex?
(?!Andrea).{6}
Assuming your regexp engine supports negative lookaheads..
Edit: ..or maybe you'd prefer to use [A-Za-z]{6}
in place of .{6}
Edit (again): Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching, they leave that to whatever language you are using them with.
How to get JavaScript variable value in PHP
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
JavaScript hide/show element
You can also use this code to show/hide elements:
document.getElementById(id).style.visibility = "hidden";
document.getElementById(id).style.visibility = "visible";
Note The difference between style.visibility
and style.display
is
when using visibility:hidden unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.
See this link to see the differences.
C# ASP.NET Single Sign-On Implementation
There are several Identity providers with SSO support out of the box, also third-party** products.
** The only problem with third party products is that they charge per user/month, and it can be quite expensive.
Some of the tools available and with APIs for .NET are:
If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.
C#
- IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
- IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
- OAuth 2.0 by Okta
Javascript
- passport-openidconnect (node.js)
- oidc-provider (node.js)
- openid-client (node.js)
Python
- pyoidc
- Django OIDC Provider
I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.
Twitter Bootstrap Multilevel Dropdown Menu
[Twitter Bootstrap v3]
To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,
CSS:
.dropdown-menu>li /* To prevent selection of text */
{ position:relative;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
/* Rules below not implemented in browsers yet */
-o-user-select: none;
user-select: none;
cursor:pointer;
}
.dropdown-menu .sub-menu
{
left: 100%;
position: absolute;
top: 0;
display:none;
margin-top: -1px;
border-top-left-radius:0;
border-bottom-left-radius:0;
border-left-color:#fff;
box-shadow:none;
}
.right-caret:after,.left-caret:after
{ content:"";
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
display: inline-block;
height: 0;
vertical-align: middle;
width: 0;
margin-left:5px;
}
.right-caret:after
{ border-left: 5px solid #ffaf46;
}
.left-caret:after
{ border-right: 5px solid #ffaf46;
}
JQuery:
$(function(){
$(".dropdown-menu > li > a.trigger").on("click",function(e){
var current=$(this).next();
var grandparent=$(this).parent().parent();
if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
$(this).toggleClass('right-caret left-caret');
grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
grandparent.find(".sub-menu:visible").not(current).hide();
current.toggle();
e.stopPropagation();
});
$(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
var root=$(this).closest('.dropdown');
root.find('.left-caret').toggleClass('right-caret left-caret');
root.find('.sub-menu:visible').hide();
});
});
HTML:
<div class="dropdown" style="position:relative">
<a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<a class="trigger right-caret">Level 1</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 2</a></li>
<li>
<a class="trigger right-caret">Level 2</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 3</a></li>
<li><a href="#">Level 3</a></li>
<li>
<a class="trigger right-caret">Level 3</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Level 2</a></li>
</ul>
</li>
<li><a href="#">Level 1</a></li>
<li><a href="#">Level 1</a></li>
</ul>
</div>
Using other keys for the waitKey() function of opencv
This prints the key combination directly to the image:
The first window shows 'z'
pressed, the second shows 'ctrl' + 'z'
pressed. When a key combination is used, a question mark appear.
Don't mess up with the question mark code, which is 63
.
import numpy as np
import cv2
im = np.zeros((100, 300), np.uint8)
cv2.imshow('Keypressed', im)
while True:
key = cv2.waitKey(0)
im_c = im.copy()
cv2.putText(
im_c,
f'{chr(key)} -> {key}',
(10, 60),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255,255,255),
2)
cv2.imshow('Keypressed', im_c)
if key == 27: break # 'ESC'
"Conversion to Dalvik format failed with error 1" on external JAR
My problem was in integration of Ant + ProGuard + AdMob SDK library + Debug mode. I was building debug APK using Ant and Added AdMob SDK JAR to libs/
directory. Eclipse generated the debug APK normally, but Ant could not. I was getting the following error.
[apply] UNEXPECTED TOP-LEVEL EXCEPTION:
[apply] java.lang.IllegalArgumentException: already added: Lcom/google/ads/AdActivity;
[apply] at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
I also had ProGuard turned on for debug build in my build.xml
(default is off):
<target name="-debug-obfuscation-check">
<property name="proguard.enabled" value="true"/>
</target>
That was the problem. Somehow ProGuard and AdMob SDK do not live together in debug mode. ProGuard did not obfuscate AdActivity
class so it appeared in bin/proguard/obfuscated.jar
unobfuscated, but the same class exists in the AdMob SDK JAR file. Eclipse was building debug APK without ProGuard, so it worked fine.
So my solution was just to turn off ProGuard for debug builds in build.xml
.
I hope it helps somebody.
WHERE statement after a UNION in SQL?
If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:
SELECT *
FROM (SELECT * FROM TableA
UNION
SELECT * FROM TableB
) AS U
WHERE U.Col1 = ...
I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.
Code to loop through all records in MS Access
In "References", import DAO 3.6 object reference.
private sub showTableData
dim db as dao.database
dim rs as dao.recordset
set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously
'populate the table
rs.movelast
rs.movefirst
do while not rs.EOF
debug.print(rs!myField) 'myField is a field name in table myTable
rs.movenext 'press Ctrl+G to see debuG window beneath
loop
msgbox("End of Table")
end sub
You can interate data objects like queries and filtered tables in different ways:
Trhough query:
private sub showQueryData
dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string
sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"
set db = currentDb
set rs = db.openRecordset(sqlStr)
rs.movefirst
do while not rs.EOF
debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
rs.movenext
loop
msgbox("End of customers from Brazil")
end sub
You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.
I hope I've helped.
How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
HTML Mobile -forcing the soft keyboard to hide
I am fighting the soft keyboard on the Honeywell Dolphin 70e with Android 4.0.3. I don't need the keyboard because the input comes from the builtin barcode reader through the 'scanwedge', set to generate key events.
What I found was that the trick described in the earlier answers of:
input.blur();
input.focus();
works, but only once, right at page initialization. It puts the focus in the input element without showing the soft keyboard. It does NOT work later, e.g. after a TAB character in the suffix of the barcode causes the onblur or oninput event on the input element.
To read and process lots of barcodes, you may use a different postfix than TAB (9), e.g. 8, which is not interpreted by the browser. In the input.keydown
event, use e.keyCode == 8
to detect a complete barcode to be processed.
This way, you initialize the page with focus in the input element, with keyboard hidden, all barcodes go to the input element, and the focus never leaves that element. Of course, the page cannot have other input elements (like buttons), because then you will not be able to return to the barcode input element with the soft keyboard hidden.
Perhaps reloading the page after a button click may be able to hide the keyboard. So use ajax for fast processing of barcodes, and use a regular asp.net button with PostBack to process a button click and reload the page to return focus to the barcode input with the keyboard hidden.
NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
Converting Milliseconds to Minutes and Seconds?
tl;dr
Duration d = Duration.ofMillis( … ) ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
Java 9 and later
In Java 9 and later, create a Duration
and call the to…Part
methods. In this case: toMinutesPart
and toSecondsPart
.
Capture the start & stop of your stopwatch.
Instant start = Instant.now();
…
Instant stop = Instant.now();
Represent elapsed time in a Duration
object.
Duration d = Duration.between( start , stop );
Interrogate for each part, the minutes and the seconds.
int minutes = d.toMinutesPart();
int seconds = d.toSecondsPart();
You might also want to see if your stopwatch ran expectedly long.
Boolean ranTooLong = ( d.toDaysPart() > 0 ) || ( d.toHoursPart() > 0 ) ;
Java 8
In Java 8, the Duration
class lacks to…Part
methods. You will need to do math as shown in the other Answers.
long entireDurationAsSeconds = d.getSeconds();
Or let Duration
do the math.
long minutesPart = d.toMinutes();
long secondsPart = d.minusMinutes( minutesPart ).getSeconds() ;
See live code in IdeOne.com.
Interval: 2016-12-18T08:39:34.099Z/2016-12-18T08:41:49.099Z
d.toString(): PT2M15S
d.getSeconds(): 135
Elapsed: 2M 15S
Resolution
FYI, the resolution of now
methods changed between Java 8 and Java 9. See this Question.
- Java 9 captures the moment with a resolution as fine as nanoseconds. Resolution depends on capability of your computer’s hardware. I see microseconds (six digits of decimal fraction) on MacBook Pro Retina with macOS Sierra.
- Java 8 captures the moment only up to milliseconds. The implementation of
Clock
is limited to a resolution of milliseconds. So you can store values in nanoseconds but only capture them in milliseconds.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
Update R using RStudio
Don't use Rstudio to update R. Rstudio IS NOT R, Rstudio is just an IDE. This answer is a summary of previous answers for different OS. For all OS it is convenient to have a look in advance what will happen with the packages you have already installed here.
WINDOWS ->> Open CMD/Powershell as an administrator and type "R" to go into interactive mode. If this does not work, search and run RGui.exe instead of writing R in the console ...and then:
lib_path <- gsub( "/", "\\\\" , Sys.getenv("R_LIBS_USER"))
install.packages("installr", lib = lib_path)
install.packages("stringr", lib_path)
library(stringr, lib.loc = lib_path)
library(installr, lib.loc = lib_path)
installr::updateR()
MacOS ->> You can use updateR package. The package is not on CRAN, so you’ll need to run the following code in Rgui:
install.packages("devtools")
devtools::install_github("AndreaCirilloAC/updateR")
updateR(admin_password = "PASSWORD") # Where "PASSWORD" stands for your system password
Note that it is planned to merge updateR and installR in the near future to work for both Mac and Windows.
Linux ->> For the moment installr
is NOT available for Linux/MacOS (see documentation for current version 0.20). As R is installed, you can follow these instructions (in Ubuntu, although the idea is the same in other distros: add the source, update and upgrade and install.)
Get generic type of java.util.List
Expanding on Steve K's answer:
/**
* Performs a forced cast.
* Returns null if the collection type does not match the items in the list.
* @param data The list to cast.
* @param listType The type of list to cast to.
*/
static <T> List<? super T> castListSafe(List<?> data, Class<T> listType){
List<T> retval = null;
//This test could be skipped if you trust the callers, but it wouldn't be safe then.
if(data!=null && !data.isEmpty() && listType.isInstance(data.iterator().next().getClass())) {
@SuppressWarnings("unchecked")//It's OK, we know List<T> contains the expected type.
List<T> foo = (List<T>)data;
return retval;
}
return retval;
}
Usage:
protected WhateverClass add(List<?> data) {//For fluant useage
if(data==null) || data.isEmpty(){
throw new IllegalArgumentException("add() " + data==null?"null":"empty"
+ " collection");
}
Class<?> colType = data.iterator().next().getClass();//Something
aMethod(castListSafe(data, colType));
}
aMethod(List<Foo> foo){
for(Foo foo: List){
System.out.println(Foo);
}
}
aMethod(List<Bar> bar){
for(Bar bar: List){
System.out.println(Bar);
}
}
Foreach Control in form, how can I do something to all the TextBoxes in my Form?
Even better, you can encapsule this to clear any type of controls you want in one method, like this:
public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;
if (!limpiar) return;
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = @"-1";
}
}
Capture Image from Camera and Display in Activity
I know it's a quite old thread, but all these solutions are not completed and don't work on some devices when user rotates camera because data in onActivityResult is null. So here is solution which I have tested on lots of devices and haven't faced any problem so far.
First declare your Uri variable in your activity:
private Uri uriFilePath;
Then create your temporary folder for storing captured image and make intent for capturing image by camera:
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
if (!mainDirectory.exists())
mainDirectory.mkdirs();
Calendar calendar = Calendar.getInstance();
uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis()));
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
startActivityForResult(intent, 1);
}
And now here comes one of the most important things, you have to save your uriFilePath in onSaveInstanceState, because if you didn't do that and user rotated his device while using camera, your uri would be null.
@Override
protected void onSaveInstanceState(Bundle outState) {
if (uriFilePath != null)
outState.putString("uri_file_path", uriFilePath.toString());
super.onSaveInstanceState(outState);
}
After that you should always recover your uri in your onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (uriFilePath == null && savedInstanceState.getString("uri_file_path") != null) {
uriFilePath = Uri.parse(savedInstanceState.getString("uri_file_path"));
}
}
}
And here comes last part to get your Uri in onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
String filePath = uriFilePath.getPath(); // Here is path of your captured image, so you can create bitmap from it, etc.
}
}
}
P.S. Don't forget to add permissions for Camera and Ext. storage writing to your Manifest.
How to read the Stock CPU Usage data
More about "load average"
showing CPU load over 1 minute, 5 minutes and 15 minutes
Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.
WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:
during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%.
You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.
To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.
more info : Link
Finding partial text in range, return an index
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
Partial Dependency (Databases)
Partial dependency means that a nonprime attribute is functionally dependent on part of a candidate key. (A nonprime attribute is an attribute that's not part of any candidate key.)
For example, let's start with R{ABCD}, and the functional dependencies AB->CD and A->C.
The only candidate key for R is AB. C and D are a nonprime attributes. C is functionally dependent on A. A is part of a candidate key. That's a partial dependency.
How do I encode and decode a base64 string?
URL safe Base64 Encoding/Decoding
public static class Base64Url
{
public static string Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
.Replace('/', '_');
}
public static string Decode(string text)
{
text = text.Replace('_', '/').Replace('-', '+');
switch (text.Length % 4)
{
case 2:
text += "==";
break;
case 3:
text += "=";
break;
}
return Encoding.UTF8.GetString(Convert.FromBase64String(text));
}
}
Seeding the random number generator in Javascript
Most of the answers here produce biased results. So here's a tested function based on seedrandom library from github:
!function(f,a,c){var s,l=256,p="random",d=c.pow(l,6),g=c.pow(2,52),y=2*g,h=l-1;function n(n,t,r){function e(){for(var n=u.g(6),t=d,r=0;n<g;)n=(n+r)*l,t*=l,r=u.g(1);for(;y<=n;)n/=2,t/=2,r>>>=1;return(n+r)/t}var o=[],i=j(function n(t,r){var e,o=[],i=typeof t;if(r&&"object"==i)for(e in t)try{o.push(n(t[e],r-1))}catch(n){}return o.length?o:"string"==i?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[n,S(a)]:null==n?function(){try{var n;return s&&(n=s.randomBytes)?n=n(l):(n=new Uint8Array(l),(f.crypto||f.msCrypto).getRandomValues(n)),S(n)}catch(n){var t=f.navigator,r=t&&t.plugins;return[+new Date,f,r,f.screen,S(a)]}}():n,3),o),u=new m(o);return e.int32=function(){return 0|u.g(4)},e.quick=function(){return u.g(4)/4294967296},e.double=e,j(S(u.S),a),(t.pass||r||function(n,t,r,e){return e&&(e.S&&v(e,u),n.state=function(){return v(u,{})}),r?(c[p]=n,t):n})(e,i,"global"in t?t.global:this==c,t.state)}function m(n){var t,r=n.length,u=this,e=0,o=u.i=u.j=0,i=u.S=[];for(r||(n=[r++]);e<l;)i[e]=e++;for(e=0;e<l;e++)i[e]=i[o=h&o+n[e%r]+(t=i[e])],i[o]=t;(u.g=function(n){for(var t,r=0,e=u.i,o=u.j,i=u.S;n--;)t=i[e=h&e+1],r=r*l+i[h&(i[e]=i[o=h&o+t])+(i[o]=t)];return u.i=e,u.j=o,r})(l)}function v(n,t){return t.i=n.i,t.j=n.j,t.S=n.S.slice(),t}function j(n,t){for(var r,e=n+"",o=0;o<e.length;)t[h&o]=h&(r^=19*t[h&o])+e.charCodeAt(o++);return S(t)}function S(n){return String.fromCharCode.apply(0,n)}if(j(c.random(),a),"object"==typeof module&&module.exports){module.exports=n;try{s=require("crypto")}catch(n){}}else"function"==typeof define&&define.amd?define(function(){return n}):c["seed"+p]=n}("undefined"!=typeof self?self:this,[],Math);
function randIntWithSeed(seed, max=1) {
/* returns a random number between [0,max] including zero and max
seed can be either string or integer */
return Math.round(new Math.seedrandom('seed' + seed)()) * max
}
test for true randomness of this code: https://es6console.com/kkjkgur2/
Get only the Date part of DateTime in mssql
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit:
True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
AngularJS - Passing data between pages
If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.
Redefine tab as 4 spaces
To define this on a permanent basis for the current user, create (or edit) the .vimrc
file:
$ vim ~/.vimrc
Then, paste the configuration below into the file. Once vim is restarted, the tab settings will apply.
set tabstop=4 " The width of a TAB is set to 4.
" Still it is a \t. It is just that
" Vim will interpret it to be having
" a width of 4.
set shiftwidth=4 " Indents will have a width of 4
set softtabstop=4 " Sets the number of columns for a TAB
set expandtab " Expand TABs to spaces