I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.
I had the same issue, I cleaned and rebuilt the project and it worked.
You cannot add a ListView in a scroll View, as list view also scolls and there would be a synchonization problem between listview scroll and scroll view scoll. You can make a CustomList View and add this method into it.
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* Prevent parent controls from stealing our events once we've gotten a touch down
*/
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
ViewParent p = getParent();
if (p != null) {
p.requestDisallowInterceptTouchEvent(true);
}
}
return false;
}
This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :
ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...
maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.
This is a solution that wait if there is a second clic before executing any action
int init = 0;
myView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (init == 0) {
init++;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (init == 1) {
Log.d("hereGoes", "actionOne");
} else {
Log.d("hereGoes", "actionTwo");
}
init = 0;
}
}, 250);
} else {
init++;
}
}
});
Although it wouldn't be a "true object", you could always do something like this:
var foo = [
{Key1: "key1"},
{Key2: "key2"},
{Key3: "key3"}
];
alert(foo.length); // === 3
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
text.indexOf("newString")
is the best method instead of startsWith
.
Example:
var text = "Format";
if(text.indexOf("Format") == 0) {
alert(text + " = Format");
} else {
alert(text + " != Format");
}
All modules in Python have to have a certain directory structure. You can find details here.
Create an empty file called __init__.py
under the model
directory, such that your directory structure would look something like that:
.
+-- project
+-- src
+-- hello-world.py
+-- model
+-- __init__.py
+-- order.py
Also in your hello-world.py
file change the import statement to the following:
from model.order import SellOrder
That should fix it
P.S.: If you are placing your model
directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path
.
A .pl is a single script.
In .pm (Perl Module) you have functions that you can use from other Perl scripts:
A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.
You need to download the ASP.NET MVC framework on the server hosting your application. It's a quick fix just download and install from here (This is the MVC 3 framework http://www.asp.net/mvc/mvc3), then boom you are good to go.
Button btnDownload = (Button) findViewById(R.id.DownloadView);
Button btnApp = (Button) findViewById(R.id.AppView);
btnDownload.setOnClickListener(handler);
btnApp.setOnClickListener(handler);
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
if(v==btnDownload){
// doStuff
Intent intentMain = new Intent(CurrentActivity.this ,
SecondActivity.class);
CurrentActivity.this.startActivity(intentMain);
Log.i("Content "," Main layout ");
}
if(v==btnApp){
// doStuff
Intent intentApp = new Intent(CurrentActivity.this,
ThirdActivity.class);
CurrentActivity.this.startActivity(intentApp);
Log.i("Content "," App layout ");
}
}
};
Note : and then you should declare all your activities in the manifest .xml file like this :
<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>
EDIT : update this part of Code :) :
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE
setContentView(R.layout.app);
TextView tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("App View yo!?\n");
}
NB : check this (Broken link) Tutorial About How To Switch Between Activities.
Have you tried this:
Taken from the site:
pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled
try this one for centos 7 : service crond reload
If you know how many rows there will be in total you can use the ROW_NUMBER() function. Here's an examble from MSDN (http://msdn.microsoft.com/en-us/library/ms186734.aspx)
USE AdventureWorks;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
FROM Sales.SalesOrderHeader
)
SELECT *
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;
A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[][] test;
test = new int[5][];//'2D array'
for (int i=0;i<test.length;i++)
test[i] = new int[i];
System.out.println(Arrays.deepToString(test));
Object[] test2;
test2 = new Object[5];//array of objects
for (int i=0;i<test2.length;i++)
test2[i] = new int[i];//array is a object too
System.out.println(Arrays.deepToString(test2));
}
}
Outputs
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
The arrays test
and test2
are (more or less) the same.
is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)
with open('in.txt') as f:
rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))
another way:
is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4),
as well for complex matrices see the example below (only change int
to complex
)
with open('in.txt') as f:
data = []
cols,rows=list(map(int, f.readline().split()))
for i in range(0, rows):
data.append(list(map(int, f.readline().split()[:cols])))
print (data)
I updated the code, this method is working for any number of matrices and any kind of matrices(int
,complex
,float
) in the initial in.txt
file.
This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes
print to print()
and
print "%7g" %a[i,j], to print ("%7g" %a[i,j],end="")
the script:
import numpy as np
def printMatrix(a):
print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
rows = a.shape[0]
cols = a.shape[1]
for i in range(0,rows):
for j in range(0,cols):
print "%7g" %a[i,j],
print
print
def readMatrixFile(FileName):
rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
return a
def readMatrixFileComplex(FileName):
data = []
rows,cols=list(map(int, FileName.readline().split()))
for i in range(0, rows):
data.append(list(map(complex, FileName.readline().split()[:cols])))
a = np.array(data)
return a
f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()
print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)
with open('complex_in.txt') as fid:
a2=readMatrixFileComplex(fid)
print(a2)
b2=readMatrixFileComplex(fid)
print(b2)
print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)
as input file I take in.txt
:
4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5
and complex_in.txt
3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j
and the output look like:
Matrix[4][4]
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
Matrix[4][3]
4.02 -3 4
-13 19 -7
3 -2 7
-1 1 -1
Matrix[3][4]
1 2 -2 0
-3 4 7 2
6 0 3 1
Matrix[4][2]
-1 3
0 9
1 -11
4 -5
matrix multiplication
Matrix[4][3]
-6.98 15 3
-35.96 70 20
-104.94 189 57
-255.92 420 96
Matrix[3][2]
-3 43
18 -60
1 -20
[[ 1.+1.j 2.+2.j -2.-2.j 0.+0.j]
[-3.-3.j 4.+4.j 7.+7.j 2.+2.j]
[ 6.+6.j 0.+0.j 3.+3.j 1.+1.j]]
[[ -1. -1.j 3. +3.j]
[ 0. +0.j 9. +9.j]
[ 1. +1.j -11.-11.j]
[ 4. +4.j -5. -5.j]]
complex matrix multiplication
[[ 0. -6.j 0. +86.j]
[ 0. +36.j 0.-120.j]
[ 0. +2.j 0. -40.j]]
real part of complex matrix
Matrix[3][2]
0 0
0 0
0 0
imaginary part of complex matrix
Matrix[3][2]
-6 86
36 -120
2 -40
According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:
git checkout -- a
(where a
is the directory you want to hard-reset). The original behavior can be accessed via
git checkout --ignore-skip-worktree-bits -- a
You need to create a TypeReference
object for each generic type you use and use that for deserialization. For example -
mapper.readValue(jsonString, new TypeReference<Data<String>>() {});
Both of them increase the variable i
by one. It's like saying i = i + 1
. The difference is subtle. If you're using it in a loop like this, there's no difference:
for (int i = 0; i < 100; i++) {
}
for (int i = 0; i < 100; ++i) {
}
If you want to know the difference, look at this example:
int a = 0;
int b = a++; // b = 0; a = 1
a = 0;
b = ++a: // b = 1; a = 1
The idea is that ++a
increments a
and returns that value, while a++
returns a's value and then increments a
.
This is how I solved it on Windows. I have git installed separately, and Idea just picks git's options automatically (Default Idea config, as I would get from clean installer).
Open the project in the command line. Make some changes there. And commit and push files via git which is installed on my machine. During push it will open a windows asking me to enter username and password. After that, when I make a commit-push from idea, it will simply work.
Try to avoid using grep
, if looking at resources.
if ( grep( /^$value$/, @badparams ) ) {
print "found";
}
for (@badparams) {
if ($_ eq $value) {
print "found";
last;
}
}
my %hash = map {$_ => 1} @badparams;
print "found" if (exists $hash{$value});
(added in Perl 5.10, marked is experimental in Perl 5.18).
use experimental 'smartmatch'; # for perl 5.18
print "found" if ($value ~~ @badparams);
List::MoreUtils
use List::MoreUtils qw(any);
@badparams = (1,2,3);
$value = 1;
print "found" if any {$_ == $value} @badparams;
For CSS, I found that max height of 180 is better for mobile phones landscape 320 when showing browser chrome.
.scrollable-menu {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
Also, to add visible scrollbars, this CSS should do the trick:
.scrollable-menu::-webkit-scrollbar {
-webkit-appearance: none;
width: 4px;
}
.scrollable-menu::-webkit-scrollbar-thumb {
border-radius: 3px;
background-color: lightgray;
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.75);
}
The changes are reflected here: https://www.bootply.com/BhkCKFEELL
My advice is to stick to rule 0 and not redo what standard libraries already do, if this is enough. Look at math.h (cmath in standard C++) and functions frexp, frexpf, frexpl, that break a floating point value (double, float, or long double) in its significand and exponent part. To extract the sign from the significand you can use signbit, also in math.h / cmath, or copysign (only C++11). Some alternatives, with slighter different semantics, are modf and ilogb/scalbn, available in C++11; http://en.cppreference.com/w/cpp/numeric/math/logb compares them, but I didn't find in the documentation how all these functions behave with +/-inf and NaNs. Finally, if you really want to use bitmasks (e.g., you desperately need to know the exact bits, and your program may have different NaNs with different representations, and you don't trust the above functions), at least make everything platform-independent by using the macros in float.h/cfloat.
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.
Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).
For context, I had this problem because I occasionally use Redux-Saga
to programmatically change the history object (say when a user successfully authenticates).
In the React Router docs, take a look at the <Router>
component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router
from a global module.
yarn add history
or npm install history --save
create a file called history.js
in your App.js
level folder (this was my preference)
// src/history.js
import createHistory from 'history/createBrowserHistory';
export default createHistory();`
Add this history object to your Router component like so
// src/App.js
import history from '../your/path/to/history.js;'
<Router history={history}>
// Route tags here
</Router>
Adjust the URL just like before by importing your global history object:
import history from '../your/path/to/history.js;'
history.push('new/path/here/');
Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.
More efficient would be using Enumerable.Except
:
var inListButNotInList2 = list.Except(list2);
var inList2ButNotInList = list2.Except(list);
This method is implemented by using deferred execution. That means you could write for example:
var first10 = inListButNotInList2.Take(10);
It is also efficient since it internally uses a Set<T>
to compare the objects. It works by first collecting all distinct values from the second sequence, and then streaming the results of the first, checking that they haven't been seen before.
In my case alter column was not working so one can use 'Modify' command, like:
alter table [table_name] MODIFY column [column_name] varchar(1200);
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
provide all custom services means written by you in component decorator section Example : providers: [serviceName]
note:if you are using service for exchanging data between components. declare providers: [serviceName] in module level
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
I had problem setting imageView.highlighted = NO;
(setting YES worked properly and the image changed to the highlighted one).
The solution was calling [imageView setHighlighted:NO];
Everything worked properly.
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
You can use the following code:
List<WebElement> checkbox = driver.findElements(By.name("vehicle"));
((WebElement) checkbox.get(0)).click();
My HTML code was as follows:
<.input type="checkbox" name="vehicle" value="Bike">I have a bike<br/>
<.input type="checkbox" name="vehicle" value="Car">I have a car<br/>
I don't think there is a way to print array for you in printf. "printf" function has no idea how long your array is.
one way
awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls
What the status is telling you is that you're behind the ref called origin/master
which is a local ref in your local repo. In this case that ref happens to track a branch in some remote, called origin
, but the status is not telling you anything about the branch on the remote. It's telling you about the ref, which is just a commit ID stored on your local filesystem (in this case, it's typically in a file called .git/refs/remotes/origin/master
in your local repo).
git pull
does two operations; first it does a git fetch
to get up to date with the commits in the remote repo (which updates the origin/master
ref in your local repo), then it does a git merge
to merge those commits into the current branch.
Until you do the fetch
step (either on its own or via git pull
) your local repo has no way to know that there are additional commits upstream, and git status
only looks at your local origin/master
ref.
When git status
says up-to-date, it means "up-to-date with the branch that the current branch tracks", which in this case means "up-to-date with the local ref called origin/master
". That only equates to "up-to-date with the upstream status that was retrieved last time we did a fetch
" which is not the same as "up-to-date with the latest live status of the upstream".
Why does it work this way? Well the fetch
step is a potentially slow and expensive network operation. The design of Git (and other distributed version control systems) is to avoid network operations when unnecessary, and is a completely different model to the typical client-server system many people are used to (although as pointed out in the comments below, Git's concept of a "remote tracking branch" that causes confusion here is not shared by all DVCSs). It's entirely possible to use Git offline, with no connection to a centralized server, and the output of git status
reflects this.
Creating and switching branches (and checking their status) in Git is supposed to be lightweight, not something that performs a slow network operation to a centralized system. The assumption when designing Git, and the git status
output, was that users understand this (too many Git features only make sense if you already know how Git works). With the adoption of Git by lots and lots of users who are not familiar with DVCS this assumption is not always valid.
The limit of requests in .Net can be configured from two properties together:
Web.Config/system.web/httpRuntime/maxRequestLength
Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength
(in bytes)References:
Example:
<location path="upl">
<system.web>
<!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
<!-- 100 MB in kilobytes -->
<httpRuntime maxRequestLength="102400" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
<!-- 100 MB in bytes -->
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
</location>
I think, in finally that this is the best solution, easy and simple:
img {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
#!/usr/bin/python
import subprocess
p = subprocess.Popen(["tail", "-n 3", "passlist"], stdout=subprocess.PIPE)
output, err = p.communicate()
print output
This Method Worked for me
import requests
response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.url)
print(response.request.body)
print(response.request.headers)
Response
objects have a .request
property which is the original PreparedRequest
object that was sent.
In my case, this was caused by a subclass name being used in the very next line as a variable name with a different type:
var binGlow: pipGlow = pipGlow(style: "Bin")
var pipGlow: PipGlowSprite = PipGlowSprite()
Notice that in line 1, pipGlow is the name of the subclass (of SKShapeNode), but in line two, I was using pipGlow as a variable name. This was not only bad coding style, but apparently an outright no-no as well! Once I change the second line to:
var binGlow: pipGlow = pipGlow(style: "Bin")
var pipGlowSprite: PipGlowSprite = PipGlowSprite()
I no longer received the error. I hope this helps someone!
If anyone is interested in a no-brainer solution for drawing an image in a custom rect in a context:
func drawImage(image: UIImage, inRect rect: CGRect, context: CGContext!) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
CGContextTranslateCTM(context, 0, ty)
CGContextScaleCTM(context, 1.0, -1.0)
//draw image
let rect__y_zero = CGRect(origin: CGPoint(x: rect.origin.x, y:0), size: rect.size)
CGContextDrawImage(context, rect__y_zero, image.CGImage)
//flip back
CGContextScaleCTM(context, 1.0, -1.0)
CGContextTranslateCTM(context, 0, -ty)
}
The image will be scaled to fill the rect.
It looks like data
not contains what you think it contains - check it.
let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};_x000D_
_x000D_
console.log( data["jobtitel"] );_x000D_
console.log( data.jobtitel );
_x000D_
First, install humanfriendly package by opening Command Prompt (CMD) as administrator and type there -
pip install humanfriendly
Code:
from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))
Output:
The most simple answer only using CSS :D !!!
table {_x000D_
/* Not required only for visualizing */_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table thead tr th {_x000D_
/* you could also change td instead th depending your html code */_x000D_
background-color: green;_x000D_
position: sticky;_x000D_
z-index: 100;_x000D_
top: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
/* Not required only for visualizing */_x000D_
padding: 1em;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Col1</th>_x000D_
<th>Col2</th>_x000D_
<th>Col3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
<td>data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>david</td>_x000D_
<td>castro</td>_x000D_
<td>rocks!</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This one is a more generic version of the ideas mentioned above... It simply checks whether there is any value in the model, and if not, it sets the value to the model.
JS:
function defaultValueDirective() {
return {
restrict: 'A',
controller: [
'$scope', '$attrs', '$parse',
function ($scope, $attrs, $parse) {
var getter = $parse($attrs.ngModel);
var setter = getter.assign;
var value = getter();
if (value === undefined || value === null) {
var defaultValueGetter = $parse($attrs.defaultValue);
setter($scope, defaultValueGetter());
}
}
]
}
}
HTML (usage example):
<select class="form-control"
ng-options="v for (i, v) in compressionMethods"
ng-model="action.parameters.Method"
default-value="'LZMA2'"></select>
Here is my answer.
public static int mode(int[] arr) {
int max = 0;
int maxFreq = 0;
Arrays.sort(arr);
max = arr[arr.length-1];
int[] count = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > maxFreq) {
maxFreq = count[i];
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] == maxFreq) {
return i;
}
}
return -1;
}
This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
If you cannot find the .exe file, rebuild your solution and in your "Output" from Visual Studio the path to the file will be shown.
Truncate table
is faster than delete * from XXX
. Delete
is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.
Usually this problem is caused by wrong user and group permissions on your Git servers file-system. The git repository has to be owned by the user and also his group.
Example:
If your user is called "git", his group "gitgroup", and the location of the Git repo is: [email protected]:path/to/repo.git
then do a:
sudo chown -R git:gitgroup path/to/repo.git/
This fixed the git insufficient permission error for me.
Here is a somewhat kludgy way to do it that works with GO-batches, by using a "global" variable.
if object_id('tempdb..#vars') is not null
begin
drop table #vars
end
create table #vars (continueScript bit)
set nocount on
insert #vars values (1)
set nocount off
-- Start of first batch
if ((select continueScript from #vars)=1) begin
print '1'
-- Conditionally terminate entire script
if (1=1) begin
set nocount on
update #vars set continueScript=0
set nocount off
return
end
end
go
-- Start of second batch
if ((select continueScript from #vars)=1) begin
print '2'
end
go
And here is the same idea used with a transaction and a try/catch block for each GO-batch. You can try to change the various conditions and/or let it generate an error (divide by 0, see comments) to test how it behaves:
if object_id('tempdb..#vars') is not null
begin
drop table #vars
end
create table #vars (continueScript bit)
set nocount on
insert #vars values (1)
set nocount off
begin transaction;
-- Batch 1 starts here
if ((select continueScript from #vars)=1) begin
begin try
print 'batch 1 starts'
if (1=0) begin
print 'Script is terminating because of special condition 1.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
print 'batch 1 in the middle of its progress'
if (1=0) begin
print 'Script is terminating because of special condition 2.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
set nocount on
-- use 1/0 to generate an exception here
select 1/1 as test
set nocount off
end try
begin catch
set nocount on
select
error_number() as errornumber
,error_severity() as errorseverity
,error_state() as errorstate
,error_procedure() as errorprocedure
,error_line() as errorline
,error_message() as errormessage;
print 'Script is terminating because of error.'
update #vars set continueScript=0
set nocount off
return
end catch;
end
go
-- Batch 2 starts here
if ((select continueScript from #vars)=1) begin
begin try
print 'batch 2 starts'
if (1=0) begin
print 'Script is terminating because of special condition 1.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
print 'batch 2 in the middle of its progress'
if (1=0) begin
print 'Script is terminating because of special condition 2.'
set nocount on
update #vars set continueScript=0
set nocount off
return
end
set nocount on
-- use 1/0 to generate an exception here
select 1/1 as test
set nocount off
end try
begin catch
set nocount on
select
error_number() as errornumber
,error_severity() as errorseverity
,error_state() as errorstate
,error_procedure() as errorprocedure
,error_line() as errorline
,error_message() as errormessage;
print 'Script is terminating because of error.'
update #vars set continueScript=0
set nocount off
return
end catch;
end
go
if @@trancount > 0 begin
if ((select continueScript from #vars)=1) begin
commit transaction
print 'transaction committed'
end else begin
rollback transaction;
print 'transaction rolled back'
end
end
Solutions listed did not exactly work for me. The closest was Chief Wiggum - I wanted to add a comment on his answer but lack the reputation to do so. So I post as separate answer:
=MIN(IF(A1:E1>0;A1:E1))
Then instead of pressing ENTER, press CTRL+SHIFT+ENTER and watch Excel add {
and }
to respectively the beginning and the end of the formula (to activate the formula on array).
The comma "," and "If" statement as proposed by Chief Wiggum did not work on Excel Home and Student 2013. Need a semicolon ";" as well as full cap "IF" did the trick. Small syntax difference but took me 1.5 hour to figure out why I was getting an error and #VALUE.
Very good question indeed. I just tried for myself.
public class IsInstanceOfTest {
public static void main(final String[] args) {
String s;
s = "";
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
s = null;
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
}
}
Prints
true
true
false
false
JLS / 15.20.2. Type Comparison Operator instanceof
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
API / Class#isInstance(Object)
If this
Class
object represents an interface, this method returnstrue
if the class or any superclass of the specifiedObject
argument implements this interface; it returnsfalse
otherwise. If thisClass
object represents a primitive type, this method returnsfalse
.
Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.
In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.
//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;
always @(posedge sysclk) //Procedural context starts here
begin
for (c = 0; c < ROWBITS; c = c + 1) begin: test
temp[c] <= 1'b0; //Still a genvar
end
end
result = db.engine.execute(text("<sql here>"))
executes the <sql here>
but doesn't commit it unless you're on autocommit
mode. So, inserts and updates wouldn't reflect in the database.
To commit after the changes, do
result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
open Credential Manager -> look for your GIT devops profile -> click on it -> edit -> add user and password generated in DevOps and save.
As a programming noob, I found a bunch of the above answers overly complex, especially if the goal is to have a simple function that you can pass various yes/no questions to, forcing the user to select yes or no. After scouring this page and several others, and borrowing all of the various good ideas, I ended up with the following:
def yes_no(question_to_be_answered):
while True:
choice = input(question_to_be_answered).lower()
if choice[:1] == 'y':
return True
elif choice[:1] == 'n':
return False
else:
print("Please respond with 'Yes' or 'No'\n")
#See it in Practice below
musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
print('and getting caught in the rain')
elif musical_taste == False:
print('You clearly have no taste in music')
Here is a link please use this to make the div in the center if position is absolute.
HTML:
<div class="bar"></div>
CSS:
.bar{
width:200px;
border-top:4px solid red;
position:absolute;
margin-left:auto;
margin-right:auto;
left:0;
right:0;
}
If you need a custom title for each option, ng-options
is not applicable. Instead use ng-repeat
with options:
<select ng-model="myVariable">
<option ng-repeat="item in items"
value="{{item.ID}}"
title="Custom title: {{item.Title}} [{{item.ID}}]">
{{item.Title}}
</option>
</select>
try the class-name
Query query = session.createQuery("from Employee");
instead of the table name
Query query = session.createQuery("from EMPLOYEE");
Use the DATE function:
SELECT DATE(orders.date_purchased) AS date
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path.The standard library function urllib.parse.urlsplit() is all you need. Here is an example for Python3:
>>> import urllib.parse
>>> o = urllib.parse.urlsplit('https://user:[email protected]:8080/dir/page.html?q1=test&q2=a2#anchor1')
>>> o.scheme
'https'
>>> o.netloc
'user:[email protected]:8080'
>>> o.hostname
'www.example.com'
>>> o.port
8080
>>> o.path
'/dir/page.html'
>>> o.query
'q1=test&q2=a2'
>>> o.fragment
'anchor1'
>>> o.username
'user'
>>> o.password
'pass'
I suggest use the common way of import.
First I will explain the way it called "relative import" maybe this way cause of some error
Second I will explain the common way of import.
FIRST:
In go version >= 1.12 there is some new tips about import file and somethings changed.
1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"
2- You have to use uppercase when you want to import a file!
3- Use Uppercase for variables, structures and functions that you want to import in another files
Notice: There is no way to import the main.go in another file.
file directory is:
root
|_____main.go
|_____model
|_____example.go
this is a example.go:
package model
import (
"time"
)
var StartTime = time.Now()
and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase
package main
import (
Mod "./model"
"fmt"
)
func main() {
fmt.Println(Mod.StartTime)
}
NOTE!!!
NOTE: I don't recommend this this type of import!
SECOND:
(normal import)
the better way import file is:
your structure should be like this:
root
|_____github.com
|_________Your-account-name-in-github
| |__________Your-project-name
| |________main.go
| |________handlers
| |________models
|
|_________gorilla
|__________sessions
and this is a example:
package main
import (
"github.com/gorilla/sessions"
)
func main(){
//you can use sessions here
}
so you can import "github.com/gorilla/sessions" in every where that you want...just import it.
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is One-Jar, which uses a special classloader to allow the nesting of jars. The second is UberJar, (or Shade), which explodes the included libraries and puts all the classes in the top-level jar.
I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).
This is how i did it:
$string = "I appreciate your service & idea to provide the branded toys at a fair rent price. This is really a wonderful to watch the kid not just playing with variety of toys but learning faster compare to the other kids who are not using the BooksandBeyond service. We wish you all the best";
print_r(substr($string, 0, strpos(wordwrap($string, 250), "\n")));
If you try set a value in datetime-local
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21
Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin:
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!
<meta property="article:author" content="https://www.facebook.com/mpatnode76">
But Pinterest wants to see something like this:
<meta property="article:author" content="Mike Patnode">
We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.
Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/
First check what your php error reports tells you. And define application wide root at the biginning of your index.php
define ('APPROOT', realpath(dirname(__FILE__)));
and then use it to include you files
include(APPROOT.'templates/header.php');
and so on... And to you have you .htaccess rewrite rule?
From the Vimeo Simple API docs:
Making a Video Request
To get data about a specific video, use the following url:
http://vimeo.com/api/v2/video/video_id.output
video_id The ID of the video you want information for.
output Specify the output type. We currently offer JSON, PHP, and XML formats.
So getting this URL http://vimeo.com/api/v2/video/6271487.xml
<videos>
<video>
[skipped]
<thumbnail_small>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_100.jpg</thumbnail_small>
<thumbnail_medium>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_200.jpg</thumbnail_medium>
<thumbnail_large>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_640.jpg</thumbnail_large>
[skipped]
</videos>
Parse this for every video to get the thumbnail
Here's approximate code in PHP
<?php
$imgid = 6271487;
$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid.php"));
echo $hash[0]['thumbnail_medium'];
In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:
config.Save(ConfigurationSaveMode.Modified);
Without this, the new value was still being written to the config file but the old value was retrieved when debugging.
We should make everything easier for everyone because you can simply combine JS to PHP Combining PHP and JS is pretty easy.
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = $house_number; document.forms[0].submit();</script>";
Or a somewhat safer way
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = " . $house_number . "; document.forms[0].submit();</script>";
Try
sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"
I got this under cygwin:
$ (echo "asdf"; \
echo "1234"; \
echo "asdf1234adsf1234asdf"; \
echo "1m2m3m4m5m6m7m8m9m0m1m2m3m4m5m6m7m8m9") | \
sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"
1234
1234 1234
1 2 3 4 5 6 7 8 9
$
You should be using a class
to achieve what you want:
css:
#topbar { width: 100%; height: 40px; background-color: #000; }
#topbar.hide { height: 10px; }
javascript:
$(document).ready(function(){
$("#topbar").click(function(){
if($(this).hasClass('hide')) {
$(this).animate({height:40},200).removeClass('hide');
} else {
$(this).animate({height:10},200).addClass('hide');
}
});
});
My solution for Ubuntu Linux:
-vm
/home/daniel/Downloads/jdk1.6.0_17/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.2.R36x_v20101019_1345
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.
However, you can convert strings to numbers like this:
pd.Series(['123', '42']).astype(float)
instead of float(series)
Option 3 is impossible - you'd get the rendered output of the .php file, exactly as you would if you hit that url in your browser. If you got raw PHP code instead (as you'd like), then ALL of your site's source code would be exposed, which is generally not a good thing.
Option 2 doesn't make much sense - you'd be hiding the variable in a function, and be subject to PHP's variable scope. You'ld also have to have $var = passvariable()
somewhere to get that 'inside' variable to the 'outside', and you're back to square one.
option 1 is the most practical. include()
will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP's parsing semantics, these two are identical:
$x = 'foo';
include('bar.php');
and
$x = 'foo';
// contents of bar.php pasted here
The reindent script did not work for me, due to some missing module. Anyway, I found this sed
command which does the job perfect for me:
sed -r 's/^([ ]*)([^ ])/\1\1\2/' file.py
You can add a Rectangle
patch to the matplotlib Axes.
For example (using the image from the tutorial here):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
im = Image.open('stinkbug.png')
# Create figure and axes
fig, ax = plt.subplots()
# Display the image
ax.imshow(im)
# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
It is a bit of hack but will do the task.
Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function
As some guys already mentioned here the problem is with the exception swallowing in case you just call e.printStackTrace()
in the catch
block. It won't stop the thread execution and will continue after the try block as in normal condition.
Instead of that you need either try to recover from the exception (in case it is recoverable), or to throw RuntimeException
, or to bubble the exception to the caller in order to avoid silent crashes (for example, due to improper logger configuration).
In Windows 7 I didn't have to restart, simply run command prompt in administrator mode.
Easy
if (lblExample.ForeColor != System.Drawing.Color.Red)
{
lblExample.ForeColor = System.Drawing.Color.Red;
}
else
{
lblExample.ForeColor = new System.Drawing.Color();
}
To install wheel packages in python 2.7x:
Install python 2.7x (i would recommend python 2.78) - download the appropriate python binary for your version of windows . You can download python 2.78 at this site https://www.python.org/download/releases/2.7.8/ -I would recommend installing the graphical Tk module, and including python 2.78 in the windows path (environment variables) during installation.
Install get-pip.py and setuptools Download the installer at https://bootstrap.pypa.io/get-pip.py Double click the above file to run it. It will install pip and setuptools [or update them, if you have an earlier version of either]
-Double click the above file and wait - it will open a black window and print will scroll across the screen as it downloads and installs [or updates] pip and setuptools --->when it finishes the window will close.
A-type cd c:\python27\scripts [or cd \scripts ]
B-type pip install -u Eg to install pyside, type pip install -u pyside
Wait - it will state 'downloading PySide or -->it will download and install the appropriate version of the python package [the one that corresponds to your version of python and windows.]
Note - if you have downloaded the .whl file and saved it locally on your hard drive, type in
pip install --no-index --find-links=localpathtowheelfile packagename
**to install a previously downloaded wheel package you need to type in the following command pip install --no-index --find-links=localpathtowheelfile packagename
When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),input.split())]
print (a, b, c, d)
Note that for more complex format strings, you do need to use regular expressions:
import re
input = '1:3.0 false,hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())]
print (a, b, c, d)
Note also that you need conversion functions for all types you want to convert. For example, above I used something like:
strtobool = lambda s: {'true': True, 'false': False}[s]
A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.
You might only want specific properties, so this allows you to only load those and not additional unneccesary properties
In Linux command shell, I did:
chmod 777 <db_folder>
Where contains the database file.
It works. Now I can access my database and make insert queries.
I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :
You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.
Above tutorial also explains how to create app in facebook developer console through video.
add below in build.gradle(Module:app)
file:
repositories {
mavenCentral()
}
and
compile 'com.facebook.android:facebook-android-sdk:4.10.0'
now add below in AndroidManifest.xml file :
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="your app id from facebook developer console"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
add following in activity_main.xml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.demonuts.fblogin.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/text"/>
<com.facebook.login.widget.LoginButton
android:id="@+id/btnfb"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
And in last add below in MainActivity.java file :
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private TextView tvdetails;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private LoginButton loginButton;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
// Application code
try {
Log.d("tttttt",object.getString("id"));
String birthday="";
if(object.has("birthday")){
birthday = object.getString("birthday"); // 01/31/1980 format
}
String fnm = object.getString("first_name");
String lnm = object.getString("last_name");
String mail = object.getString("email");
String gender = object.getString("gender");
String fid = object.getString("id");
tvdetails.setText(fnm+" "+lnm+" \n"+mail+" \n"+gender+" \n"+fid+" \n"+birthday);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
tvdetails = (TextView) findViewById(R.id.text);
loginButton = (LoginButton) findViewById(R.id.btnfb);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
loginButton.registerCallback(callbackManager, callback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
@Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
}
Here's another two examples.
To output the day, month, and year, you can use:
select STR_TO_DATE('14/02/2015', '%d/%m/%Y');
Which produces:
2015-02-14
To also output the time, you can use:
select STR_TO_DATE('14/02/2017 23:38:12', '%d/%m/%Y %T');
Which produces:
2017-02-14 23:38:12
This may not be a solution to the question, but to illustrate examples:
import pandas as pd
df = pd.DataFrame({
'A': [1,1,3,4],
'B': [2,2,5,6],
'C': [3,4,7,6],
})
print(df)
df.duplicated(keep=False)
df.duplicated(['A','B'], keep=False)
The outputs:
A B C
0 1 2 3
1 1 2 4
2 3 5 7
3 4 6 6
0 False
1 False
2 False
3 False
dtype: bool
0 True
1 True
2 False
3 False
dtype: bool
Use '_blank'. It will not only open the link in a new tab but the state of the original webpage will also remain unaffected.
As far as I know, the dual
table in Oracle is a special table with just one row. So, this would suffice:
SELECT user
FROM dual
You can't insert comments inside xml tags.
Bad
<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib">
Good
<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib">
<!-- Cool comment -->
The way you have synchronized is correct. But there is a catch
However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.
a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.
b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.
c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.
Note for Windows users, the jars should be separated by ;
and not :
.
for example:
javac -cp external_libs\lib1.jar;other\lib2.jar;
If the yml
is called docker-compose.yml
it can be launched with a simple $ docker-compose up
. The corresponding attachment of a terminal can be simply (consider that the yml
has specified a service called myservice
):
$ docker-compose exec myservice sh
However, if you are using a different yml
file name, such as docker-compose-mycompose.yml
, it should be launched using $ docker-compose -f docker-compose-mycompose.yml up
. To attach an interactive terminal you have to specify the yml
file too, just like:
$ docker-compose -f docker-compose-mycompose.yml exec myservice sh
Here's another link demonstrating how const isn't version safe, or relevant for reference types.
Summary:
Based on the instructions at the link below, do the following.
In VBA insert a new module and paste in this code:
Public Function UserName()
UserName = Environ$("UserName")
End Function
Call the function using the formula:
=Username()
Based on instructions at:
as this example you can change ip and port this works with me
php artisan serve --host=0.0.0.0 --port=8000
See the crypto.createHash()
function and the associated hash.update()
and hash.digest()
functions:
var crypto = require('crypto')
var shasum = crypto.createHash('sha1')
shasum.update('foo')
shasum.digest('hex') // => "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
From this post, try this javascript:
function removeRow(id) {
var tr = document.getElementById(id);
if (tr) {
if (tr.nodeName == 'TR') {
var tbl = tr; // Look up the hierarchy for TABLE
while (tbl != document && tbl.nodeName != 'TABLE') {
tbl = tbl.parentNode;
}
if (tbl && tbl.nodeName == 'TABLE') {
while (tr.hasChildNodes()) {
tr.removeChild( tr.lastChild );
}
tr.parentNode.removeChild( tr );
}
} else {
alert( 'Specified document element is not a TR. id=' + id );
}
} else {
alert( 'Specified document element is not found. id=' + id );
}
}
I tried this javascript in a test page and it worked for me in Firefox.
Conda needs to know where to find you SSL certificate store.
conda config --set ssl_verify <pathToYourFile>.crt
No need to disable SSL verification.
This command add a line to your $HOME/.condarc
file or %USERPROFILE%\.condarc
file on Windows that looks like:
ssl_verify: <pathToYourFile>.crt
If you leave your organization's network, you can just comment out that line in .condarc
with a #
and uncomment when you return.
If it still doesn't work, make sure that you are using the latest version of curl
, checking both the conda-forge
and anaconda
channels.
They use regular CSS.
Just use your regular font family like this:
font-family: 'Open Sans', sans-serif;
Now you decide what "weight" the font should have by adding
for semi-bold
font-weight:600;
for bold (700)
font-weight:bold;
for extra bold (800)
font-weight:800;
Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.
Pretty smart :-)
Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.
For example the following link will include both weights 400 and 700:
<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
I've always tested to find the MAX string length of an encrypted string and set that as the character length of a VARCHAR type. Depending on how many records you're going to have, it could really help the database size.
Lets define px_ratio as below:
px ratio = ratio of physical pixel to css px.
if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.
but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.
but
resizing: trigger windows.resize event --> doesnāt change px_ratio
//for zoom detection
px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
$(window).resize(function(){isZooming();});
function isZooming(){
var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
if(newPx_ratio != px_ratio){
px_ratio = newPx_ratio;
console.log("zooming");
return true;
}else{
console.log("just resizing");
return false;
}
}
The key point is difference between CSS PX and Physical Pixel.
https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e
select * from (select name, ID from Empoyee) Visits
pivot(sum(ID) for name
in ([Emp1],
[Emp2],
[Emp3]
) ) as pivottable;
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.
To append a name/value name/value pair to a Headers object (headers), run these steps:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headersās guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
To fill a Headers object headers with a given object object, run these steps:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
The delete(name) method steps are:
- If name is not a name, then throw a TypeError.
- If thisās guard is "immutable", then throw a TypeError.
The get(name) method steps are:
- If name is not a name, then throw a TypeError.
- Return the result of getting name from thisās header list.
The has(name) method steps are:
- If name is not a name, then throw a TypeError.
The set(name, value) method steps are:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If thisās guard is "immutable", then throw a TypeError.
To extract a body and a
Content-Type
value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.
In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set requestās referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If thisās requestās mode is "no-cors", then:
1. If thisās requestās method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and requestās method isGET
orHEAD
, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If thisās requestās mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...
The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.
In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
If you are using a virtualenvwrapper
, you can just locate it using which virtualenvwrapper.sh
, then open it using vim
or any other editor then change the following
# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi
Change the line VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
to VIRTUALENVWRAPPER_PYTHON="$(command \which python3)"
.
service.service.ts
--------------------------------------------------------------
import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
private url="some URL";
constructor(private http:Http) { }
//getData() is a method to fetch the data from web api or json file
getData(){
getData(){
return this.http.get(this.url)
.map((response:Response)=>response.json())
}
}
}
display.component.ts
--------------------------------------------
//In this component get the data using suscribe() and store it in local object as dataObject and display the data in display.component.html like {{dataObject .propertyName}}.
import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
dataObject :any={};
constructor(private service:ServiceService) { }
ngOnInit() {
this.service.getData()
.subscribe(resData=>this.dataObject =resData)
}
}
Delegate
is just the base class so you can't use it like that. You could do something like this though:
public void DoRequest(string request, Action<string> callback)
{
// do stuff....
callback("asdf");
}
This is what worked for me when I had this error:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>
You can use $.each()
Suppose your xml
is
<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>
In your Ajax
success
success: function (xml) {
$(xml).find('Cloudtags').each(function(){// your outer tag of xml
var id = $(this).find("id").text(); //
});
}
For your case
success: function (xml) {
$(xml).find('person').each(function(){// your outer tag of xml
var name = $(this).find("name").text(); //
var age = $(this).find("age").text();
});
}
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
This is the code required if you're using only JavaScript and not jQuery
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
I'm the author of Aba Search and Replace. Just like PowerGREP, it supports regular expressions, saving patterns for further use, undo for replacements, preview with syntax highlight for HTML/CSS/JS/PHP, different encodings, including UTF-8 and UTF-16.
In comparison with PowerGREP, the GUI is less cluttered. Aba instantly starts searching as you are typing the pattern (incremental search), so you can experiment with regular expressions and immediately see the results.
You are welcomed to try my tool; I will be happy to answer any questions.
Shorted variant based on dmckee's answer:
ls -t | head -1
I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup
Edit: details you asked for. in Eclipse 3.4
Run->Run Configurations...
if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner
on the right, "Main" tab make sure the project and the class are the right ones
select the "Arguments" tab on the right.
this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
-Xmx2048m
I think that 1024m should more than enough for what you need though!
Click Apply, then Click Run
Should work :)
Your understanding is incorrect, in cases like these always consult the JavaDoc.
assertFalse
public static void assertFalse(java.lang.String message, boolean condition)
Asserts that a condition is false. If it isn't it throws an AssertionError with the given message.
Parameters:
message
- the identifying message for the AssertionError (null okay)condition
- condition to be checked
For a 2d numpy
array, simply use imshow()
may help you:
import matplotlib.pyplot as plt
import numpy as np
def heatmap2d(arr: np.ndarray):
plt.imshow(arr, cmap='viridis')
plt.colorbar()
plt.show()
test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)
This code produces a continuous heatmap.
You can choose another built-in colormap
from here.
If bind-address is not present in your configuration file and mysql is hosted on AWS instance, please check your security group. In ideal conditions, the inbound rules should accept all connection from port 3306 and outbound rule should respond back to all valid IPs.
I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):
// Create delegates for the different return types needed.
private delegate void VoidDelegate();
private delegate Boolean ReturnBooleanDelegate();
private delegate Hashtable ReturnHashtableDelegate();
// Now use the delegates and the delegate() keyword to create
// an anonymous method as required
// Here a case where there's no value returned:
public void SetTitle(string title)
{
myWindow.Invoke(new VoidDelegate(delegate()
{
myWindow.Text = title;
}));
}
// Here's an example of a value being returned
public Hashtable CurrentlyLoadedDocs()
{
return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
{
return myWindow.CurrentlyLoadedDocs;
}));
}
It's not possible using the framework APIs. It's at the discretion of the operating system (Android) to decide when a process should be removed or remain in memory. This is for efficiency reasons: if the user decides to relaunch the app, then it's already there without it having to be loaded into memory.
So no, it's not only discouraged, it's impossible to do so.
This answer is useful in the case you no longer have SSH access to the existing server (i.e. you lost your private key).
If you still have SSH access, please use one of the answers below.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#replacing-lost-key-pair
Here is what I did, thanks to Eric Hammond's blog post:
/dev/xvda1
volume (let's call it volume A) - see here/dev/xvdf
(or /dev/sdf
)/mnt/tmp
$ sudo mkdir /mnt/tmp; sudo mount /dev/xvdf1 /mnt/tmp
~/.ssh/authorized_keys
to /mnt/tmp/home/ubuntu/.ssh/authorized_keys
/dev/xvda
.pem
fileThat's it.
You've another instance of Tomcat already running. You can confirm this by going to http://localhost:8080 in your webbrowser and check if you get the Tomcat default home page or a Tomcat-specific 404 error page. Both are equally valid evidence that Tomcat runs fine; if it didn't, then you would have gotten a browser specific HTTP connection timeout error message.
You need to shutdown it. Go to /bin subfolder of the Tomcat installation folder and execute the shutdown.bat (Windows) or shutdown.sh (Unix) script.
check this answer for more information.
(Also works for 7.1.1)
Like this:
And then delete it here:
Hope that helps!
UPDATE: This is no longer necessary with Python3.4. It installs pip3 as part of the stock install.
I ended up posting this same question on the python mailing list, and got the following answer:
# download and install setuptools
curl -O https://bootstrap.pypa.io/ez_setup.py
python3 ez_setup.py
# download and install pip
curl -O https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
Which solved my question perfectly. After adding the following for my own:
cd /usr/local/bin
ln -s ../../../Library/Frameworks/Python.framework/Versions/3.3/bin/pip pip
So that I could run pip directly, I was able to:
# use pip to install
pip install pyserial
or:
# Don't want it?
pip uninstall pyserial
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
You might like this little item... It pulls the list and asks for confirmation of each item before finally deleting all selections...
git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "remove branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done`
Use -D to force deletions (like usual).
For readability, here is that broken up line by line...
git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do
read -p "remove branch: $line (y/N)?" answer </dev/tty;
case "$answer" in y|Y) echo "$line";;
esac;
done`
here is the xargs approach...
git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do
read -p "remove branch: $line (y/N)?" answer </dev/tty;
case "$answer" in
y|Y) echo "$line";;
esac;
done | xargs git branch -D
finally, I like to have this in my .bashrc
alias gitselect='git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "select branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done'
That way I can just say
gitSelect | xargs git branch -D.
You can use $("#drpList").val();
Have appended the html in componentDidMount using jQuery append. This should solve the problem.
var MyComponent = React.createClass({
render: function() {
return (
<div>
</div>
);
},
componentDidMount() {
$(ReactDOM.findDOMNode(this)).append(this.props.text);
}
});
function numinstr(p_source in varchar2,p_token in varchar2)
return pls_integer
is
v_occurrence pls_integer := 1;
v_start pls_integer := 1;
v_loc pls_integer;
begin
v_loc:=instr(p_source, p_token, 1, 1);
while v_loc > 0 loop
v_occurrence := v_occurrence+1;
v_start:=v_loc+1;
v_loc:=instr(p_source, p_token, v_start, 1);
end loop;
return v_occurrence-1;
end numinstr;
--
--
--
--
function get_split_field(p_source in varchar2,p_delim in varchar2,nth pls_integer)
return varchar2
is
v_num_delims pls_integer;
first_pos pls_integer;
final_pos pls_integer;
len_delim pls_integer := length(p_delim);
ret_len pls_integer;
begin
v_num_delims := numinstr(p_source,p_delim);
if nth < 1 or nth > v_num_delims+1 then
return null;
else
if nth = 1 then
first_pos := 1;
else
first_pos := instr(p_source, p_delim, 1, nth-1) + len_delim;
end if;
if nth > v_num_delims then
final_pos := length(p_source);
else
final_pos := instr(p_source, p_delim, 1, nth) - 1;
end if;
ret_len := (final_pos - first_pos) + 1;
return substr(p_source, first_pos, ret_len);
end if;
end get_split_field;
I suppose that Chrome's behavior is more consistent with the CSS specification (though it's less intuitive). According to Flexbox specification, the default stretch
value of align-self
property changes only the used value of the element's "cross size property" (height
, in this case). And, as I understand the CSSĀ 2.1 specification, the percentage heights are calculated from the specified value of the parent's height
, not its used value. The specified value of the parent's height
isn't affected by any flex properties and is still auto
.
Setting an explicit height: 100%
makes it formally possible to calculate the percentage height of the child, just like setting height: 100%
to html
makes it possible to calculate the percentage height of body
in CSSĀ 2.1.
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1; // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.
INSERT INTO viewname (Column name) values (value);
With Mercurial you do a
$ hg grep "search for this" [file...]
There are other options that narrow down the range of revisions that are searched.
Other answers work, but
To get the full/default price:
$product->get_price_html();
With Ajax, for me worked:
Html:
<div id='anID'>
<form name="nameOfForm">
<p><b>Your headline</b></p>
<input type='radio' name='nameOfRadio' value='seed'
<?php if ($interviewStage == 'seed') {echo" checked ";}?>
onchange='funcInterviewStage()'><label>Your label</label><br>
</form>
</div>
Javascript:
function funcInterviewStage() {
var dis = document.nameOfForm.nameOfRadio.value;
//Auswahltafel anzeigen
if (dis == "") {
document.getElementById("anID").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("anID").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/includes/[name].php?id="+dis,true);
xmlhttp.send();
}
}
And php:
//// Get Value
$id = mysqli_real_escape_string($db, $_GET['id']);
//// Insert to database
$insert = mysqli_query($db, "UPDATE [TABLE] SET [column] = '$id' WHERE [...]");
//// Show radio buttons again
$mysqliAbfrage = mysqli_query($db, "SELECT [column] FROM [Table] WHERE [...]");
while ($row = mysqli_fetch_object($mysqliAbfrage)) {
...
}
echo"
<form name='nameOfForm'>
<p><b>Your headline</b></p>
<input type='radio' name='nameOfRadio' value='seed'"; if ($interviewStage == 'seed') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Yourr Label</label><br>
<input type='radio' name='nameOfRadio' value='startup'"; if ($interviewStage == 'startup') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Your label</label><br>
</form> ";
You just need to set
spring.jpa.show-sql=true
in application.properties
for example you may reffer this https://github.com/007anwar/ConfigServerRepo/blob/master/application.yaml
You can set height and width like this also:
viewinstance.setLayoutParams(new LayoutParams(width, height));
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
Its .net Version mismatch of the dll so try changing to from in app.config or web.config. Generally have a higher Framework than lower because when we add system's dll to the lower version built .net application so it won't work therefore just change to the higher version
Both are effectively the same class (you can look at the disassembly). HashTable was created first before .Net had generics. Dictionary, however is a generic class and gives you strong typing benefits. I would never use HashTable since Dictionary costs you nothing to use.
I've previously used Ultimate++ IDE and it's rather good.
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
Since I cannot comment yet I copied the answer from above, it really helped me out. But I changed it to work with cookies instead of #id so I wanted to share the alterations. This makes it possible to store the active tab longer than just one refresh (e.g. multiple redirect) or when the id is already used and you don't want to implement koppors split method.
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
<script>
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
$.cookie('activeTab', id);
});
// on load of the page: switch to the currently selected tab
var hash = $.cookie('activeTab');
if (hash != null) {
$('#myTab a[href="#' + hash + '"]').tab('show');
}
</script>
This regex pattern will match an empty string:
^$
And this will match (crudely) an email or an empty string:
(^$|^.*@.*\..*$)
ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
content: "\2022";
font-family: FontAwesome;
margin-right: 10px;
display: inline;
vertical-align: middle;
font-size: 1.6em;
font-weight: normal;
}
Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.
Visual for you - http://i.imgur.com/d533SQD.png
Use View.getLocationOnScreen()
and/or getLocationInWindow()
.
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
Are you trying to do logical equality utilizing the object's .equals method? You can do this utilizing the argThat matcher that is included in Mockito
import static org.mockito.Matchers.argThat
Next you can implement your own argument matcher that will defer to each objects .equals method
private class ObjectEqualityArgumentMatcher<T> extends ArgumentMatcher<T> {
T thisObject;
public ObjectEqualityArgumentMatcher(T thisObject) {
this.thisObject = thisObject;
}
@Override
public boolean matches(Object argument) {
return thisObject.equals(argument);
}
}
Now using your code you can update it to read...
Object obj = getObject();
Mockeable mock= Mockito.mock(Mockeable.class);
Mockito.when(mock.mymethod(obj)).thenReturn(null);
Testeable obj = new Testeable();
obj.setMockeable(mock);
command.runtestmethod();
verify(mock).mymethod(argThat(new ObjectEqualityArgumentMatcher<Object>(obj)));
If you are just going for EXACT equality (same object in memory), just do
verify(mock).mymethod(obj);
This will verify it was called once.
The most problems appear when you want to add new host to dynamic inventory (via add_host module) in playbook. I don't want to disable fingerprint host checking permanently so solutions like disabling it in a global config file are not ok for me. Exporting var like ANSIBLE_HOST_KEY_CHECKING
before running playbook is another thing to do before running that need to be remembered.
It's better to add local config file in the same dir where playbook is. Create file named ansible.cfg
and paste following text:
[defaults]
host_key_checking = False
No need to remember to add something in env vars or add to ansible-playbook
options. It's easy to put this file to ansible git repo.
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
The following code worked for me very well.
SELECT
D.name As DbName,
F.Name AS FullDbName,
CASE WHEN F.type_desc='ROWS' THEN 'mdf' ELSE 'ldf' END AS FileType,
F.physical_name AS PhysicalFile,
CONVERT(DATE,D.create_date) AS CreationDate,
F.state_desc AS OnlineStatus,
CAST((F.size*8)/1024 AS VARCHAR(26)) + ' MB' AS FileSize_MB,
CAST(F.size*8 AS VARCHAR(32)) + ' Bytes' AS FileSize_Bytes,
CAST(CAST(ROUND((F.size*8)/(1024.0*1024.0),0) AS INT) AS VARCHAR(32)) + ' GB' AS FileSize_GB
FROM
sys.master_files F
INNER JOIN sys.databases D ON D.database_id = F.database_id
ORDER BY
D.name
Dim row As DataRow
For Each row In dtDataTable.Rows
Dim strDetail As String
strDetail = row("Detail")
Console.WriteLine("Processing Detail {0}", strDetail)
Next row
Every function inside a class, and every class variable must take the self argument as pointed.
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
def sum(self,a,b):
return a+b
print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok
If class variables are involved:
class mystuff:
def setVariables(self,a,b):
self.x = a
self.y = b
return a+b
def mult(self):
return x * y # This line will raise an error
def sum(self):
return self.x + self.y
print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
print mystuff.mult() # should raise error
print mystuff.sum() # should be ok
Use these two commands (for Java 8):
sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment
public static int getDifferenceIndays(long timestamp1, long timestamp2) {
final int SECONDS = 60;
final int MINUTES = 60;
final int HOURS = 24;
final int MILLIES = 1000;
long temp;
if (timestamp1 < timestamp2) {
temp = timestamp1;
timestamp1 = timestamp2;
timestamp2 = temp;
}
Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
endDate.setTimeInMillis(timestamp1);
startDate.setTimeInMillis(timestamp2);
if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
int day1 = endDate.get(Calendar.DAY_OF_MONTH);
int day2 = startDate.get(Calendar.DAY_OF_MONTH);
if (day1 == day2) {
return 0;
} else {
return 1;
}
}
int diffDays = 0;
startDate.add(Calendar.DAY_OF_MONTH, diffDays);
while (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
return diffDays;
}
You can also simply create ONLY a UIView in Interface builder and drag & drop the ImageView and UILabel (to make it look like your desired header) and then use that.
Once your UIView looks like the way you want it too, you can programmatically initialize it from the XIB and add to your UITableView. In other words, you dont have to design the ENTIRE table in IB. Just the headerView (this way the header view can be reused in other tables as well)
For example I have a custom UIView for one of my table headers. The view is managed by a xib file called "CustomHeaderView" and it is loaded into the table header using the following code in my UITableViewController subclass:
-(UIView *) customHeaderView {
if (!customHeaderView) {
[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
}
return customHeaderView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the CustomerHeaderView as the tables header view
self.tableView.tableHeaderView = self.customHeaderView;
}
If you don't want to rely on a javascript library, you can use document.write()
to spit out the required css, wrapped in style
tags, straight into the document head
:
<head>
<script type="text/javascript">
document.write("<style>body { background-color:#000 }</style>");
</script>
# other stuff..
</head>
This way you avoid firing an extra HTTP request.
There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!
Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
eval('(' + jsonObject + ')')
I would tentatively recommend using PDO for your SQL access.
Then it is only a case of changing the driver and ensuring the SQL works on the new backend. In theory. Data migration is a different issue.
Abstract database access is great.
As all the other answers show, the problem is that adding a std::string
and a const char*
using +
results in a std::string
, while system()
expects a const char*
. And the solution is to use c_str()
. However, you can also do it without a temporary:
string name = "john";
system((" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'").c_str());
[quote from http://www.javabeat.net/session-factory-hibernate-4/]
There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.
You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?
If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
I had that issue and I solved by doing this:
.done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
I added this code after my script as I used jQuery. Try same)
<script type="text/JavaScript">
$(document).ready(function() {
$("#feedback").submit(function(event) {
event.preventDefault();
$.ajax({
url: "feedback_lib.php",
type: "post",
data: $("#feedback").serialize()
}).done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
});
});
</script>
<form id="feedback" action="" name="feedback" method="post">
<input id="name" name="name" placeholder="name" />
<br />
<input id="surname" name="surname" placeholder="surname" />
<br />
<input id="enquiry" name="enquiry" placeholder="enquiry" />
<br />
<input id="organisation" name="organisation" placeholder="organisation" />
<br />
<input id="email" name="email" placeholder="email" />
<br />
<textarea id="message" name="message" rows="7" cols="40" placeholder="?????????"></textarea>
<br />
<button id="send" name="send">send</button>
</form>
Solved!
$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
Try this.
20 4 * * *
Check the below Screenshot
Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/
I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.
http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/ The blog post is a 2 parter, and the project is here: https://github.com/dkarzon/DropNet
It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.
You should add parse_dates=True
, or parse_dates=['column name']
when reading, thats usually enough to magically parse it. But there are always weird formats which need to be defined manually. In such a case you can also add a date parser function, which is the most flexible way possible.
Suppose you have a column 'datetime' with your string, then:
from datetime import datetime
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
This way you can even combine multiple columns into a single datetime column, this merges a 'date' and a 'time' column into a single 'datetime' column:
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)
You can find directives (i.e. the letters to be used for different formats) for strptime
and strftime
in this page.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.
Map<String, Integer> pointsByName = new HashMap<>();
Map<String, Integer> maxPointsByName = new HashMap<>();
Map<String, Double> gradesByName = pointsByName.entrySet().stream()
.map(entry -> new AbstractMap.SimpleImmutableEntry<>(
entry.getKey(), ((double) entry.getValue() /
maxPointsByName.get(entry.getKey())) * 100d))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.
var queryString = $('#myFormId').formSerialize();
From http://malsup.com/jquery/form
Or using straight jquery:
var queryString = $('#myFormId').serialize();
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
JavaScript's Date
object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.
The internal representation of a Date
object is a single number, representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC
, without regard to leap seconds. There is no time zone or string format stored in the Date object itself. When various functions of the Date
object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.
The only operations the Date
object can do with non-local time zones are:
It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting Date
object. For example:
var d = new Date("2020-04-13T00:00:00.000+08:00");
d.toISOString() //=> "2020-04-12T16:00:00.000Z"
d.valueOf() //=> 1586707200000 (this is what is actually stored in the object)
In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a Date
object can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via the timeZone
option to toLocaleString
and its variations. Most implementations will support IANA time zone identifiers, such as 'America/New_York'
. For example:
var d = new Date("2020-04-13T00:00:00.000+08:00");
d.toLocaleString('en-US', { timeZone: 'America/New_York' })
//=> "4/12/2020, 12:00:00 PM"
// (midnight in China on Apring 13th is noon in New York on April 12th)
Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is 'UTC'
, thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).
There are several libraries that can be used to work with time zones. Though they still cannot make the Date
object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.
Here are the libraries to consider:
Intl-based Libraries
New development should choose from one of these implementations, which rely on the Intl API for their time zone data:
Non-Intl Libraries
These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.
* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.
Discontinued Libraries
These libraries have been officially discontinued and should no longer be used.
The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.
Polling like this is definitely the least preferred solution.
I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:
Main thread:
synchronized(syncObject) {
try {
// Calling wait() will block this thread until another thread
// calls notify() on the object.
syncObject.wait();
} catch (InterruptedException e) {
// Happens if someone interrupts your thread.
}
}
Other thread:
// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
syncObject.notify();
}
syncObject
itself can be a simple Object
.
There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.
It is probably not a correct way for clean, but I made that to delete unnecessary files, and take less size of a project. It continuously finds and deletes all build and Gradle folders made file clean.bat copy that into the folder where your project is
set mypath=%cd%
for /d /r %mypath% %%a in (build\) do if exist "%%a" rmdir /s /q "%%a"
for /d /r %mypath% %%a in (.gradle\) do if exist "%%a" rmdir /s /q "%%a"
For me the best solution is this one: https://www.bitcaal.com/how-to-change-the-app-language-programmatically-in-android/
package me.mehadih.multiplelanguage;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setApplicationLocale("az"); // short name of language. "en" for English
setContentView(R.layout.activity_main);
}
private void setApplicationLocale(String locale) {
Resources resources = getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration config = resources.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(new Locale(locale.toLowerCase()));
} else {
config.locale = new Locale(locale.toLowerCase());
}
resources.updateConfiguration(config, dm);
}
}
solved it by:
Converter<MyError> converter =
(Converter<MyError>)JacksonConverterFactory.create().get(MyError.class);
MyError myError = converter.fromBody(response.errorBody());
Simply delete the maintenance.flag
file in root folder and then delete the files of cache folder and session folder inside var/
folder.
Given your comment to the question (where you say that executing the install for a single package works as expected), I would suggest looping over your requirement file. In bash:
#!/bin/sh
while read p; do
pip install $p
done < requirements.pip
HTH!
If you are able to allow the ASPNET and associated users permission to read & write a file, you can easily use an HTML file with standard String.Format()
placeholders ({0}
, {1:C}
, etc.) to accomplish this.
Merely read in the file, as a string, using classes from the System.IO
namespace. Once you have that string, pass it as the first argument to String.Format()
, and provide the parameters.
Keep that string around, and use it as the body of the e-mail, and you're essentially done. We do this on dozens of (admittedly small) sites today, and have had no issues.
I should note that this works best if (a) you're not sending zillions of e-mails at a time, (b) you're not personalizing each e-mail (otherwise you eat up a ton of strings) and (c) the HTML file itself is relatively small.
GUIDs are 128bits, or
0 through ffffffffffffffffffffffffffffffff (hex) or
0 through 340282366920938463463374607431768211455 (decimal) or
0 through 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 (binary, base 2) or
0 through 91"<b.PX48m!wVmVA?1y (base 95)
So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:
0 through -r54lj%NUUO[Hi$c2ym0 (base 85, using 0-9A-Za-z!"#$%&'()*+,- chars)
:-)
The page has to be launched from the Home screen for the meta tag to work.
SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;
In case if someone is having an issue using extract.
If you truly want to "grep" the formatted output (display strings) then go with Mike's approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell's object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:
PS> alias | Get-Member
TypeName: System.Management.Automation.AliasInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
<snip>
*Definition* Property System.String Definition {get;}
<snip>
Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:
PS> alias
CommandType Name *Definition*
----------- ---- ----------
Alias % ForEach-Object
<snip>
Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to "script" against. Now if what you want to "grep" is the Definition property contents then consider this. Rather than just grepping that one property's value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:
PS> alias | Where-Object {$_.Definition -match 'alias'}
CommandType Name Definition
----------- ---- ----------
Alias epal Export-Alias
Alias gal Get-Alias
Alias ipal Import-Alias
Alias nal New-Alias
Alias sal Set-Alias
In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex 'alias'. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.
BTW if you're typing this, then you can use one of two aliases for Where-Object - 'Where' or '?'. For example:
PS> gal | ?{$_.Definition -match '-Item*'}
The point against parseInt
-approach:
There's no need to use lambdas and/or give radix
parameter to parseInt
, just use parseFloat
or Number
instead.
Reasons:
It's working:
var src = "1,2,5,4,3";
var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
var obj = {1: ..., 3: ..., 4: ..., 7: ...};
var keys= Object.keys(obj); // ["1", "3", "4", "7"]
var ids = keys.map(parseFloat); // [1, 3, 4, 7]
var arr = ["1", 5, "7", 11];
var ints= arr.map(parseFloat); // [1, 5, 7, 11]
ints[1] === "5" // false
ints[1] === 5 // true
ints[2] === "7" // false
ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when parseInt
-approach - doesn't:
// execution time measure function
// keep it simple, yeah?
> var f = (function (arr, c, n, m) {
var i,t,m,s=n();
for(i=0;i++<c;)t=arr.map(m);
return n()-s
}).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
> f(Number) // first launch, just warming-up cache
> 3971 // nice =)
> f(Number)
> 3964 // still the same
> f(function(e){return+e})
> 5132 // yup, just little bit slower
> f(function(e){return+e})
> 5112 // second run... and ok.
> f(parseFloat)
> 3727 // little bit quicker than .map(Number)
> f(parseFloat)
> 3737 // all ok
> f(function(e){return parseInt(e,10)})
> 21852 // awww, how adorable...
> f(function(e){return parseInt(e)})
> 22928 // maybe, without '10'?.. nope.
> f(function(e){return parseInt(e)})
> 22769 // second run... and nothing changes.
> f(Number)
> 3873 // and again
> f(parseFloat)
> 3583 // and again
> f(function(e){return+e})
> 4967 // and again
> f(function(e){return parseInt(e,10)})
> 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt
works about 4 times faster, but still slower than others. In total: +e
< Number
< parseFloat
< parseInt
Run this command in terminal to remove simulators that can't be accessed from the current version of Xcode in use.
xcrun simctl delete unavailable
Also if you're looking to reclaim simulator related space Michael Tsai found that deleting sim logs saved him 30 GB.
~/Library/Logs/CoreSimulator
I solved this problem by adding another div as a sibling to the scrolling content div. It's height is set to the radius of the curved borders. There will be design issues if you have content that you want nudged to the very bottom, or text you want to flow into this new div, etc,. but for my UI this thin div is no problem.
The real trick is to have the following structure:
<div class="window">
<div class="title">Some title text</div>
<div class="content">Main content area</div>
<div class="footer"></div>
</div>
Important CSS highlights:
Here's what that looks like:
In Solution Explorer, please select files you want to copied to output directory and assign two properties: - Build action = Content - Copy to Output Directory = Copy Always
This will do the trick.
(1..4).each { |i|
a = 9 if i==3
puts a
}
#nil
#nil
#9
#nil
for i in 1..4
a = 9 if i==3
puts a
end
#nil
#nil
#9
#9
In 'for' loop, local variable is still lives after each loop. In 'each' loop, local variable refreshes after each loop.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
import os, sys, re, glob
pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
for line in reader:
retline = pattern.sub(replacementStringMatchesPattern, "", line)
sys.stdout.write(retline)
print (retline)