One command and does not use the destructive git reset
command:
GIT_SEQUENCE_EDITOR="sed -i 's/pick/d/'" git rebase -i HEAD~ --autostash
It simply drops the commit, putting you back exactly in the state before the cherry-pick even if you had local changes.
The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService
" as the service reference name, that will generate the type TestUploaderWebService.Service1
. That class will have a method named GetFileListOnWebServer
, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:
string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
proxy = new TestUploaderWebService.Service1();
files = proxy.GetFileListOnWebServer();
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.
I came up with this method because while on the CLI, it's not possible to use the methods provided in the other answers here and it had always bugged me.
Basic Example
FOR /L %L IN (0,0,1) DO @(
ECHO. Counter always 0, See "%L" = "0" - Waiting a split second&ping -n 1 127.0.0.1>NUL )
This is truly an infinite loop!
This is useful for monitoring something in a CMD
window, and allows you to use CTRL
+C
to break it when you're done.
Want to Have a counter?
Either use SET /A
OR You can modify the FOR /L
Loop to do the counting and still be infinite (Note, BOTH of these methods have a 32bit integer overflow)
SET /A
Method:
FOR /L %L IN (0,0,1) DO @(
SET /A "#+=1"&ECHO. L Still equals 0, See "%L = 0"! - Waiting a split second &ping -n 1 127.0.0.1>NUL )
Native FOR /L
Counter:
FOR /L %L IN (-2147483648,1,2147483648) DO @(
ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )
Counting Sets of 4294967295 and Showing Current Value of L:
FOR /L %L IN (1,1,2147483648) DO @(
(
IF %L EQU 0 SET /A "#+=1">NUL
)&SET /A "#+=0"&ECHO. Sets of 4294967295 - Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )
However, what if:
For this, I determined how to use a couple methods to break the FOR
Loop prematurely effectively turning it into a "DO WHILE
" or "DO UNTIL
" Loop, which is otherwise sorely lacking in CMD.
NOTE: Most of the time a loop will continue to iterate past the condition you checked for, often this is a wanted behavior, but not in our case.
DO WHILE
" / "DO UNTIL
" LoopUPDATE: Due to wanting to use this code in CMD Scripts (and have them persist!) as well as CLI, and on thinking if there might be a "more Correct" method to achieve this I recommend using the New method!
New Method (Can be used inside CMD Scripts without exiting the script):
FOR /F %%A IN ('
CMD /C "FOR /L %%L IN (0,1,2147483648) DO @( ECHO.%%L & IF /I %%L EQU 10 ( exit /b ) )"
') DO @(
ECHO %%~A
)
At CLI:
FOR /F %A IN ('
CMD /C "FOR /L %L IN (0,1,2147483648) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )"
') DO @(
ECHO %~A
)
Original Method (Will work on CLI just fine, but will kill a script.)
FOR /L %L IN (0,1,2147483648) DO @(
ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL&(
IF /I %L EQU 10 (
ECHO.Breaking the Loop! Because We have matched the condition!&DIR >&0
)
)
) 2>NUL
Through chance I had hit upon some ways to exit loops prematurely that did not close the CMD prompt when trying to do other things which gave me this Idea.
While ECHO.>&3 >NUL
had worked for me in some scenarios, I have played with this off and on over the years and found that DIR >&0 >NUL
was much more consistent.
I am re-writing this answer from here forward to use that method instead as I recently found the old note to myself to use this method instead.
DIR >&0 >NUL
The >NUL is optional, I just prefer not to have it output the error.
I prefer to match inLine when possible, as you can see in this sanitized example of a Command I use to monitor LUN Migrations on our VNX.
for /l %L IN (0,0,1) DO @(
ECHO.& ECHO.===========================================& (
[VNX CMD] | FINDSTR /R /C:"Source LU Name" /C:"State:" /C:"Time " || DIR >&0 >NUL
) & Ping -n 10 1.1.1.1 -w 1000>NUL )
Also, I have another method I found in that note to myself which I just re-tested to confirm works just as well at the CLI as the other method.
Apparently, when I first posted here I posted an older iteration I was playing with instead of the two newer ones which work better:
In this method, we use EXIT /B
to exit the For Loop, but we don't want to exit the CLI so we wrap it in a CMD session:
FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )" ') DO @(ECHO %~A)
Because the loop itself happens in the CMD session, we can use EXIT /B to exit the iteration of the loop without losing our CMD Session, and without waiting for the loop to complete, much the same as with the other method.
I would go so far as to say that this method is likely the "intended" method for the sort of scenario where you want to break a for loop at the CLI, as using CMD session is also the only way to get Delayed expansion working at the CLI for your loops, and the behavior and such behavior is clearly an intended workflow to leave a CMD session.
IE: Microsoft clearly made an intentional effort to have CMD Exit /B For loops behave this way, while the "Intended" way of doing this, as my other method, relies on having accidentally created just the right error to kick you out of the loop without letting the loop finish processing, which I only happenstantially discovered, and seems to only reliably work when using the DIR command which is fairly strange.
So that said, I think it's probably a better practice to use Method 2:
FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )" ') DO @(ECHO %~A)
Although I suspect Method 1 is going to be slightly faster:
FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( DIR >&) >NUL ) )
And in either case, both should allow DO-While loops as you need for your purposes.
From Api level 1, you can use the public void setTextSize (float size)
method.
From the documentation:
Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.
Parameters: size -> float: The scaled pixel size.
So you can simple do:
textView.setTextSize(12); // your size in sp
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
To prevent "Div parent" use margin of "div child":
In parent use these css:
For swift 4.2 and above you can do it as below:
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div
has role="dialog"
. When the screen reader notices that a div
becomes visible which has this role, it'll speak the label for that div
.
There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label>
HTML tag. With HTML modals the label is usually a <h>
header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader]
, and the screen reader will speak that header when the modal appears.
Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden
property is frequently redundant and can probably be skipped in most cases.
var marker+i = "some stuff";
coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
most performant solution for string
string result = new StringBuilder().Insert(0, "---", 5).ToString();
What follows is an explanation for what is going on, scroll to bottom for code demos.
Passing parameter suppress=True
to function set_printoptions
works only for numbers that fit in the default 8 character space allotted to it, like this:
import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential
#notation on print, default False
# tiny med large
a = np.array([1.01e-5, 22, 1.2345678e7]) #notice how index 2 is 8
#digits wide
print(a) #prints [ 0.0000101 22. 12345678. ]
However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:
np.set_printoptions(suppress=True)
a = np.array([1.01e-5, 22, 1.2345678e10]) #notice how index 2 is 10
#digits wide, too wide!
#exponential notation where we've told it not to!
print(a) #prints [1.01000000e-005 2.20000000e+001 1.23456780e+10]
numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.
Here comes set_printoptions(formatter=...)
to the rescue to specify options for printing and rounding. Tell set_printoptions
to just print bare a bare float:
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:f}'.format})
a = np.array([1.01e-5, 22, 1.2345678e30]) #notice how index 2 is 30
#digits wide.
#Ok good, no exponential notation in the large numbers:
print(a) #prints [0.000010 22.000000 1234567799999999979944197226496.000000]
We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:0.2f}'.format}) #float, 2 units
#precision right, 0 on left
a = np.array([1.01e-5, 22, 1.2345678e30]) #notice how index 2 is 30
#digits wide
print(a) #prints [0.00 22.00 1234567799999999979944197226496.00]
The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.
from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
[9.55, 116, 189688622.37, 260332262.0, 1.97],
[2.2, 768, 6004865.13, 5759960.98, 1.21],
[3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
[1.91, 474, 44555062.72, 44555062.72, 0.41],
[5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
[4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]
#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)
#This is a little recursive helper function converts all nested
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
if type(arr) == type(np.array):
#If the passed type is an ndarray then convert it to a list and
#recursively convert all nested types
return arrayToList(arr.tolist())
else:
#if item isn't an ndarray leave it as is.
return arr
#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))
Prints:
array([[ 3.740, 5162.000, 13683628846.640, 12783387559.860, 1.810],
[ 9.550, 116.000, 189688622.370, 260332262.000, 1.970],
[ 2.200, 768.000, 6004865.130, 5759960.980, 1.210],
[ 3.740, 4062.000, 3263822121.390, 3066869087.900, 1.930],
[ 1.910, 474.000, 44555062.720, 44555062.720, 0.410],
[ 5.800, 5006.000, 8254968918.100, 7446788272.740, 3.250],
[ 4.500, 7887.000, 30078971595.460, 27814989471.310, 2.180],
[ 7.030, 116.000, 66252511.460, 81109291.000, 1.560],
[ 6.520, 116.000, 47674230.760, 57686991.000, 1.430],
[ 1.850, 623.000, 3002631.960, 2899484.080, 0.640],
[ 13.760, 1227.000, 1737874137.500, 1446511574.320, 4.320],
[ 13.760, 1227.000, 1737874137.500, 1446511574.320, 4.320]])
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
# very tiny medium size large sized
# numbers numbers numbers
my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81],
[1.000000000055, 116, 189688622.37, 260332262.0, 1.97],
[0.010000000022, 768, 6004865.13, -99e13, 1.21],
[1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93],
[2.91, 474, 44555062.72, 44555062.72, 0.41],
[5, 5006, 8254968918.1, 7446788272.74, 3.25],
[0.01, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1337, 1737874137.5, 1446511574.32, 4.32]]
import sys
#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)
#following two lines do the same thing, showing that np.savetxt can
#correctly handle python lists of lists and numpy 2D ndarrays.
np.savetxt(sys.stdout, my_list, '%19.2f')
np.savetxt(sys.stdout, my_array, '%19.2f')
Prints:
0.00 5162.00 13683628846.64 10100000000.00 1.81
1.00 116.00 189688622.37 260332262.00 1.97
0.01 768.00 6004865.13 -990000000000000.00 1.21
1.00 4062.00 3263822121.39 3066869087.90 1.93
2.91 474.00 44555062.72 44555062.72 0.41
5.00 5006.00 8254968918.10 7446788272.74 3.25
0.01 7887.00 30078971595.46 27814989471.31 2.18
7.03 116.00 66252511.46 81109291.00 1.56
6.52 116.00 47674230.76 57686991.00 1.43
1.85 623.00 3002631.96 2899484.08 0.64
13.76 1227.00 1737874137.50 1446511574.32 4.32
13.76 1337.00 1737874137.50 1446511574.32 4.32
0.00 5162.00 13683628846.64 10100000000.00 1.81
1.00 116.00 189688622.37 260332262.00 1.97
0.01 768.00 6004865.13 -990000000000000.00 1.21
1.00 4062.00 3263822121.39 3066869087.90 1.93
2.91 474.00 44555062.72 44555062.72 0.41
5.00 5006.00 8254968918.10 7446788272.74 3.25
0.01 7887.00 30078971595.46 27814989471.31 2.18
7.03 116.00 66252511.46 81109291.00 1.56
6.52 116.00 47674230.76 57686991.00 1.43
1.85 623.00 3002631.96 2899484.08 0.64
13.76 1227.00 1737874137.50 1446511574.32 4.32
13.76 1337.00 1737874137.50 1446511574.32 4.32
Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x
and very small e-x
ranges.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
Well here is a solution for you but I don't really understand why it works:
<html><body>
<div style="width: 200px; border: 1px solid red;">Test</div>
<div style="width: 200px; border: 1px solid blue; overflow: hidden; height: 1.5em;">My hovercraft is full of eels. These pretzels are making me thirsty.</div>
<div style="width: 200px; border: 1px solid yellow; overflow: hidden; height: 1.5em;">
This_is_a_terrible_example_of_thinking_outside_the_box.
</div>
<table style="border: 2px solid black; border-collapse: collapse; width: 200px;"><tr>
<td style="width:200px; border: 1px solid green; overflow: hidden; height: 1.5em;"><div style="width: 200px; border: 1px solid yellow; overflow: hidden;">
This_is_a_terrible_example_of_thinking_outside_the_box.
</div></td>
</tr></table>
</body></html>
Namely, wrapping the cell contents in a div.
No need for regex. This will also remove tabs, newlines etc
var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));
WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000
.
Apache Commons Lang 3 contais the class EnumUtils. If you aren't using Apache Commons in your projects, you're doing it wrong. You are reinventing the wheel!
There's a dozen of cool methods that we could use without throws an Exception. For example:
Gets the enum for the class, returning null if not found.
This method differs from Enum.valueOf in that it does not throw an exceptionfor an invalid enum name and performs case insensitive matching of the name.
EnumUtils.getEnumIgnoreCase(SeasonEnum.class, season);
If you haven't pushed your changes yet use git reset --soft [Hash for one commit]
to rollback to a specific commit. --soft
tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard
tells git to delete the changes being rolled back.
The = way is 2-way binding, which lets you to have live changes inside your directive. When someone changes that variable out of directive, you will have that changed data inside your directive, but @ way is not two-ways binding. It works like Text. You bind once, and you will have only its value.
To get it more clearly, you can use this great article:
I experienced the same error while using Windows 7 x64, Eclipse, and JDK 1.6.0_30. In the JDK installation folder there is a jre
folder. This threw me off at first as I was adding the aforementioned jars to the JDK's lib/security folder with no luck. Full path:
C:\Program Files\Java\jdk1.6.0_30\jre\lib\security
Download and extract the files contained in the jce
folder of this archive into that folder.
Here's your script...
DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
cd ..
DIR=$(pwd)
echo $DIR
done
Note the spaces, use of quotes, and $ signs.
1) The common mistake is shown in the example below.
public class Car {
private String color;
public Car(String color) {
this.color = color;
}
public boolean equals(Object obj) {
if(obj==null) return false;
if (!(obj instanceof Car))
return false;
if (obj == this)
return true;
return this.color.equals(((Car) obj).color);
}
public static void main(String[] args) {
Car a1 = new Car("green");
Car a2 = new Car("red");
//hashMap stores Car type and its quantity
HashMap<Car, Integer> m = new HashMap<Car, Integer>();
m.put(a1, 10);
m.put(a2, 20);
System.out.println(m.get(new Car("green")));
}
}
the green Car is not found
2. Problem caused by hashCode()
The problem is caused by the un-overridden method hashCode()
. The contract between equals()
and hashCode()
is:
If two objects have the same hash code, they may or may not be equal.
public int hashCode(){
return this.color.hashCode();
}
I know that is old question but mabye someone enjoy my way of solution in pure CSS. Gradient fade from left to right.
.contener{
width:300px;
height:200px;
background-size:cover;
border:solid 2px black;
}
.ed {
width: 0px;
height: 200px;
background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.75));
position: relative;
opacity:0;
transition:width 20s, opacity 0.6s;
}
.contener:hover .ed{
width: 300px;
background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.75));
position: relative;
opacity:1;
transition:width 0.4s, opacity 1.1s;
transition-delay: width 2s;
animation-name: gradient-fade;
animation-duration: 1.1s;
-webkit-animation-name: gradient-fade; /* Chrome, Safari, Opera */
-webkit-animation-duration: 1.1s; /* Chrome, Safari, Opera */
}
/* ANIMATION */
@-webkit-keyframes gradient-fade {
0% {background:linear-gradient(to right, rgba(0,0,255,0), rgba(255,0,0,0));}
2% {background:linear-gradient(to right, rgba(0,0,255,0.01875), rgba(255,0,0,0));}
4% {background:linear-gradient(to right, rgba(0,0,255,0.0375), rgba(255,0,0,0.0));}
6% {background:linear-gradient(to right, rgba(0,0,255,0.05625), rgba(255,0,0,0.0));}
8% {background:linear-gradient(to right, rgba(0,0,255,0.075), rgba(255,0,0,0));}
10% {background:linear-gradient(to right, rgba(0,0,255,0.09375), rgba(255,0,0,0));}
12% {background:linear-gradient(to right, rgba(0,0,255,0.1125), rgba(255,0,0,0));}
14% {background:linear-gradient(to right, rgba(0,0,255,0.13125), rgba(255,0,0,0));}
16% {background:linear-gradient(to right, rgba(0,0,255,0.15), rgba(255,0,0,0));}
18% {background:linear-gradient(to right, rgba(0,0,255,0.16875), rgba(255,0,0,0));}
20% {background:linear-gradient(to right, rgba(0,0,255,0.1875), rgba(255,0,0,0));}
22% {background:linear-gradient(to right, rgba(0,0,255,0.20625), rgba(255,0,0,0.01875));}
24% {background:linear-gradient(to right, rgba(0,0,255,0.225), rgba(255,0,0,0.0375));}
26% {background:linear-gradient(to right, rgba(0,0,255,0.24375), rgba(255,0,0,0.05625));}
28% {background:linear-gradient(to right, rgba(0,0,255,0.2625), rgba(255,0,0,0.075));}
30% {background:linear-gradient(to right, rgba(0,0,255,0.28125), rgba(255,0,0,0.09375));}
32% {background:linear-gradient(to right, rgba(0,0,255,0.3), rgba(255,0,0,0.1125));}
34% {background:linear-gradient(to right, rgba(0,0,255,0.31875), rgba(255,0,0,0.13125));}
36% {background:linear-gradient(to right, rgba(0,0,255,0.3375), rgba(255,0,0,0.15));}
38% {background:linear-gradient(to right, rgba(0,0,255,0.35625), rgba(255,0,0,0.16875));}
40% {background:linear-gradient(to right, rgba(0,0,255,0.375), rgba(255,0,0,0.1875));}
42% {background:linear-gradient(to right, rgba(0,0,255,0.39375), rgba(255,0,0,0.20625));}
44% {background:linear-gradient(to right, rgba(0,0,255,0.4125), rgba(255,0,0,0.225));}
46% {background:linear-gradient(to right, rgba(0,0,255,0.43125),rgba(255,0,0,0.24375));}
48% {background:linear-gradient(to right, rgba(0,0,255,0.45), rgba(255,0,0,0.2625));}
50% {background:linear-gradient(to right, rgba(0,0,255,0.46875), rgba(255,0,0,0.28125));}
52% {background:linear-gradient(to right, rgba(0,0,255,0.4875), rgba(255,0,0,0.3));}
54% {background:linear-gradient(to right, rgba(0,0,255,0.50625), rgba(255,0,0,0.31875));}
56% {background:linear-gradient(to right, rgba(0,0,255,0.525), rgba(255,0,0,0.3375));}
58% {background:linear-gradient(to right, rgba(0,0,255,0.54375), rgba(255,0,0,0.35625));}
60% {background:linear-gradient(to right, rgba(0,0,255,0.5625), rgba(255,0,0,0.375));}
62% {background:linear-gradient(to right, rgba(0,0,255,0.58125), rgba(255,0,0,0.39375));}
64% {background:linear-gradient(to right,rgba(0,0,255,0.6), rgba(255,0,0,0.4125));}
66% {background:linear-gradient(to right, rgba(0,0,255,0.61875), rgba(255,0,0,0.43125));}
68% {background:linear-gradient(to right, rgba(0,0,255,0.6375), rgba(255,0,0,0.45));}
70% {background:linear-gradient(to right, rgba(0,0,255,0.65625), rgba(255,0,0,0.46875));}
72% {background:linear-gradient(to right, rgba(0,0,255,0.675), rgba(255,0,0,0.4875));}
74% {background:linear-gradient(to right, rgba(0,0,255,0.69375), rgba(255,0,0,0.50625));}
76% {background:linear-gradient(to right, rgba(0,0,255,0.7125), rgba(255,0,0,0.525));}
78% {background:linear-gradient(to right, rgba(0,0,255,0.73125),,rgba(255,0,0,0.54375));}
80% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.5625));}
82% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.58125));}
84% {background:linear-gradient(to right, rgba(0,0,255,0.75),rgba(255,0,0,0.6));}
86% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.61875));}
88% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.6375));}
90% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.65625));}
92% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.675));}
94% {background:linear-gradient(to right, rgba(0,0,255,0.75),rgba(255,0,0,0.69375));}
96% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.7125));}
98% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.73125),);}
100% {background:linear-gradient(to right, rgba(0,0,255,0.75), rgba(255,0,0,0.75));}
}
_x000D_
<div class="contener" style="">
<div class="ed"></div>
</div>
_x000D_
Installing modules usually requires you to run an sql script that is included with the database installation.
Assuming linux-like OS
find / -name dblink.sql
Verify the location and run it
Just use like this somewhere inside the form
@method('PUT')
Updated 2017-12-16
I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.
Synchronous
<script src...>
will block downloading of the resources below it until it is downloaded and executed
This is no longer true. Have a look at the waterfall generated by Chrome 63:
<head>
<script src="//alias-0.redacted.com/payload.php?type=js&delay=333&rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&delay=333&rand=3"></script>
</head>
<link rel=stylesheet>
will not block download and execution of scripts below it
This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:
<link href="//alias-0.redacted.com/payload.php?type=css&delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&block=1000"></script>
Keeping the above in mind, the results in OP can be explained as follows:
CSS First:
CSS Download 500ms:<------------------------------------------------>
JS Download 400ms:<-------------------------------------->
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1500ms: ?
JS First:
JS Download 400ms:<-------------------------------------->
CSS Download 500ms:<------------------------------------------------>
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1400ms: ?
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
No, however, you could layer multiple <canvas>
elements on top of each other and accomplish something similar.
<div style="position: relative;">
<canvas id="layer1" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="layer2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
Draw your first layer on the layer1
canvas, and the second layer on the layer2
canvas. Then when you clearRect
on the top layer, whatever's on the lower canvas will show through.
with underscore.js
use the findWhere method:
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var result = _.findWhere(array, {name: 'string 1'});
console.log(result.name);
See this in JSFIDDLE
Use the overflow-y: scroll
property on the element that contains the elements.
The overflow-y
property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:
<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
i use this code, which relies on the library "JQuery":
$(document).on('change', 'select', function () {
let next_select = $(this);
// console.log(next_select.toArray())
if (!next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().parent().next().find('input[type="text"]').click()
console.log(next_select.parent().parent().parent().next());
} else if (next_select.parent().parent().next().find('select').prop("disabled")) {
setTimeout(function () {
next_select.parent().parent().next().find('select').select2('open')
}, 1000)
console.log('b');
} else if (next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().next().find('select').select2('open')
console.log('c');
}
});
Convert from human readable date to epoch:
long epoch = new java.text.SimpleDateFormat("MM/dd/yyyyHH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000;
Convert from epoch to human readable date:
String date = new java.text.SimpleDateFormat("MM/dd/yyyyHH:mm:ss").format(new java.util.Date (epoch*1000));
For other language converter: https://www.epochconverter.com
I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.
Public Sub Main()
REM Set up Global Unhandled Exception Handler.
AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent
REM Do other stuff
End Sub
Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
REM Log Exception here and do whatever else is needed
End Sub
I used the REM
comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM
.
Right click > Open.
Or, you can go into System Preferences, Security & Privacy, and set the restrictions on opening apps there.
Cleaning the project worked for me, Build > clean project.
The last question has an easy answer:
> .Machine$sizeof.pointer
[1] 8
Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.
EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/...
On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)
For image use this
ClipOval(
child: Image.network(
'https://url to your image',
fit: BoxFit.fill,
),
);
While for Asset Image use this
ClipOval(
child: Image.asset(
'Path to your image',
fit: BoxFit.cover,
),
)
Your example code essentially asks why the example program doesn't trap, and the answer is that memory protection is a kernel feature and applies only to entire pages, whereas the memory allocator is a library feature and it manages .. without enforcement .. arbitrary sized blocks which are often much smaller than pages.
Memory can only be removed from your program in units of pages, and even that is unlikely to be observed.
calloc(3) and malloc(3) do interact with the kernel to get memory, if necessary. But most implementations of free(3) do not return memory to the kernel1, they just add it to a free list that calloc() and malloc() will consult later in order to reuse the released blocks.
Even if a free() wanted to return memory to the system, it would need at least one contiguous memory page in order to get the kernel to actually protect the region, so releasing a small block would only lead to a protection change if it was the last small block in a page.
So your block is there, sitting on the free list. You can almost always access it and nearby memory just as if it were still allocated. C compiles straight to machine code and without special debugging arrangements there are no sanity checks on loads and stores. Now, if you try and access a free block, the behavior is undefined by the standard in order to not make unreasonable demands on library implementators. If you try and access freed memory or meory outside an allocated block, there are various things that can go wrong:
So, working backwards from your example to the overall theory, malloc(3) gets memory from the kernel when it needs it, and typically in units of pages. These pages are divided or consolidated as the program requires. Malloc and free cooperate to maintain a directory. They coalesce adjacent free blocks when possible in order to be able to provide large blocks. The directory may or may not involve using the memory in freed blocks to form a linked list. (The alternative is a bit more shared-memory and paging-friendly, and it involves allocating memory specifically for the directory.) Malloc and free have little if any ability to enforce access to individual blocks even when special and optional debugging code is compiled into the program.
1. The fact that very few implementations of free() attempt to return memory to the system is not necessarily due to the implementors slacking off. Interacting with the kernel is much slower than simply executing library code, and the benefit would be small. Most programs have a steady-state or increasing memory footprint, so the time spent analyzing the heap looking for returnable memory would be completely wasted. Other reasons include the fact that internal fragmentation makes page-aligned blocks unlikely to exist, and it's likely that returning a block would fragment blocks to either side. Finally, the few programs that do return large amounts of memory are likely to bypass malloc() and simply allocate and free pages anyway.
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect javascript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your javascript in an external javascript file that is included with:
<script type="text/javascript" src="http://mydomain.com/xxxx.js"></script>
tags, then the javascript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external javascript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at you do, not by having secrets. That's ultimately how success works on the web anyway.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.
Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.
Hibernate has this already written:
CDI might solve this, but don't know - haven't investigated fully yet
.
@Inject Instance< MyClass> x;
...
x.iterator()
Also for annotations:
abstract class MyAnnotationQualifier
extends AnnotationLiteral<Entity> implements Entity {}
Using generators, it is quite simple:
signal = ['?Signal value?']
def pniter( iter, signal=signal ):
iA = iB = signal
for iC in iter:
if iB is signal:
iB = iC
continue
else:
yield iA, iB, iC
iA = iB
iB = iC
iC = signal
yield iA, iB, iC
if __name__ == '__main__':
print('test 1:')
for a, b, c in pniter( range( 10 )):
print( a, b, c )
print('\ntest 2:')
for a, b, c in pniter([ 20, 30, 40, 50, 60, 70, 80 ]):
print( a, b, c )
print('\ntest 3:')
cam = { 1: 30, 2: 40, 10: 9, -5: 36 }
for a, b, c in pniter( cam ):
print( a, b, c )
for a, b, c in pniter( cam ):
print( a, a if a is signal else cam[ a ], b, b if b is signal else cam[ b ], c, c if c is signal else cam[ c ])
print('\ntest 4:')
for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ]):
print( a, b, c )
print('\ntest 5:')
for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ], ['sig']):
print( a, b, c )
print('\ntest 6:')
for a, b, c in pniter([ 20, ['?Signal value?'], None, '?Signal value?', 60, 70, 80 ], signal ):
print( a, b, c )
Note that tests that include None and the same value as the signal value still work, because the check for the signal value uses "is" and the signal is a value that Python doesn't intern. Any singleton marker value can be used as a signal, though, which might simplify user code in some circumstances.
You should use urllib2, like this:
import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()
# Prints:
# 200 [from the try block]
# 404 [from the except block]
Paul's answer seems to defeat the purpose of bootstrap; that of being responsive to the viewport / screen size.
By nesting rows and columns you can achieve the same result, while retaining responsiveness.
Here is an up-to-date response to this problem;
<div class="container-fluid">_x000D_
<h1> Responsive Nested Bootstrap </h1> _x000D_
<div class="row">_x000D_
<div class="col-md-5" style="background-color:red;">Span 5</div>_x000D_
<div class="col-md-3" style="background-color:blue;">Span 3</div>_x000D_
<div class="col-md-2">_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:green;">Span 2</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:purple;">Span 2</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-2" style="background-color:yellow;">Span 2</div>_x000D_
</div>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:yellow;">Span 6</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:green;">Span 6</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-6" style="background-color:red;">Span 6</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can view the codepen here.
Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".
An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.
For example, here is a completely imaginary case with a pseudo language:
You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:
book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
book = new Book();
book.setAuthor(row.get('author');
book_list.add(book);
}
With an ORM library, it would look like this:
book_list = BookTable.query(author="Linus");
The mechanical part is taken care of automatically via the ORM library.
Using ORM saves a lot of time because:
Using an ORM library is more flexible because:
But ORM can be a pain:
for
loop.Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:
If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:
Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
I had the same problem, when i loaded a text file via fs.readFile()
, I tried to set the encodeing to UTF8, it keeped the same. my solution now is this:
myString = JSON.parse( JSON.stringify( myString ) )
after this an Ö is realy interpreted as an Ö.
If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work
$ cat config/database.yml
$ echo $DATABASE_URL
mysql://root:[email protected]:3306/my_db_name
for Heroku:
heroku config:set DATABASE_URL='mysql://root:[email protected]/my_db_name'
A quite common usage for '&&' is compiling software with autotools. For example:
./configure --prefix=/usr && make && sudo make install
Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.
Sometimes I get really carried away...
tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf
I do this when for example making a linux from scratch box.
I did Google about this issue but didn't find any best solution ,So Created a solution that works fine in all browsers.
just call badFixSelectBoxDataWidthIE() function on page load.
function badFixSelectBoxDataWidthIE(){
if ($.browser.msie){
$('select').each(function(){
if($(this).attr('multiple')== false){
$(this)
.mousedown(function(){
if($(this).css("width") != "auto") {
var width = $(this).width();
$(this).data("origWidth", $(this).css("width"))
.css("width", "auto");
/* if the width is now less than before then undo */
if($(this).width() < width) {
$(this).unbind('mousedown');
$(this).css("width", $(this).data("origWidth"));
}
}
})
/* Handle blur if the user does not change the value */
.blur(function(){
$(this).css("width", $(this).data("origWidth"));
})
/* Handle change of the user does change the value */
.change(function(){
$(this).css("width", $(this).data("origWidth"));
});
}
});
}
}
Swift 4 Solution :
@IBInspectable var backgroundImage: UIImage? {
didSet {
UIGraphicsBeginImageContext(self.frame.size)
backgroundImage?.draw(in: self.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image{
self.backgroundColor = UIColor(patternImage: image)
}
}
}
Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.
Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.
While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.
I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.
Base64decode("the answer to life the universe and everything") = 00101010
An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".
var Hello = React.createClass({
render: function() {
return (
<div className="divClass">
<img src={this.props.url} alt={`${this.props.title}'s picture`} className="img-responsive" />
<span>Hello {this.props.name}</span>
</div>
);
}
});
AdBlock seems to block the loading of AdSense (etc) JavaScript files. So, if you are using asynchronous version of AdSense ads you can check if adsbygoogle
is an Array
. This must be checked after few seconds since the asynchronous script is... asynchronous. Here is a rough outline:
window.setTimeout(function(){
if(adsbygoogle instanceof Array) {
// adsbygoogle.js did not execute; probably blocked by an ad blocker
} else {
// adsbygoogle.js executed
}
}, 2000);
To clarify, here is an example of what the AdSense asynchronous ads code looks like:
<!-- this can go anywhere -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- this is where the ads display -->
<ins class="adsbygoogle" ...></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Notice that adsbygoogle
is initialized as an Array. The adsbygoogle.js
library changes this array into Object {push: ...}
when it executes. Checking the type of variable after a certain time can tell you if the script was loaded.
Function:
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
Usage:
var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));
dates.forEach(function(date) {
console.log(date);
});
Hope it helps you
No need to check every single element unless you care contents and you can utilize slice append. try it out
pos := 0
arr := []int{1, 2, 3, 4, 5, 6, 7, 9}
fmt.Println("input your position")
fmt.Scanln(&pos)
/* you need to check if negative input as well */
if (pos < len(arr)){
arr = append(arr[:pos], arr[pos+1:]...)
} else {
fmt.Println("position invalid")
}
I notice that Entity Framework 6.1 pointed at MSSQL does automatically add indexes on foreign keys.
Use this CSS (jsFiddle example):
input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
color: green
}
You have to write the most outer element on the left and the most inner element on the right.
.btn:hover input:disabled
would select any disabled input elements contained in an element with a class btn
which is currently hovered by the user.
I would prefer :disabled
over [disabled]
, see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?
By the way, Laravel (PHP) generates the HTML - not the browser.
Using jQuery function
var valFileDownloadPath = 'http//:'+'your url';
window.open(valFileDownloadPath , '_blank');
Weirdness is highly subjective, I just suggest to follow the official recommendation:
Guide to naming conventions on groupId, artifactId and version
groupId
will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.eg.
org.apache.maven
,org.apache.commons
A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.
eg.
org.apache.maven
,org.apache.maven.plugins
,org.apache.maven.reporting
artifactId
is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.eg.
maven
,commons-math
version
if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.eg.
2.0
,2.0.1
,1.3.1
I was getting this issue when trying to install on 2.3 devices (fine on 4.0.3). It ended up being due to a lib project i was using had multiple jars which were for stuff already in android e.g. HttpClient and XML parsers etc. Looking at logcat
led me to find this as it was telling me it was skipping classes due to them already being present. Nice unhelpful original error there!
You can check if you got your remote setup right and have the proper permissions with
git ls-remote origin
if you called your remote "origin". If you get an error you probably don't have your security set up correctly such as uploading your public key to github for example. If things are setup correctly, you will get a list of the remote references. Now
git fetch origin
will work barring any other issues like an unplugged network cable.
Once you have that done, you can get any branch you want that the above command listed with
git checkout some-branch
this will create a local branch of the same name as the remote branch and check it out.
If you just want to look for methods:
On mac OS X 10.5+ binding, it is Alt + ? + O
By Default XWin Key binding, it is Shift + Ctrl + Alt + N
You can also press double SHIFT then, you can search anything (not only method, but also class, files, and actions)
Sounds like you executed another statement in the same connection before traversing the result set from the first statement. If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
Another alternative is KMP (Knuth–Morris–Pratt).
The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.
Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {_x000D_
if (pattern.length == 0)_x000D_
return 0; // Immediate match_x000D_
_x000D_
// Compute longest suffix-prefix table_x000D_
var lsp = [0]; // Base case_x000D_
for (var i = 1; i < pattern.length; i++) {_x000D_
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1];_x000D_
if (pattern.charAt(i) == pattern.charAt(j))_x000D_
j++;_x000D_
lsp.push(j);_x000D_
}_x000D_
_x000D_
// Walk through text string_x000D_
var j = 0; // Number of chars matched in pattern_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1]; // Fall back in the pattern_x000D_
if (text.charAt(i) == pattern.charAt(j)) {_x000D_
j++; // Next char matched, increment position_x000D_
if (j == pattern.length)_x000D_
return i - (j - 1);_x000D_
}_x000D_
}_x000D_
return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
There are new units that you can use:
vw
- viewport width
vh
- viewport height
#neo_main_container1
{
width: 100%; //fallback
width: 100vw;
}
Opera Mini does not support this, but you can use it in all other modern browsers.
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
Here is a simple clean implementation which is consistent with Pattern#split
and works with variable length patterns, which look behind cannot support, and it is easier to use. It is similar to the solution provided by @cletus.
public static String[] split(CharSequence input, String pattern) {
return split(input, Pattern.compile(pattern));
}
public static String[] split(CharSequence input, Pattern pattern) {
Matcher matcher = pattern.matcher(input);
int start = 0;
List<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(input.subSequence(start, matcher.start()).toString());
result.add(matcher.group());
start = matcher.end();
}
if (start != input.length()) result.add(input.subSequence(start, input.length()).toString());
return result.toArray(new String[0]);
}
I don't do null checks here, Pattern#split
doesn't, why should I. I don't like the if
at the end but it is required for consistency with the Pattern#split
. Otherwise I would unconditionally append, resulting in an empty string as the last element of the result if the input string ends with the pattern.
I convert to String[] for consistency with Pattern#split
, I use new String[0]
rather than new String[result.size()]
, see here for why.
Here are my tests:
@Test
public void splitsVariableLengthPattern() {
String[] result = Split.split("/foo/$bar/bas", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar", "/bas" }, result);
}
@Test
public void splitsEndingWithPattern() {
String[] result = Split.split("/foo/$bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar" }, result);
}
@Test
public void splitsStartingWithPattern() {
String[] result = Split.split("$foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "", "$foo", "/bar" }, result);
}
@Test
public void splitsNoMatchesPattern() {
String[] result = Split.split("/foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/bar" }, result);
}
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
Use this to remove HTML tags from string in JavaScript:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
Use two <input type=file>
elements instead, without the multiple
attribute.
Use forward declarations where you can. If a class declaration only uses a pointer or reference to a type, you can just forward declare it and include the header for the type in the implementation file.
For example:
// T.h
class Class2; // Forward declaration
class T {
public:
void doSomething(Class2 &c2);
private:
Class2 *m_Class2Ptr;
};
// T.cpp
#include "Class2.h"
void Class2::doSomething(Class2 &c2) {
// Whatever you want here
}
Fewer includes means far less work for the preprocessor if you do it enough.
This is another way to shuffle the data.frame
using package dplyr
:
row-wise:
df2 <- slice(df1, sample(1:n()))
or
df2 <- sample_frac(df1, 1L)
column-wise:
df2 <- select(df1, one_of(sample(names(df1))))
That combination of username, host, and password is not allowed to connect to the server. Verify the permission tables (reloading grants if required) on the server and that you're connecting to the correct server.
For example, if you want an array of int
pointers it will be int* a[10]
. It means that variable a
is a collection of 10 int*
s.
EDIT
I guess this is what you want to do:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
If used inside Bootstrap v3 tabs, the following should work:
$('a[href="#tab-location"]').on('shown.bs.tab', function(e){
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
where tab-location
is the ID of tab containing map.
var date=new Date();
//here I am using "-30" to subtract 30 minutes from the current time.
var minute=date.setMinutes(date.getMinutes()-30);
console.log(minute) //it will print the time and date according to the above condition in Unix-timestamp format.
you can convert Unix timestamp into conventional time by using new Date()
.for example
var extract=new Date(minute)
console.log(minute)//this will print the time in the readable format.
Create a table with column as type json
CREATE TABLE friends ( id serial primary key, data jsonb);
Now let's insert json data
INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
Now let's make some queries to fetch data
select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;
You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])
name | work
------------+----------------------------
"Arya" | ["Improvements", "Office"]
"Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)
Now to retrieve only the values just use ->>
select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
Combining the input from everyone else (use not, no parens, use os.mkdir
) you'd get...
special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
os.mkdir(special_path_for_john)
I had the same problem. I'm using this solution I found: React Native display SVG from a file
It's not perfect, and i'm revisiting today, because it performs a lot worse on Android.
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
If %x%==1 (
If %y%==1 (
:: both are equal to 1.
)
)
That's for checking if multiple variables equal value. Here's for either variable.
If %x%==1 (
:: true
)
If %x%==0 (
If %y%==1 (
:: true
)
)
If %x%==0 (
If %y%==0 (
:: False
)
)
I just thought of that off the top if my head. I could compact it more.
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
URLSearchParams has increasing browser support.
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = new URLSearchParams(data);
// searchParams.toString() === 'var1=value1&var2=value2'
Node.js offers the querystring module.
const querystring = require('querystring');
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = querystring.stringify(data);
// searchParams === 'var1=value1&var2=value2'
You can use the rotate attribute
<item>
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%" >
<shape
android:shape="line"
android:top="1dip" >
<stroke
android:width="1dip"
/>
</shape>
</rotate>
</item>
This may help if someone want it in PHP
$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);
The key to getting this to work is to tell sed
to exclude what you don't want to be output as well as specifying what you do want.
string='This is a sample 123 text and some 987 numbers'
echo "$string" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'
This says:
-n
)p
)In general, in sed
you capture groups using parentheses and output what you capture using a back reference:
echo "foobarbaz" | sed 's/^foo\(.*\)baz$/\1/'
will output "bar". If you use -r
(-E
for OS X) for extended regex, you don't need to escape the parentheses:
echo "foobarbaz" | sed -r 's/^foo(.*)baz$/\1/'
There can be up to 9 capture groups and their back references. The back references are numbered in the order the groups appear, but they can be used in any order and can be repeated:
echo "foobarbaz" | sed -r 's/^foo(.*)b(.)z$/\2 \1 \2/'
outputs "a bar a".
If you have GNU grep
(it may also work in BSD, including OS X):
echo "$string" | grep -Po '\d+'
or variations such as:
echo "$string" | grep -Po '(?<=\D )(\d+)'
The -P
option enables Perl Compatible Regular Expressions. See man 3 pcrepattern
or man
3 pcresyntax
.
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
I'd recommend Charles Proxy - you can choose to slowdown individual sites, also has a whole bunch of HTTP inspection tools.
Edit:
As of June 2014, Chrome now has the ability to do this natively in DevTools - you'll need Chrome 38 though.
The option is accessible from the Network tab via a drop down at the end of the toolbar.
Set / change / reset the MySQL root password on Ubuntu Linux. Enter the following lines in your terminal.
sudo /etc/init.d/mysql stop
Start the mysqld
configuration: sudo mysqld --skip-grant-tables &
In some cases, you've to create the /var/run/mysqld
first:
sudo mkdir -v /var/run/mysqld && sudo chown mysql /var/run/mysqld
sudo service mysql start
mysql -u root mysql
Replace YOURNEWPASSWORD
with your new password:
UPDATE
mysql.user
SET
Password = PASSWORD('YOURNEWPASSWORD')
WHERE
User = 'root';
FLUSH PRIVILEGES;
exit;
Note: on some versions, if
password
column doesn't exist, you may want to try:
UPDATE user SET authentication_string=password('YOURNEWPASSWORD') WHERE user='root';
Note: This method is not regarded as the most secure way of resetting the password, however, it works.
References:
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.
Hope that helps.
If you are using ES6 Classes and ControllerAs
syntax, you need to do something slightly different.
See the snippet below and note that vm
is the ControllerAs
value of the parent Controller as used in the parent HTML
myApp.directive('name', function() {
return {
// no scope definition
link : function(scope, element, attrs, ngModel) {
scope.vm.func(...)
This is a bug in Firefox:
https://bugzilla.mozilla.org/show_bug.cgi?id=356558
Try this workaround:
<iframe src="webpage2.html?var=xxx" id="theframe"></iframe>
<script>
var _theframe = document.getElementById("theframe");
_theframe.contentWindow.location.href = _theframe.src;
</script>
git clone ssh://[email protected]/home/user/private/repos/project_hub.git $(pwd)
Try this:
SELECT *
FROM (
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users
) a
WHERE firstlast = "Bob Michael Jones"
There is a CSS unit called viewport height / viewport width.
Example
.mainbody{height: 100vh;}
similarly html,body{width: 100vw;}
or 90vh = 90% of the viewport height.
**IE9+ and most modern browsers.
You can use
string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
I do this for a print spooler program that I wrote, it's just a shell script:
#!/bin/sh
if ps -ef | grep -v grep | grep doctype.php ; then
exit 0
else
/home/user/bin/doctype.php >> /home/user/bin/spooler.log &
#mailing program
/home/user/bin/simplemail.php "Print spooler was not running... Restarted."
exit 0
fi
It runs every two minutes and is quite effective. I have it email me with special information if for some reason the process is not running.
You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.
I also had some problems after updating Xcode.
I fixed it by opening Xcode Preferences (?+,), going to Accounts → View Details. Then select all provisioning profiles and delete them with backspace (note: they can't be removed in Xcode 7.2). Restart Xcode, else the list doesn't seem to update properly.
Now click the Download all button, and you should have all provisioning profiles that you defined in the Member center back in Xcode. Don't worry about the Xcode-generated ones (Prefixed with XC:
), Xcode will regenerate them if necessary. Restart Xcode again.
Now go to the Code Signing section in your Build Settings and select the correct profile and cert.
Why this happens at all? No idea... I gave up on understanding Apple's policies regarding app signing.
This will keep the right aspect ratio.
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken
to return either Optional.empty()
instead of null, or Optional.of(myReturnObject)
, where myReturnObject
is your chicken
.
Then you can call getChicken()
and if it would return Optional.empty()
the orElse(fallback)
would give you whatever the fallback would be, in your case the second method.
I like Linq and to make it exit on first mismatch you can do this
string str = '0129834X33';
bool isAllDigits = !str.Any( ch=> ch < '0' || ch > '9' );
Try this:
var momentObj = $("#start_ts").datepicker("getDate");
var yourDate = momentObj.format('L');
For localhost / wampserver 3 we can set sql-mode = user_mode to remove this error:
click on wamp icon -> MySql -> MySql Setting -> sql-mode -> user_mode
then restart wamp or apache
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
You must get directory right path of program(node.js in program files).
such as
and use "npm install -g phonegap"
Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html
For example: /lib/systemd/system/[email protected]
looks something like this:
[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service
[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0
So, you may start it like:
$ systemctl start [email protected]
$ systemctl start [email protected]
For systemd it will different instances:
$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
Loaded: loaded (/lib/systemd/system/[email protected]; static)
Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
Main PID: 5443 (agetty)
CGroup: name=systemd:/system/[email protected]/ttyUSB0
+ 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600
It also mean great possibility enable and disable it separately.
Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]
Seems it will be available in C++14:
https://en.wikipedia.org/wiki/C%2B%2B14#Runtime-sized_one_dimensional_arrays
Update: It did not make it into C++14.
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
Here is what is did it with string
export function withoutRange(number) {
const str = String(number);
const dotPosition = str.indexOf('.');
if (dotPosition > 0) {
const length = str.substring().length;
const end = length > 3 ? 3 : length;
return str.substring(0, dotPosition + end);
}
return str;
}
Environment.getExternalStorageDirectory()
will NOT return path to micro SD card Storage.
how to get file path from sd card in android
By sd card, I am assuming that, you meant removable micro SD card.
In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type)
in Context
Class that allows apps to store data/files in micro SD cards.
Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.
Environment.getExternalStorageDirectory()
was there from API level 1
getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).
But note that,
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using
getExternalStorageState(File)
.There is no security enforced with these files. For example, any application holding
WRITE_EXTERNAL_STORAGE
can write to these files.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
Install PAR::Packer from CPAN (it is free) and use pp utility.
The above examples aren't simply written for Swift 3.0+
Update - Swift 3.0+ - Convert Date To String
let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like
var dateString = dateFormatter.string(from: date)
There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.
There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.
Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.
The getFilesDir()
somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
You need to replace open
with urllib.urlopen or urllib2.urlopen.
e.g.
import csv
import urllib2
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
for row in cr:
print row
This would output the following
Year,City,Sport,Discipline,NOC,Event,Event gender,Medal
1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver
1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold
...
The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) see below.
public static final long SECOND_IN_MILLIS = 1000;
public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
You could cast int but I would recommend using long.
I'm not an expert but it sounds to me that this is something you could only do if you built the browser yourself - ie, not something done in a web page. I'm not sure that the sources for Chrome are publicly available (I think they are though), but the sources are what you'd probably need to change for this.
Try this:
UPDATE YourTable
SET Col2 = RIGHT(Col1,LEN(Col1)-CHARINDEX('/',Col1))
The difference is that std::make_shared
performs one heap-allocation, whereas calling the std::shared_ptr
constructor performs two.
std::shared_ptr
manages two entities:
std::make_shared
performs a single heap-allocation accounting for the space necessary for both the control block and the data. In the other case, new Obj("foo")
invokes a heap-allocation for the managed data and the std::shared_ptr
constructor performs another one for the control block.
For further information, check out the implementation notes at cppreference.
NOTE (2019/08/30): This is not a problem since C++17, due to the changes in the evaluation order of function arguments. Specifically, each argument to a function is required to fully execute before evaluation of other arguments.
Since the OP seem to be wondering about the exception-safety side of things, I've updated my answer.
Consider this example,
void F(const std::shared_ptr<Lhs> &lhs, const std::shared_ptr<Rhs> &rhs) { /* ... */ }
F(std::shared_ptr<Lhs>(new Lhs("foo")),
std::shared_ptr<Rhs>(new Rhs("bar")));
Because C++ allows arbitrary order of evaluation of subexpressions, one possible ordering is:
new Lhs("foo"))
new Rhs("bar"))
std::shared_ptr<Lhs>
std::shared_ptr<Rhs>
Now, suppose we get an exception thrown at step 2 (e.g., out of memory exception, Rhs
constructor threw some exception). We then lose memory allocated at step 1, since nothing will have had a chance to clean it up. The core of the problem here is that the raw pointer didn't get passed to the std::shared_ptr
constructor immediately.
One way to fix this is to do them on separate lines so that this arbitary ordering cannot occur.
auto lhs = std::shared_ptr<Lhs>(new Lhs("foo"));
auto rhs = std::shared_ptr<Rhs>(new Rhs("bar"));
F(lhs, rhs);
The preferred way to solve this of course is to use std::make_shared
instead.
F(std::make_shared<Lhs>("foo"), std::make_shared<Rhs>("bar"));
std::make_shared
Quoting Casey's comments:
Since there there's only one allocation, the pointee's memory cannot be deallocated until the control block is no longer in use. A
weak_ptr
can keep the control block alive indefinitely.
weak_ptr
s keep the control block alive?There must be a way for weak_ptr
s to determine if the managed object is still valid (eg. for lock
). They do this by checking the number of shared_ptr
s that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr
count and the weak_ptr
count both hit 0.
std::make_shared
Since std::make_shared
makes a single heap-allocation for both the control block and the managed object, there is no way to free the memory for control block and the managed object independently. We must wait until we can free both the control block and the managed object, which happens to be until there are no shared_ptr
s or weak_ptr
s alive.
Suppose we instead performed two heap-allocations for the control block and the managed object via new
and shared_ptr
constructor. Then we free the memory for the managed object (maybe earlier) when there are no shared_ptr
s alive, and free the memory for the control block (maybe later) when there are no weak_ptr
s alive.
I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617
The approach with:
<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>
and with
<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>
Only works if the person who clicked on your link have your number on their contact list.
Since not everybody will have it, the other solution is to use Whatsapp API like this:
<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>
More details on this API here: https://www.whatsapp.com/faq/en/general/26000030
And observations on how to use it here: https://stackoverflow.com/a/43357241/3958617
I also faced a similar issue, the problem was the form was inside a folder and the file .aspx.designer.cs
I had the namespace referencing specifically to that directory; which caused the error to appear in several components:
El nombre no existe en el contexto actual
This in your case, a possible solution is to leave the namespace line of the Members_Jobs.aspx.designer.cs
file specified globally, ie change this
namespace stman.Members {
For this
namespace stman {
It's what helped me solve the problem.
I hope to be helpful
CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats
Good luck!
In most versions of the JDK the two versions will be the same:
String s = new String("silly");
String s = "No longer silly";
Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.
To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.
I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.
UPDATE: I was wrong! Based on a down vote and comment attached I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.
As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).
Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
And then use this in your code via:
WriteLine("{0}", DateTimeUtils.Tomorrow)
I use moment along with new Date to handle cases of undefined
data values:
const date = moment(new Date("2016-10-19"));
because of: moment(undefined).isValid() == true
where as the better way: moment(new Date(undefined)).isValid() == false
Replication is not very hard to create.
Here's some good tutorials:
http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication
Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):
This way, you will avoid errors.
For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.
You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.
NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).
I would recommend to monitor your servers to make sure everything is fine.
Let me know if you need additional help
If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:
public static String TrimEnd(this String str, int count)
{
return str.Substring(0, str.Length - count);
}
and call it:
string oldString = "...Hello!";
string newString = oldString.Trim(1); //returns "...Hello"
or chained:
string newString = oldString.Substring(3).Trim(1); //returns "Hello"
A little more pythonic way I think would be:
timestr = '00:04:23'
ftr = [3600,60,1]
sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
Output is 263Sec.
I would be interested to see if anyone could simplify it further.
Continuum Analytics now provides instructions on how to setup Anaconda with various IDEs including Pycharm here. However, with Pycharm 5.0.1 running on Unbuntu 15.10 Project Interpreter settings were found via the File | Settings and then under the Project branch of the treeview on the Settings dialog.
Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
Here's other way of getting Zscore using custom function:
In [6]: import pandas as pd; import numpy as np
In [7]: np.random.seed(0) # Fixes the random seed
In [8]: df = pd.DataFrame(np.random.randn(5,3), columns=["randomA", "randomB","randomC"])
In [9]: df # watch output of dataframe
Out[9]:
randomA randomB randomC
0 1.764052 0.400157 0.978738
1 2.240893 1.867558 -0.977278
2 0.950088 -0.151357 -0.103219
3 0.410599 0.144044 1.454274
4 0.761038 0.121675 0.443863
## Create custom function to compute Zscore
In [10]: def z_score(df):
....: df.columns = [x + "_zscore" for x in df.columns.tolist()]
....: return ((df - df.mean())/df.std(ddof=0))
....:
## make sure you filter or select columns of interest before passing dataframe to function
In [11]: z_score(df) # compute Zscore
Out[11]:
randomA_zscore randomB_zscore randomC_zscore
0 0.798350 -0.106335 0.731041
1 1.505002 1.939828 -1.577295
2 -0.407899 -0.875374 -0.545799
3 -1.207392 -0.463464 1.292230
4 -0.688061 -0.494655 0.099824
In [12]: from scipy.stats import zscore
In [13]: df.apply(zscore) # (Credit: Manuel)
Out[13]:
randomA randomB randomC
0 0.798350 -0.106335 0.731041
1 1.505002 1.939828 -1.577295
2 -0.407899 -0.875374 -0.545799
3 -1.207392 -0.463464 1.292230
4 -0.688061 -0.494655 0.099824
var clientHeight = document.getElementById('myDiv').clientHeight;
or
var offsetHeight = document.getElementById('myDiv').offsetHeight;
clientHeight
includes padding.
offsetHeight
includes padding, scrollBar and borders.
As simple as 80 lines:
package windows.prefs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IniFile {
private Pattern _section = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );
private Pattern _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );
private Map< String,
Map< String,
String >> _entries = new HashMap<>();
public IniFile( String path ) throws IOException {
load( path );
}
public void load( String path ) throws IOException {
try( BufferedReader br = new BufferedReader( new FileReader( path ))) {
String line;
String section = null;
while(( line = br.readLine()) != null ) {
Matcher m = _section.matcher( line );
if( m.matches()) {
section = m.group( 1 ).trim();
}
else if( section != null ) {
m = _keyValue.matcher( line );
if( m.matches()) {
String key = m.group( 1 ).trim();
String value = m.group( 2 ).trim();
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
_entries.put( section, kv = new HashMap<>());
}
kv.put( key, value );
}
}
}
}
}
public String getString( String section, String key, String defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return kv.get( key );
}
public int getInt( String section, String key, int defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Integer.parseInt( kv.get( key ));
}
public float getFloat( String section, String key, float defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Float.parseFloat( kv.get( key ));
}
public double getDouble( String section, String key, double defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Double.parseDouble( kv.get( key ));
}
}
I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .
I hope you this concept.
I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:
public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {
// Vars
private LayoutInflater mInflater;
public GenericArrayAdapter(Context context, ArrayList<T> objects) {
super(context, 0, objects);
init(context);
}
// Headers
public abstract void drawText(TextView textView, T object);
private void init(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
drawText(vh.textView, getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
private ViewHolder(View rootView) {
textView = (TextView) rootView.findViewById(android.R.id.text1);
}
}
}
and here your adapter (example):
public class SizeArrayAdapter extends GenericArrayAdapter<Size> {
public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
super(context, objects);
}
@Override public void drawText(TextView textView, Size object) {
textView.setText(object.getName());
}
}
and finally, how to initialize it:
ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);
I've created a Gist with TextView layout gravity customizable ArrayAdapter:
This could help:
public static String getCorporateID(String fileName) {
String corporateId = null;
try {
corporateId = fileName.substring(0, fileName.indexOf("_"));
// System.out.println(new Date() + ": " + "Corporate:
// "+corporateId);
return corporateId;
} catch (Exception e) {
corporateId = null;
e.printStackTrace();
}
return corporateId;
}
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
Pretty Diff will beautify (pretty print) JavaScript in a way that conforms to JSLint and JSHint white space algorithms.
You seem to misunderstand the box model - in CSS you provide points for the top and left and then width and height - these are all that are needed for a box to be placed with exact measurements.
The width
property is what your C-D
is, but it is also what A-B
is. If you omit it, the div will not have a defined width and the width will be defined by its contents.
Update (following the comments on the question:
Add a border-bottom-style: none;
to your CSS to remove this style from the bottom only.
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
What it the underlying need?
It arises from the fact that, ultimately, computers represent, internally, numbers in binary format. That leads, inevitably, to rounding errors.
Consider this:
0.1 (decimal, or "base 10") = .00011001100110011... (binary, or "base 2")
The above ellipsis [...] means 'infinite'. If you look at it carefully, there is an infinite repeating pattern (='0011')
So, at some point the computer has to round that value. This leads to accumulation errors deriving from the repeated use of numbers that are inexactly stored.
Say that you want to store financial amounts (which are numbers that may have a fractional part). First of all, you cannot use integers obviously (integers don't have a fractional part).
From a purely mathematical point of view, the natural tendency would be to use a float
. But, in a computer, floats have the part of a number that is located after a decimal point - the "mantissa" - limited. That leads to rounding errors.
To overcome this, computers offer specific datatypes that limit the binary rounding error in computers for decimal numbers. These are the data type that
should absolutely be used to represent financial amounts. These data types typically go by the name of Decimal
. That's the case in C#, for example. Or, DECIMAL
in most databases.
Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.
Super late to this question, but in case anyone wants a version that handles the amount of splits you want to get.....
-- Split a string into a table using a delimiter and a limit
string.split = function(str, pat, limit)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t, cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
if limit ~= nil and limit <= #t then
break
end
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
This worked for me:
for n in tf.get_default_graph().as_graph_def().node:
print('\n',n)
This seems to be old post but still I wanted to share how this issue got fixed for me.
For users, who do not have admin access and when they open a command prompt, it runs under the user privilege. It means, you may have path like C:\Users\
so when trying C:\Users\XYZ>mvn --version , it actually search the JAVA_HOME path from user variables not system variables in Environment Variables.
So, In order to fix this, we need to create a environment variable for JAVA_HOME in user variables.
Hope, this helps someone.
You can simply use substring
:
if(fieldName.endsWith(","))
{
fieldName = fieldName.substring(0,fieldName.length() - 1);
}
Make sure to reassign your field after performing substring
as Strings are immutable in java
Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.
The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false}
just does not work.
The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.
I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.
BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.
You can use typeof
, like this:
if (typeof something != "undefined") {
// ...
}
put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t
<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string);
echo $string = str_replace( array( '-', '.' ), '', $string);
?>
I think the easiest way here is to preload the json or load it once on$dirty
and then the filter search will take care of the rest. This'll save you the extra http calls and its much faster with preloaded data. Memory will hurt, but its worth it.
Please note that you can use view.setZ(float)
starting from API level 21. Here you can find more info.
You can use textContent attribute to retrieve data from a label.
<script>
var datas = document.getElementById("excel-data-div").textContent;
</script>
<label id="excel-data-div" style="display: none;">
Sample text
</label>
Update all changes you made:
git add -u
The deleted files should change from unstaged (usually red color) to staged (green). Then commit to remove the deleted files:
git commit -m "note"
Unfortunately, strptime()
can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:
Support for the
%Z
directive is based on the values contained intzname
and whetherdaylight
is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
strftime()
doesn't officially support %z
.
You are stuck with python-dateutil
to support timezone parsing, I am afraid.
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
I had a similar problem and it had to do with the libraries referenced by the java build path; I was referencing libraries that didn't exist anymore when I did an update. When I removed these references, by project started running again.
The libraries are listed under the Java Build Path in the project properties window.
Hope this helps.
Ideally, you should create a self-managed certificate authority. Start with generating a key pair:
ssh-keygen -f cert_signer
Then sign each server's public host key:
ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub
This generates a signed public host key:
/etc/ssh/ssh_host_rsa_key-cert.pub
In /etc/ssh/sshd_config
, point the HostCertificate
to this file:
HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub
Restart the sshd service:
service sshd restart
Then on the SSH client, add the following to ~/.ssh/known_hosts
:
@cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/
The above contains:
@cert-authority
*.example.com
cert_signer.pub
The cert_signer
public key will trust any server whose public host key is signed by the cert_signer
private key.
Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).
For more details, see this wiki page.
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
I like the idea of using a directive for this:
.directive('stopEvent', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind('click', function (e) {
e.stopPropagation();
});
}
};
});
Then use the directive like:
<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
<img src="http://some_src" ng-click="nextImage()" stop-event/>
</div>
If you wanted, you could make this solution more generic like this answer to a different question: https://stackoverflow.com/a/14547223/347216
The duplicate can be achieved by CTRL+C and CTRL+V with cursor in the line without nothing selected.
I've had this problem after installing the genymotion (another android amulator) plugin. A closer inspection reveled that gradle needs SDK tools version 19.1.0 in order to run (I had 19.0.3 previously).
To fix it, I had to edit build.gradle
and under android
I changed to: buildToolsVersion 19.1.0
Then I had to rebuild again, and the error was gone.
There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
}
_x000D_
, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside
declare module '*.jpg';
declare module '*.png';
_x000D_
,then restart dev-server. After these steps we can import and use images like in code bellow
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';
const HelloWorld = () => (
<>
<h1 className="main">React TypeScript Starter</h1>
<img src={image} alt="some example image" />
</>
);
export default HelloWorld;
_x000D_
Works in typescript and also in javacript,just change extension from .ts to .js
Cheers.
If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:
String myString=
new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));
Note that the getClassLoader() method is missing on some of the other examples.
I also faced the same issue while running JUnit test. I resolved this by putting the annotation @Test just above the main test function.
:set go=a
ggVG
See :help go-a
:
'a' Autoselect: If present, then whenever VISUAL mode is started,
or the Visual area extended, Vim tries to become the owner of
the windowing system's global selection. This means that the
Visually highlighted text is available for pasting into other
applications as well as into Vim itself. When the Visual mode
ends, possibly due to an operation on the text, or when an
application wants to paste the selection, the highlighted text
is automatically yanked into the "* selection register.
Thus the selection is still available for pasting into other
applications after the VISUAL mode has ended.
If not present, then Vim won't become the owner of the
windowing system's global selection unless explicitly told to
by a yank or delete operation for the "* register.
The same applies to the modeless selection.
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
console.log(array[i]);
}
var fs = require('fs');
fs.readFile('file.txt', function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
console.log(array[i]);
}
});
You have just created an empty integer array. The array guess
does not contain anything to my knowledge. The rest you should work out to get better.
Suppose you simply don't know the size of the data.frame in advance. It can well be a few rows, or a few millions. You need to have some sort of container, that grows dynamically. Taking in consideration my experience and all related answers in SO I come with 4 distinct solutions:
rbindlist
to the data.frame
Use data.table
's fast set
operation and couple it with manually doubling the table when needed.
Use RSQLite
and append to the table held in memory.
data.frame
's own ability to grow and use custom environment (which has reference semantics) to store the data.frame so it will not be copied on return.
Here is a test of all the methods for both small and large number of appended rows. Each method has 3 functions associated with it:
create(first_element)
that returns the appropriate backing object with first_element
put in.
append(object, element)
that appends the element
to the end of the table (represented by object
).
access(object)
gets the data.frame
with all the inserted elements.
rbindlist
to the data.frameThat is quite easy and straight-forward:
create.1<-function(elems)
{
return(as.data.table(elems))
}
append.1<-function(dt, elems)
{
return(rbindlist(list(dt, elems),use.names = TRUE))
}
access.1<-function(dt)
{
return(dt)
}
data.table::set
+ manually doubling the table when needed.I will store the true length of the table in a rowcount
attribute.
create.2<-function(elems)
{
return(as.data.table(elems))
}
append.2<-function(dt, elems)
{
n<-attr(dt, 'rowcount')
if (is.null(n))
n<-nrow(dt)
if (n==nrow(dt))
{
tmp<-elems[1]
tmp[[1]]<-rep(NA,n)
dt<-rbindlist(list(dt, tmp), fill=TRUE, use.names=TRUE)
setattr(dt,'rowcount', n)
}
pos<-as.integer(match(names(elems), colnames(dt)))
for (j in seq_along(pos))
{
set(dt, i=as.integer(n+1), pos[[j]], elems[[j]])
}
setattr(dt,'rowcount',n+1)
return(dt)
}
access.2<-function(elems)
{
n<-attr(elems, 'rowcount')
return(as.data.table(elems[1:n,]))
}
RSQLite
solutionThis is basically copy&paste of Karsten W. answer on similar thread.
create.3<-function(elems)
{
con <- RSQLite::dbConnect(RSQLite::SQLite(), ":memory:")
RSQLite::dbWriteTable(con, 't', as.data.frame(elems))
return(con)
}
append.3<-function(con, elems)
{
RSQLite::dbWriteTable(con, 't', as.data.frame(elems), append=TRUE)
return(con)
}
access.3<-function(con)
{
return(RSQLite::dbReadTable(con, "t", row.names=NULL))
}
data.frame
's own row-appending + custom environment.create.4<-function(elems)
{
env<-new.env()
env$dt<-as.data.frame(elems)
return(env)
}
append.4<-function(env, elems)
{
env$dt[nrow(env$dt)+1,]<-elems
return(env)
}
access.4<-function(env)
{
return(env$dt)
}
For convenience I will use one test function to cover them all with indirect calling. (I checked: using do.call
instead of calling the functions directly doesn't makes the code run measurable longer).
test<-function(id, n=1000)
{
n<-n-1
el<-list(a=1,b=2,c=3,d=4)
o<-do.call(paste0('create.',id),list(el))
s<-paste0('append.',id)
for (i in 1:n)
{
o<-do.call(s,list(o,el))
}
return(do.call(paste0('access.', id), list(o)))
}
Let's see the performance for n=10 insertions.
I also added a 'placebo' functions (with suffix 0
) that don't perform anything - just to measure the overhead of the test setup.
r<-microbenchmark(test(0,n=10), test(1,n=10),test(2,n=10),test(3,n=10), test(4,n=10))
autoplot(r)
For 1E5 rows (measurements done on Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz):
nr function time
4 data.frame 228.251
3 sqlite 133.716
2 data.table 3.059
1 rbindlist 169.998
0 placebo 0.202
It looks like the SQLite-based sulution, although regains some speed on large data, is nowhere near data.table + manual exponential growth. The difference is almost two orders of magnitude!
If you know that you will append rather small number of rows (n<=100), go ahead and use the simplest possible solution: just assign the rows to the data.frame using bracket notation and ignore the fact that the data.frame is not pre-populated.
For everything else use data.table::set
and grow the data.table exponentially (e.g. using my code).
By pid:
pgrep [pid] >/dev/null
By name:
pgrep -u [user] -x [name] >/dev/null
"-x" means "exact match".
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}
Whenever possible, you should avoid parsing the output of ls
(see Greg's wiki on the subject). Basically, the output of ls
will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */
, what happens is that the shell expands */
to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d
, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls
command isn't doing anything useful!
Well, ok, it is doing one thing that's useful: if there are no subdirectories, */
will get left as is, ls
will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).
The cleaner way to make an array of subdirectory names is to use the glob (*/
) without passing it to ls
. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):
shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}" # Note double-quotes to avoid extra parsing of funny characters in filenames
If you want to print an error message if there are no subdirectories, you're better off doing it yourself:
if (( ${#array[@]} == 0 )); then
echo "No subdirectories found" >&2
fi
You are getting that error because the keytool
executable is under the bin
directory, not the lib
directory in your example. And you will need to add the location of your keystore
as well in the command line. There is a pretty good reference to all of this here - Jrun Help / Import certificates | Certificate stores | ColdFusion
The default truststore is the JRE's cacerts file. This file is typically located in the following places:
Server Configuration:
cf_root/runtime/jre/lib/security/cacerts
Multiserver/J2EE on JRun 4 Configuration:
jrun_root/jre/lib/security/cacerts
Sun JDK installation:
jdk_root/jre/lib/security/cacerts
Consult documentation for other J2EE application servers and JVMs
The keytool is part of the Java SDK and can be found in the following places:
Server Configuration:
cf_root/runtime/bin/keytool
Multiserver/J2EE on JRun 4 Configuration:
jrun_root/jre/bin/keytool
Sun JDK installation:
jdk_root/bin/keytool
Consult documentation for other J2EE application servers and JVMs
So if you navigate to the directory where the keytool
executable is located your command line would look something like this:
keytool -list -v -keystore JAVA_HOME\jre\lib\security\cacert -storepass changeit
You will need to supply pathing information depending on where you run the keytool command from and where your certificate file resides.
Also, be sure you are updating the correct cacerts file that ColdFusion is using. In case you have more than one JRE installed on that server. You can verify the JRE ColdFusion is using from the administrator under the 'System Information'. Look for the Java Home line.
Maybe something like this, where you could select more than one element if you'd like?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
I set permissions to:
# Set all files and directories user and group to wp-user
chown wp-user:wp-user -R *
# Set uploads folder user and group to www-data
chown www-data:www-data -R wp-content/uploads/
# Set all directories permissions to 755
find . -type d -exec chmod 755 {} \;
# Set all files permissions to 644
find . -type f -exec chmod 644 {} \;
In my case I created a specific user for WordPress which is different from the apache default user that prevent access from the web to those files owned by that user.
Then it gives permission to apache user to handle the upload folder and finally set secure enough file and folder permissions.
EDITED
If you're using W3C Total Cache you should do the next also:
rm -rf wp-content/cache/config
rm -rf wp-content/cache/object
rm -rf wp-content/cache/db
rm -rf wp-content/cache/minify
rm -rf wp-content/cache/page_enhanced
Then it'll work!
EDITED
After a while developing WordPress sites I'd recommend different file permissions per environment:
In production, I wouldn't give access to users to modify the filesystem, I'll only allow them to upload resources and give access to some plugins specific folders to do backups, etc. But managing projects under Git and using deploy keys on the server, it isn't good update plugins on staging nor production. I leave here the production file setup:
# Set uploads folder user and group to www-data
chown www-data:www-data -R wp-content/uploads/
www-data:www-data = apache or nginx user and group
Staging will share the same production permissions as it should be a clone of it.
Finally, development environment will have access to update plugins, translations, everything...
# Set uploads folder user and group to www-data
chown www-data:www-data -R wp-content/
# Set uploads folder user and group to www-data
chown your-user:root-group -R wp-content/themes
# Set uploads folder user and group to www-data
chown your-user:root-group -R wp-content/plugins/your-plugin
www-data:www-data = apache or nginx user and group your-user:root-group = your current user and the root group
These permissions will give you access to develop under themes
and your-plugin
folder without asking permission. The rest of the content will be owned by the Apache or Nginx user to allow WP to manage the filesystem.
Before creating a git repo first run these commands:
# Set all directories permissions to 755
find . -type d -exec chmod 755 {} \;
# Set all files permissions to 644
find . -type f -exec chmod 644 {} \;
Simply use the "utf-8-sig" codec:
fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")
That gives you a unicode
string without the BOM. You can then use
s = u.encode("utf-8")
to get a normal UTF-8 encoded string back in s
. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:
import os, sys, codecs
BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)
path = sys.argv[1]
with open(path, "r+b") as fp:
chunk = fp.read(BUFSIZE)
if chunk.startswith(codecs.BOM_UTF8):
i = 0
chunk = chunk[BOMLEN:]
while chunk:
fp.seek(i)
fp.write(chunk)
i += len(chunk)
fp.seek(BOMLEN, os.SEEK_CUR)
chunk = fp.read(BUFSIZE)
fp.seek(-BOMLEN, os.SEEK_CUR)
fp.truncate()
It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.
As for guessing the encoding, then you can just loop through the encoding from most to least specific:
def decode(s):
for encoding in "utf-8-sig", "utf-16":
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode("latin-1") # will always work
An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None
instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).
Using jQuery: $('#gift-close').trigger('click');
Using JavaScript: document.getElementById('gift-close').click();
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
Use otool:
otool -TV your.dylib
OR
nm -g your.dylib
For people in the future seeing this, postgres
is in the /usr/lib/postgresql/10/bin
on my Ubuntu server.
I added it to the PATH in my .bashrc file, and add this line at the end
PATH=$PATH:/usr/lib/postgresql/10/bin
then on the command line
$> source ./.bashrc
I refreshed my bash environment. Now I can use postgres -D /wherever
from any directory