After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
I vote for the dictionary.
I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.
Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)
If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:
data<- rbind(c(480, 780, 431, 295, 670, 360, 190),
c(720, 350, 377, 255, 340, 615, 345),
c(460, 480, 179, 560, 60, 735, 1260),
c(220, 240, 876, 789, 820, 100, 75))
a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))
data <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
library(ggplot2)
ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +
geom_bar(stat = "identity") +
opts(legend.position = "none")
Setting the warning level to 2 suppresses this messages. Don't know if it's the best solution as it also suppresses useful warnings.
Your plunker is firing off
angular.element(document.getElementById('MyController')).scope().myfunction('test');
Before anything is rendered.
You can verify that by wrapping it in a timeout
setTimeout(function() {
angular.element(document.getElementById('MyController')).scope().myfunction('test');
}, 1000);
You also need to acutally add an ID to your div.
<div ng-app='MyModule' ng-controller="MyController" id="MyController">
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
The method show()
must be called from the User-Interface (UI) thread, while doInBackground()
runs on different thread which is the main reason why AsyncTask
was designed.
You have to call show()
either in onProgressUpdate()
or in onPostExecute()
.
For example:
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
@Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
}
}
You map your dispatcher on *.do:
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
but your controller is mapped on an url without .do:
@RequestMapping("/editPresPage")
Try changing this to:
@RequestMapping("/editPresPage.do")
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
for(int i = 0; deletedtrs_array.length(); i++){
JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
I run into the same problem and wrote a little shared-memory utility class to work around it.
I'm using multiprocessing.RawArray
(lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.
With the solution I get speedups by a factor of approx 3 on a quad-core i7.
Here's the code: Feel free to use and improve it, and please report back any bugs.
'''
Created on 14.05.2013
@author: martin
'''
import multiprocessing
import ctypes
import numpy as np
class SharedNumpyMemManagerError(Exception):
pass
'''
Singleton Pattern
'''
class SharedNumpyMemManager:
_initSize = 1024
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SharedNumpyMemManager, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.lock = multiprocessing.Lock()
self.cur = 0
self.cnt = 0
self.shared_arrays = [None] * SharedNumpyMemManager._initSize
def __createArray(self, dimensions, ctype=ctypes.c_double):
self.lock.acquire()
# double size if necessary
if (self.cnt >= len(self.shared_arrays)):
self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)
# next handle
self.__getNextFreeHdl()
# create array in shared memory segment
shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))
# convert to numpy array vie ctypeslib
self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)
# do a reshape for correct dimensions
# Returns a masked array containing the same data, but with a new shape.
# The result is a view on the original array
self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)
# update cnt
self.cnt += 1
self.lock.release()
# return handle to the shared memory numpy array
return self.cur
def __getNextFreeHdl(self):
orgCur = self.cur
while self.shared_arrays[self.cur] is not None:
self.cur = (self.cur + 1) % len(self.shared_arrays)
if orgCur == self.cur:
raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')
def __freeArray(self, hdl):
self.lock.acquire()
# set reference to None
if self.shared_arrays[hdl] is not None: # consider multiple calls to free
self.shared_arrays[hdl] = None
self.cnt -= 1
self.lock.release()
def __getArray(self, i):
return self.shared_arrays[i]
@staticmethod
def getInstance():
if not SharedNumpyMemManager._instance:
SharedNumpyMemManager._instance = SharedNumpyMemManager()
return SharedNumpyMemManager._instance
@staticmethod
def createArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)
@staticmethod
def getArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)
@staticmethod
def freeArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)
# Init Singleton on module load
SharedNumpyMemManager.getInstance()
if __name__ == '__main__':
import timeit
N_PROC = 8
INNER_LOOP = 10000
N = 1000
def propagate(t):
i, shm_hdl, evidence = t
a = SharedNumpyMemManager.getArray(shm_hdl)
for j in range(INNER_LOOP):
a[i] = i
class Parallel_Dummy_PF:
def __init__(self, N):
self.N = N
self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)
self.pool = multiprocessing.Pool(processes=N_PROC)
def update_par(self, evidence):
self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))
def update_seq(self, evidence):
for i in range(self.N):
propagate((i, self.arrayHdl, evidence))
def getArray(self):
return SharedNumpyMemManager.getArray(self.arrayHdl)
def parallelExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_par(5)
print(pf.getArray())
def sequentialExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_seq(5)
print(pf.getArray())
t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")
print("Sequential: ", t1.timeit(number=1))
print("Parallel: ", t2.timeit(number=1))
Using __and__
attribute method also works.
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a).__and__(set(b))
set([5])
or simply
>>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5]))
set([5])
>>>
Some of the answers that are written here are pretty trivial (O(n^2) or sorting and traversing in O(NlogN)) and I'm assuming that is not what was expected in an interview for Microsoft. Obviously any answer above O(n) wasn't what they were looking for. The update states that there shouldn't be any helper data structures so any answer that has one (a hash table, tree, bit array or whatever) shouldn't be a valid solution.
If you can allocate additional memory then Jeff B's answer is probably easiest way to do it. I have a good answer for questions like these but the MAXINT needs to be bounded by the size of the array. (Example: An array of size 100 may contain any number between 1 and 100. Remove the dups as the original question)
The answer to this in O(n) time and O(1) memory is:
// FLAG ALL DUPS IN THE ORIGIN ARRAY
int maxNumInArray = findMaxNumInArray(arr);
int dup = findMinNumInArray(arr) - 1;
for (int i=0; i < arrLength; ++i) {
int seekIndex = arr[i] % (maxNumInArray+1);
if (arr[seekIndex] > maxNumInArray)
arr[i] = dup; // invalidate index
else
arr[seekIndex] = arr[seekIndex] + maxNumInArray;
}
// REMOVE EMPTY SPACES
int i = 0;
int j = arrLength(arr)-1;
while (i<j) {
while (arr[i] != dup)
++i;
while (arr[j] == dup)
--j;
swap(arr[i], arr[j]);
}
If you don't know the bounds my answer isn't useful but u can try and play with it. Oh, and this specific variation wont work with negative numbers but its not a problem to fix it.
Depending on your shell, you may be able to use the following syntax:
expr substr $string $position $length
So for your example:
TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`
Alternatively,
echo 'MOTEST' | cut -c1-5
or
echo 'MOTEST' | awk '{print substr($0,0,5)}'
You can use array.slice(0,1) // First index is removed and array is returned.
Keyboard(BT) commands can be passed through command prompt
open command prompt and write "adb shell input keyevent keycode"
examples:-
for "enter" write
adb shell input keyevent 23
up
adb shell input keyevent 19
down
adb shell input keyevent 20
left
adb shell input keyevent 21
right
adb shell input keyevent 22
keycode List:
0 --> "KEYCODE_0"
1 --> "KEYCODE_SOFT_LEFT"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "KEYCODE_MEDIA_PLAY_PAUSE"
86 --> "KEYCODE_MEDIA_STOP"
87 --> "KEYCODE_MEDIA_NEXT"
88 --> "KEYCODE_MEDIA_PREVIOUS"
89 --> "KEYCODE_MEDIA_REWIND"
90 --> "KEYCODE_MEDIA_FAST_FORWARD"
91 --> "KEYCODE_MUTE"
92 --> "KEYCODE_PAGE_UP"
93 --> "KEYCODE_PAGE_DOWN"
94 --> "KEYCODE_PICTSYMBOLS"
...
122 --> "KEYCODE_MOVE_HOME"
123 --> "KEYCODE_MOVE_END"
Suppose, this is your TAB and you want to disable it
<li class="" id="groups"><a data-toggle="tab" class="navuserli" href="#groups" aria-expanded="false">Groups</a></li>
So you can also disable this tab by adding dynamic css
$('#groups').css('pointer-events', 'none')
The volatile
and transient
modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.
The transient
modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null
for a reference type, and zero or false
for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient
means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient
-ness. Or they may ignore it.
(Note that the JLS permits a static
field to be declared as transient
. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)
The volatile
modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long
or double
fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.
1 - But not to local variables or parameters.
I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!
set /p choice= "Please Select one of the above options :"
echo '%choice%'
The space after =
is very important.
Assuming that Windows doesn't really know how to deal with TTC files (which I honestly find strange), you can "split" the combined fonts in an easy way if you use fontforge.
The steps are:
unzip "STHeiti Medium.ttc.zip"
).File > Open
).File > Generate Fonts...
.Repeat the steps of loading 4--6 for the other font and you will have your TTFs readily usable for you.
Note that I emphasized generating instead of saving above: saving the font will create a file in Fontforge's specific SFD format, which is probably useless to you, unless you want to develop fonts with Fontforge.
If you want to have a more programmatic/automatic way of manipulating fonts, then you might be interested in my answer to a similar (but not exactly the same) question.
Further comments: One reason why some people may be interested in performing the splitting mentioned above (or using a font converter after all) is to convert the fonts to web formats (like WOFF). That's great, but be careful to see if the license of the fonts that you are splitting/converting allows such wide redistribution.
Of course, for Free ("as in Freedom") fonts, you don't need to worry (and one of the most prominent licenses of such fonts is the OFL).
Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:
$(boot2docker shellinit)
I had tested these commands:
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>> boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)
...
>> $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>> docker info
Containers: 3
...
Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:
Create a named region,
Setup the dropdown in a cell.
There is a detailed explanation of the process HERE.
All you need is a check on the post side of things.
if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
$_REQUEST['type_id'] = null;
see http://en.wikipedia.org/wiki/Globally_unique_identifier
There is no guarantee that an alpha will actually be there.
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
There is also this one:
hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]
Why it works:
The &
calls to_proc
on the object, and passes it as a block to the method.
something {|i| i.foo }
something(&:foo)
Many of the other answers here do not take into account unicode characters (e.g. öäüß??îû??????? ). In this case you can use the following:
$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $string);
There's a strange class of characters in the range \x80-\x9F
(Just above the 7-bit ASCII range of characters) that are technically control characters, but over time have been misused for printable characters. If you don't have any problems with these, then you can use:
$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $string);
If you wish to also strip line feeds, carriage returns, tabs, non-breaking spaces, and soft-hyphens, you can use:
$string = preg_replace('/[\x00-\x1F\x7F-\xA0\xAD]/u', '', $string);
Note that you must use single quotes for the above examples.
If you wish to strip everything except basic printable ASCII characters (all the example characters above will be stripped) you can use:
$string = preg_replace( '/[^[:print:]]/', '',$string);
For reference see http://www.fileformat.info/info/charset/UTF-8/list.htm
Unfortunately, I had problem with Local SQL Server installed within Visual Studio and here many solutions didn't work out for me. All I have to do is to reset my Visual Studio, by going to:
Control Panel > Program & Features > Visual Studio Setup Launcher
and click on More button and choose Repair
After that I was able to access my Local SQL Server and work with local SQL Databases.
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
You may also try this one if you already configured AFNetworking in your project.
-(void)viewDidLoad{ // -- add connectivity notification --//
[[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(ReachabilityDidChangeNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];}
-(void)ReachabilityDidChangeNotification:(NSNotification *)notify
{
// -- NSLog(@"Reachability changed: %@", AFStringFromNetworkReachabilityStatus(status)); -- //
NSDictionary *userInfo =[notif userInfo];
AFNetworkReachabilityStatus status= [[userInfo valueForKey:AFNetworkingReachabilityNotificationStatusItem] intValue];
switch (status)
{
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
// -- Reachable -- //
// -- Do your stuff when internet connection is available -- //
[self getLatestStuff];
NSLog(@"Reachable");
break;
case AFNetworkReachabilityStatusNotReachable:
default:
// -- Not reachable -- //
// -- Do your stuff for internet connection not available -- //
NSLog(@"Not Reachable");
break;
}
}
Try this:
[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
express.static()
expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html
and use that.
Serving static files in Express documentation, or more detailed serve-static
documentation, including the default behavior of serving index.html
:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
You can use a bit of functionality that is already built in to the ant jar task.
If you go to The documentation for the ant jar task and scroll down to the "merging archives" section there's a snippet for including the all the *.class files from all the jars in you "lib/main" directory:
<jar destfile="build/main/checksites.jar">
<fileset dir="build/main/classes"/>
<restrict>
<name name="**/*.class"/>
<archives>
<zips>
<fileset dir="lib/main" includes="**/*.jar"/>
</zips>
</archives>
</restrict>
<manifest>
<attribute name="Main-Class" value="com.acme.checksites.Main"/>
</manifest>
</jar>
This Creates an executable jar file with a main class "com.acme.checksites.Main", and embeds all the classes from all the jars in lib/main.
It won't do anything clever in case of namespace conflicts, duplicates and things like that. Also, it will include all class files, also the ones that you don't use, so the combined jar file will be full size.
If you need more advanced things like that, take a look at like one-jar and jar jar links
public static bool IsPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(IsPropertyExist(settings, "Filename"));
Console.WriteLine(IsPropertyExist(settings, "Size"));
Output:
True
False
Try this one if you want to create a virtual column "age" within a select statement:
select brand, name, "10" as age from cars...
If nothing works, just create the adapter instance again with the new set of results or the updated set of results. Then you can see the new view.
XYZAdapter adbXzy = new XYZAdapter(context, 0, listData);
xyzListView.setAdapter(adbXzy);
adbXzy.notifyDataSetChanged();
ChangeDetectorRef.detectChanges()
is usually the most focused way of doing this. ApplicationRef.tick()
is usually too much of a sledgehammer approach.
To use ChangeDetectorRef.detectChanges()
, you'll need this at the top of your component:
import { ChangeDetectorRef } from '@angular/core';
... then, usually you alias that when you inject it in your constructor like this:
constructor( private cdr: ChangeDetectorRef ) { ... }
Then, in the appropriate place, you call it like this:
this.cdr.detectChanges();
Where you call ChangeDetectorRef.detectChanges()
can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges()
appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).
This works:
"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")
It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...
A bit late to the party, but there is actually a pretty simple way to do this:
The index sequence you are looking for can be expressed as the sum of two sequences:
0 1 2 3 ...
+1 -1 +1 -1 ...
Both are easy to express. The first one is just range(N)
. A sequence that toggles for each i
in that range is i % 2
. You can adjust the toggle by scaling and offsetting it:
i % 2 -> 0 1 0 1 ...
1 - i % 2 -> 1 0 1 0 ...
2 * (1 - i % 2) -> 2 0 2 0 ...
2 * (1 - i % 2) - 1 -> +1 -1 +1 -1 ...
The entire expression simplifies to i + 1 - 2 * (i % 2)
, which you can use to join the string almost directly:
result = ''.join(string[i + 1 - 2 * (i % 2)] for i in range(len(string)))
This will work only for an even-length string, so you can check for overruns using min
:
N = len(string)
result = ''.join(string[min(i + 1 - 2 * (i % 2), N - 1)] for i in range(N))
Basically a one-liner, doesn't require any iterators beyond a range over the indices, and some very simple integer math.
I cheated and used combination of multiple answers submitted by other people. I think this is pretty clear and straight forward piece of code. ip_validation
should return True
or False
. Also this answer only works for IPv4 addresses
import re
ip_match = re.match('^' + '[\.]'.join(['(\d{1,3})']*4) + '$', ip_input)
ip_validate = bool(ip_match)
if ip_validate:
ip_validate &= all(map(lambda n: 0 <= int(n) <= 255, ip_match.groups())
According to the documentation, $lookup can join only one external collection.
What you could do is to combine userInfo
and userRole
in one collection, as provided example is based on relational DB schema. Mongo is noSQL database - and this require different approach for document management.
Please find below 2-step query, which combines userInfo with userRole - creating new temporary collection used in last query to display combined data. In last query there is an option to use $out and create new collection with merged data for later use.
create collections
db.sivaUser.insert(
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userId" : "AD",
"userName" : "admin"
})
//"userinfo"
db.sivaUserInfo.insert(
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
})
//"userrole"
db.sivaUserRole.insert(
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
})
"join" them all :-)
db.sivaUserInfo.aggregate([
{$lookup:
{
from: "sivaUserRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$unwind:"$userRole"
},
{
$project:{
"_id":1,
"userId" : 1,
"phone" : 1,
"role" :"$userRole.role"
}
},
{
$out:"sivaUserTmp"
}
])
db.sivaUserTmp.aggregate([
{$lookup:
{
from: "sivaUser",
localField: "userId",
foreignField: "userId",
as: "user"
}
},
{
$unwind:"$user"
},
{
$project:{
"_id":1,
"userId" : 1,
"phone" : 1,
"role" :1,
"email" : "$user.email",
"userName" : "$user.userName"
}
}
])
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.
$array = new-object object[] 5
for($i=0; $i -lt $array.Length;$i++)
{
$array[$i] = $FALSE
}
If you don't mind using an external library, Lodash has lots of wonderful utilities
var people = [
{
"f_name":"john",
"l_name":"doe",
"sequence":"0",
"title":"president",
"url":"google.com",
"color":"333333"
},
{
"f_name":"michael",
"l_name":"goodyear",
"sequence":"0",
"title":"general manager",
"url":"google.com",
"color":"333333"
}
];
var sorted = _.sortBy(people, "l_name")
You can also sort by multiple properties. Here's a plunk showing it in action
Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions
if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection
how the query could look like:
-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))
here is the function:
ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
number int NOT NULL) AS
-- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer liste von elementen
BEGIN
-- Deklaration der Variablen
DECLARE @startpos int,
@endpos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000)
-- Startwerte festlegen
SET @textpos = 1
SET @leftover = ''
-- Loop 1
WHILE @textpos <= datalength(@list) / 2
BEGIN
--
SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)
--
SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings
--hochzählen der TestPosition
SET @textpos = @textpos + @chunklen
--start position 0 setzen
SET @startpos = 0
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)
-- Loop 2
WHILE @endpos > 0
BEGIN
--str ist der string welcher zwischen den [LEERZEICHEN] steht
SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1)
--wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF @str <> ''
INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)
-- start wird auf das letzte bekannte end gesetzt
SET @startpos = @endpos
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
END
-- Loop 2
-- dient dafür den letzten teil des strings zu selektieren
SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
END
-- Loop 1
--wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (number) VALUES(convert(int, @leftover))
RETURN
END
-- ############################ WICHTIG ############################
-- das is ein Beispiel wie man die Funktion benutzt
--
--CREATE PROCEDURE get_product_names_iter
-- @ids varchar(50) AS
--SELECT P.ProductName, P.ProductID
--FROM Northwind.Products P
--JOIN iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
--go
--EXEC get_product_names_iter '9 12 27 37'
--
-- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer Liste von Id's
-- ############################ WICHTIG ############################
For me I had all of the namespaces on the pages and none of the solutions above fixed it. My problem was in:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.aspx.cs"
Inherits="xxx.xxx.xxx"
MasterPageFile="~masterurl/default.master" %>
Then in my aspx.cs
file the namespace did not match the Inherits
tag. So it needed
namespace xxx.xxx.xxx
In the .cs
to match the Inherits
.
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
If you want to feel especially sly, you can write it as this:
(firstWord, rest) = yourLine.split(maxsplit=1)
This is supposed to bring the best from both worlds:
maxsplit
while splitting with any whitespaceI kind of fell in love with this solution and it's general unpacking capability, so I had to share it.
It is your setting as the owner of your local repo. Change it like this:
git remote set-head origin some_branch
And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.
Manual entry for remote set-head provides some good information on this.
Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.
Thought this might be handy for others. Knowing regex is useful, kids. Stay in school.
Edit: Turned it into a handy dandy function!
let specificStatusCodeMappings = {
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
};
function getStatusCodeString(code) {
if (code >= 0 && code <= 999) {
return '(Unused)';
} else if (code >= 1016) {
if (code <= 1999) {
return '(For WebSocket standard)';
} else if (code <= 2999) {
return '(For WebSocket extensions)';
} else if (code <= 3999) {
return '(For libraries and frameworks)';
} else if (code <= 4999) {
return '(For applications)';
}
}
if (typeof(specificStatusCodeMappings[code]) !== 'undefined') {
return specificStatusCodeMappings[code];
}
return '(Unknown)';
}
Usage:
getStatusCodeString(1006); //'Abnormal Closure'
{
'0-999': '(Unused)',
'1016-1999': '(For WebSocket standard)',
'2000-2999': '(For WebSocket extensions)',
'3000-3999': '(For libraries and frameworks)',
'4000-4999': '(For applications)'
}
{
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
}
Source (with minor edits for terseness): https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):
<div id="printOption">
<a href="javascript:void();"
onclick="document.getElementById('printOption').style.visibility = 'hidden';
document.print();
return true;">
Print
</a>
</div>
The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).
The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption
ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.
Create an texview_design.xml file and populate it with the following code. Put it in res/drawable.
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#98AFC7" />
<stroke
android:width="2dp"
android:color="#98AFC7" />
<corners
android:bottomLeftRadius="20dp"
android:bottomRightRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp" />
</shape>
Then in your main XML file just add the following line for each TextView:
android:background="@drawable/texview_design"
Second way (not recommended):
Download this circle and place it in your drawable
folder and then make it your TextView's
background. and then set the gravity
to center
.
Then it will look like this:
It's all about display: block
:)
Updated:
Ok so you have the table, tr and td tags:
<table>
<tr>
<td>
<!-- your image goes here -->
</td>
</tr>
</table>
Lets say your table
or td
(whatever define your width) has property width: 360px;
. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%;
which should fully fill out the td
cell you will face the problem.
The problem is that your table cell (td
) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).
How to solve this in a simpliest way?
You are working with the tables, right? You just need to add the display property to your image so that it has the following:
img {
width: 100%;
display: block;
}
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
To clarify, yes, you need to set default values in the constructor for class derived objects. You will need to ensure the constructor exists with the proper access modifier for construction where used. If the object is not instantiated, e.g. it has no constructor (e.g. static methods) then the default value can be set by the field. The reasoning here is that the object itself will be created only once and you do not instantiate it.
@Darren Kopp - good answer, clean, and correct. And to reiterate, you CAN write constructors for Abstract methods. You just need to access them from the base class when writing the constructor:
Constructor at Base Class:
public BaseClassAbstract()
{
this.PropertyName = "Default Name";
}
Constructor at Derived / Concrete / Sub-Class:
public SubClass() : base() { }
The point here is that the instance variable drawn from the base class may bury your base field name. Setting the current instantiated object value using "this." will allow you to correctly form your object with respect to the current instance and required permission levels (access modifiers) where you are instantiating it.
For Docker users - When trying to connect local sql using mysql -u root -h 127.0.0.1 -p
and your database is running on Docker container, make sure the mysql service is up and running (verify using docker ps
and also check that you are in the right port as well) , if the container is down you'll get connection error.
Best practice is to set the ip's in /etc/hosts
on your machine:
127.0.0.1 db.local
and running it by mysql -u root -h db.local -p
A very simple solution is to override
the toString()
method in the Node
. Then, you can call print by passing LinkedList
's head
.
You don't need to implement any kind of loop.
Code:
public class LinkedListNode {
...
//New
@Override
public String toString() {
return String.format("Node(%d, next = %s)", data, next);
}
}
public class LinkedList {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
l.insertFront(1);
l.insertFront(2);
l.insertFront(3);
//New
System.out.println(l.head);
}
}
For Ubuntu 14.04 with
PHP 7.0.13-1+deb.sury.org~trusty+1 (cli) ( NTS )
sudo apt-get install php-xml
worked for me.
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n)
is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange()
was renamed to range()
- if you want a list, you have to specifically request it via list(range(n))
.
It's sad not to see any answers with an example.
Using Mysqli::$insert_id:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$mysqli->query($sql);
$last_inserted_id=$mysqli->insert_id; // returns last ID
Using PDO::lastInsertId:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$database->query($sql);
$last_inserted_id=$database->lastInsertId(); // returns last ID
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.
...
:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice
:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done
:doonotsyncthefiles
echo Backup Complete!
...
You can have as many as you need of these blocks.
If you want to restrict valid input to integer values between 1 and 100, this will do it:
^([1-9]|[1-9][0-9]|100)$
Explanation:
This WILL NOT ACCEPT: 1. Zero - 0 2. Any integer preceded with a zero - 01, 021, 001 3. Any integer greater than 100
Hope this helps!
Gez
What are disadvantages of the following solution? Seems to be faster and shorter.
var options = {
set0: ['Option 1','Option 2'],
set1: ['First Option','Second Option','Third Option']
};
var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;
$service mongodb start
$service mongodb status
the status is active when I started using above command
int z = sizeof(name)/sizeof(name[0]); //Get the array size
sort(name,name+z); //Use the start and end like this
for(int y = 0; y < z; y++){
cout << name[y] << endl;
}
Edit :
Considering all "proper" naming conventions (as per comments) :
int N = sizeof(name)/sizeof(name[0]); //Get the array size
sort(name,name+N); //Use the start and end like this
for(int i = 0; i < N; i++){
cout << name[i] << endl;
}
Note: Dietmar Kühl's answer is best in all respect, std::begin()
& std::end()
should be used for std::sort
like functions with C++11, else they can be defined.
If someone is using Sequel the migration would look something like:
add_column :products, :price, "decimal(8,2)"
somehow Sequel ignores :precision and :scale
(Sequel Version: sequel (3.39.0, 3.38.0))
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
Instead of AudioManager.STREAM_RING
you shoul use AudioManager.STREAM_MUSIC
This question has already discussed here.
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing
A probably easier way to achieve this:
Objective-C:
CGFloat dummyViewHeight = 40;
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, dummyViewHeight)];
self.tableView.tableHeaderView = dummyView;
self.tableView.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0);
Swift:
let dummyViewHeight = CGFloat(40)
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
self.tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)
Section headers will now scroll just like any regular cell.
<asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:TemplateField HeaderText="SerialNo">
<ItemTemplate>
<%# Container .DataItemIndex+1 %>. 
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo">
<ItemTemplate>
<%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
<asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SName">
<ItemTemplate>
<%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
<asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cpp">
<ItemTemplate>
<%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
<asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Java">
<ItemTemplate>
<%-- <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
<asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<table>
<tr>
<td>
<asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
<asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
<asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
<asp:TextBox ID="txtc" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
<asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
<asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
</td>
</tr>
</table>
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.
If you are creating a new rails application you can set the database using the -d switch like this:
rails -d mysql myapp
Its always easy to switch your database later though, and using sqlite really is easier if you are developing on a Mac.
There are already multiple answers and formatting types for SQL server 2008. But this method somewhat ambiguous and it would be difficult for you to remember the number with respect to Specific Date Format. That's why in next versions of SQL server there is better option.
FORMAT ( value, format [, culture ] )
With culture option, you can specify date as per your viewers.
DECLARE @d DATETIME = '10/01/2011';
SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'
,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'
,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result';
SELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'
,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'
,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';
US English Result Great Britain English Result German Result Simplified Chinese (PRC) Result
---------------- ----------------------------- ------------- -------------------------------------
10/1/2011 01/10/2011 01.10.2011 2011/10/1
US English Result Great Britain English Result German Result Chinese (Simplified PRC) Result
---------------------------- ----------------------------- ----------------------------- ---------------------------------------
Saturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011?10?1?
For OP's solution, we can use following format, which is already mentioned by @Martin Smith:
FORMAT(GETDATE(), 'dd/MMM/yyyy', 'en-us')
Some sample date formats:
If you want more date formats of SQL server, you should visit:
Here's another way this can be done (just adding it to the answers because reduce
is a very effective functional tool that is often overlooked as a replacement for loops. In this particular case, neither of these are significantly faster than do.call)
using base R:
df <- Reduce(rbind, listOfDataFrames)
or, using the tidyverse:
library(tidyverse) # or, library(dplyr); library(purrr)
df <- listOfDataFrames %>% reduce(bind_rows)
RowDefinition
and ColumnDefinition
are of type ContentElement
, and Margin
is strictly a FrameworkElement
property. So to your question, "is it easily possible" the answer is a most definite no. And no, I have not seen any layout panels that demonstrate this kind of functionality.
You can add extra rows or columns as you suggested. But you can also set margins on a Grid
element itself, or anything that would go inside a Grid
, so that's your best workaround for now.
There is none.
Postal/zip codes around the world don't follow a common pattern. In some countries they are made up by numbers, in others they can be combinations of numbers an letters, some can contain spaces, others dots, the number of characters can vary from two to at least six...
What you could do (theoretically) is create a seperate regex for every country in the world, not recommendable IMO. But you would still be missing on the validation part: Zip code 12345
may exist, but 12346
not, maybe 12344
doesn't exist either. How do you check for that with a regex?
You can't.
I would partially disagree with Milan's suggestion of embedding the requested representation in the URI.
If anyhow possible, URIs should only be used for addressing resources and not for tunneling HTTP methods/verbs. Eventually, specific business action (edit, lock, etc.) could be embedded in the URI if create (POST) or update (PUT) alone do not serve the purpose:
POST http://shonzilla.com/orders/08/165;edit
In the case of requesting a particular representation in URI you would need to disrupt your URI design eventually making it uglier, mixing two distinct REST concepts in the same place (i.e. URI) and making it harder to generically process requests on the server-side. What Milan is suggesting and many are doing the same, incl. Flickr, is exactly this.
Instead, a more RESTful approach would be using a separate place to encode preferred representation by using Accept
HTTP header which is used for content negotiation where client tells to the server which content types it can handle/process and server tries to fulfill client's request. This approach is a part of HTTP 1.1 standard, software compliant and supported by web browsers as well.
Compare this:
GET /orders/08/165.xml HTTP/1.1 or GET /orders/08/165&format=xml HTTP/1.1
to this:
GET /orders/08/165 HTTP/1.1 Accept: application/xml
From a web browser you can request any content type by using setRequestHeader
method of XMLHttpRequest
object. For example:
function getOrder(year, yearlyOrderId, contentType) { var client = new XMLHttpRequest(); client.open("GET", "/order/" + year + "/" + yearlyOrderId); client.setRequestHeader("Accept", contentType); client.send(orderDetails); }
To sum it up: the address, i.e. the URI of a resource should be independent of its representation and XMLHttpRequest.setRequestHeader
method allows you to request any representation using the Accept
HTTP header.
Cheers!
Shonzilla
you can only pass one value, but it can be an array with multiples values within, as example:
function step1(){
let server = "myserver.com";
let data = "so much data, very impresive";
return Promise.resolve([server, data]);
}
on the other side, you can use the destructuring expression for ES2015 to get the individual values.
function step2([server, data]){
console.log(server); // print "myserver.com"
console.log(data); // print "so much data, very impresive"
return Promise.resolve("done");
}
to call both promise, chaining them:
step1()
.then(step2)
.then((msg)=>{
console.log(msg); // print "done"
})
You can also propagate your static pain with lambdas, so the whole thing looks readable:
s.filter(a -> propagate(a::isActive))
propagate
here receives java.util.concurrent.Callable
as a parameter and converts any exception caught during the call into RuntimeException
. There is a similar conversion method Throwables#propagate(Throwable) in Guava.
This method seems being essential for lambda method chaining, so I hope one day it will be added to one of the popular libs or this propagating behavior would be by default.
public class PropagateExceptionsSample {
// a simplified version of Throwables#propagate
public static RuntimeException runtime(Throwable e) {
if (e instanceof RuntimeException) {
return (RuntimeException)e;
}
return new RuntimeException(e);
}
// this is a new one, n/a in public libs
// Callable just suits as a functional interface in JDK throwing Exception
public static <V> V propagate(Callable<V> callable){
try {
return callable.call();
} catch (Exception e) {
throw runtime(e);
}
}
public static void main(String[] args) {
class Account{
String name;
Account(String name) { this.name = name;}
public boolean isActive() throws IOException {
return name.startsWith("a");
}
}
List<Account> accounts = new ArrayList<>(Arrays.asList(new Account("andrey"), new Account("angela"), new Account("pamela")));
Stream<Account> s = accounts.stream();
s
.filter(a -> propagate(a::isActive))
.map(a -> a.name)
.forEach(System.out::println);
}
}
Jquery.min.js is nothing else but compressed version of jquery.js. You can use it the same way as jquery.js, but it's smaller, so in production you should use minified version and when you're debugging you can use normal jquery.js version. If you want to compress your own javascript file you can these compressors:
Or just read topis on StackOverflow about js compression :) :
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
Using DataBinding and setting background to the edittext with resources from the drawable folder causes the exception.
<EditText
android:background="@drawable/rectangle"
android:imeOptions="flagNoExtractUi"
android:layout_width="match_parent"
android:layout_height="45dp"
android:hint="Enter Your Name"
android:gravity="center"
android:textColorHint="@color/hintColor"
android:singleLine="true"
android:id="@+id/etName"
android:inputType="textCapWords"
android:text="@={viewModel.model.name}"
android:fontFamily="@font/avenir_roman"/>
Solution
I just change the background from android:background="@drawable/rectangle"
to android:background="@null"
Clean and Rebuild the Project.
You need to include this in your textview:
android:singleLine="false"
by default its true. You need to explicitly set it false.
In my experience with regex you really need to focus on what EXACTLY you are trying to match, rather than what NOT to match.
for example
\d{2}
[1-9][0-9]
The first expression will match any 2 digits....and the second will match 1 digit from 1 to 9 and 1 digit - any digit. So if you type 07 the first expression will validate it, but the second one will not.
See this for advanced reference:
http://www.regular-expressions.info/refadv.html
EDITED:
^((?!my string).)*$
Is the regular expression for does not contain "my string".
Casting my hat into the ring a couple years later.
Will need to save the beginning center of the image view:
var panBegin: CGPoint.zero
Then update the new center using a transform:
if recognizer.state == .began {
panBegin = imageView!.center
} else if recognizer.state == .ended {
panBegin = CGPoint.zero
} else if recognizer.state == .changed {
let translation = recognizer.translation(in: view)
let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)
imageView!.center = panBegin.applying(panOffsetTransform)
}
For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.
Assuming your list of people is in data
variable and you filter people using query
model, the following code will work for you:
<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
{{data.length}}
- prints total number of people{{(data|filter:query).length}}
- prints filtered number of peopleNote that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.
New Feature in Angular 1.3
AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.
<div ng-repeat="person in data | filter:query as results">
<!-- template ... -->
</div>
<p>Number of visible people: {{results.length}}</p>
The alias expression will prevent multiple filter execution issue.
I hope that will help.
If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline()
function (see the manual page here):
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
As in a similar question, use display: inline-block
with a placeholder element to vertically center the span inside of a block element:
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="container">_x000D_
<span id="content">_x000D_
Content_x000D_
</span>_x000D_
<span id="placeholder"></span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block
or display:table-cell
with a display:table
parent when vertically centering block elements.
References:
May I suggest a php+css solution I used on my site? It's simple and no js problems :)
url to page: <a href="page.php?tab=menu1">link to menu1</a>
<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
<li class="<? if ($tab=='menu1' OR $tab=='menu2')
{
echo "";
}
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
<li class="<? if ($tab=='menu1')
{
echo "active";
}
?>"><a data-toggle="tab" href="#menu1">News</a></li>
<li class="<? if ($tab=='menu2')
{
echo "active";
}
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2')
{
echo "";
}
else {
echo "in active";
}
?>
">
<h3>Prodotti</h3>
<p>Contenuto della pagina, zona prodotti</p>
</div>
<div id="menu1" class="tab-pane fade <? if ($tab=='menu1')
{
echo "in active";
}
?>">
<h3>News</h3>
<p>Qui ci saranno le news.</p>
</div>
<div id="menu2" class="tab-pane fade <? if ($tab=='menu2')
{
echo "in active";
}
?>">
<h3>Gallery</h3>
<p>Qui ci sarà la gallery</p>
</div>
</div>
Use curly braces around the variable name:
`tail -1 ${filepath}_newstap.sh`
Download it from here and extract LatoOFL.rar
then go to TTF and open this font-face-generator click at Choose File
choose font which you want to use and click at generate then download it and then go html
file open it and you see the code like this
@font-face {
font-family: "Lato Black";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body{
font-family: "Lato Black";
direction: ltr;
}
change the src code and give the url where your this font directory placed, now you can use it at your website...
If you don't want to download it use this
<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:
$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");
As others have pointed out, params
values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.
As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params
. For example, if you have a route like this:
match 'products/:id', ...
Then a request to a URL like http://example.com/products/42
will set params[:id]
to 42
.
I have tried all suggestions and found my own simple solution.
The problem is that codes written in external environment like C
need compiler. Look for its own VS environment, i.e. VS 2008.
Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat
.
I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS
as variable name and gave the value of VS120COMNTOOLS
.
You can find my step by step solution below:
Now open a new session and pip install your-package
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
Create a shortcut to your bat
file by using the right-click
and selecting Create shortcut
.
Right-click
on the shortcut you created and click on properties.
Click on the Run drop-down box and select Minimized.
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds
file. Not so for Rda
> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)
## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5
## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to <environment: R_GlobalEnv>
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values.
> x
[1] 1 2 3 4 5
select *from table_name where boolean_column is False or Null;
Is interpreted as "( boolean_column is False ) or (null)".
It returns only rows where boolean_column
is False as the second condition is always false.
select *from table_name where boolean_column is Null or False;
Same reason. Interpreted as "(boolean_column is Null) or (False)"
select *from table_name where boolean_column is Null or boolean_column = False;
This one is valid and returns 2 rows: false
and null
.
I just created the table to confirm. You might have typoed somewhere.
I reinstalled the usb
drivers and ensured that I was not using USB 3.0
port.
I then closed out eclipse and killed and restarted adb
.
Was immediately prompted on phone to allow computer access. After accepting I restarted eclipse and now my Galaxy S3 shows up in device Device Manager.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
You can do this pretty easily:
@app.route("/")
def home():
resp = flask.Response("Foo bar baz")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
Look at flask.Response and flask.make_response()
But something tells me you have another problem, because the after_request
should have handled it correctly too.
EDIT
I just noticed you are already using make_response
which is one of the ways to do it. Like I said before, after_request
should have worked as well. Try hitting the endpoint via curl and see what the headers are:
curl -i http://127.0.0.1:5000/your/endpoint
You should see
> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT
Noting the Access-Control-Allow-Origin header.
EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True
before you start the app and try again. You should get some output showing you the root cause of the problem.
For example:
@app.route("/")
def home():
resp = flask.Response("Foo bar baz")
user.weapon = boomerang
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)
Traceback (most recent call last):
...
File "/private/tmp/min.py", line 8, in home
user.weapon = boomerang
NameError: global name 'boomerang' is not defined
In 9.4.4 using the #>>
operator works for me:
select to_json('test'::text) #>> '{}';
To use with a table column:
select jsoncol #>> '{}' from mytable;
The three best way to do it using a single line of code
import cv2
import numpy as np
img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena
# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical = np.vstack((newIMG, X))
cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)
cv2.waitKey(0)
# Methode 2: Using Numpy (contanate)
Fusion_Vertical = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)
cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)
cv2.waitKey(0)
# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])
cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)
cv2.waitKey(0)
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.
Try this code:
import java.util.Scanner;
public class BasicElement {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int hours;
System.out.print("Enter the hours to convert:");
hours =input.nextInt();
int d=hours/24;
int m=hours%24;
System.out.println(d+"days"+" "+m+"hours");
}
}
You can also use regular expression in addition to this:
$directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
$directoryPath = preg_replace("/app..../i", "", $directoryPath);
echo $directoryPath;
Use .val()
not attr('value')
.
Use a SmartInitializingSingleton
bean in spring > 4.1
@Bean
public SmartInitializingSingleton importProcessor() {
return () -> {
doStuff();
};
}
As alternative a CommandLineRunner
bean can be implemented or annotating a bean method with @PostConstruct
.
/* This example uses an XML variable with a schema */
IF EXISTS (SELECT * FROM sys.xml_schema_collections
WHERE name = 'OrderingAfternoonTea')
BEGIN
DROP XML SCHEMA COLLECTION dbo.OrderingAfternoonTea
END
GO
CREATE XML SCHEMA COLLECTION dbo.OrderingAfternoonTea AS
N'<?xml version="1.0" encoding="UTF-16" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://Tfor2.com/schemas/actions/orderAfternoonTea"
xmlns="http://Tfor2.com/schemas/actions/orderAfternoonTea"
xmlns:TFor2="http://Tfor2.com/schemas/actions/orderAfternoonTea"
elementFormDefault="qualified"
version="0.10"
>
<xsd:complexType name="AfternoonTeaOrderType">
<xsd:sequence>
<xsd:element name="potsOfTea" type="xsd:int"/>
<xsd:element name="cakes" type="xsd:int"/>
<xsd:element name="fruitedSconesWithCream" type="xsd:int"/>
<xsd:element name="jams" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="schemaVersion" type="xsd:long" use="required"/>
</xsd:complexType>
<xsd:element name="afternoonTeaOrder"
type="TFor2:AfternoonTeaOrderType"/>
</xsd:schema>' ;
GO
DECLARE @potsOfTea int;
DECLARE @cakes int;
DECLARE @fruitedSconesWithCream int;
DECLARE @jams nvarchar(128);
DECLARE @RequestMsg NVARCHAR(2048);
DECLARE @RequestXml XML(dbo.OrderingAfternoonTea);
set @potsOfTea = 5;
set @cakes = 7;
set @fruitedSconesWithCream = 25;
set @jams = N'medlar jelly, quince and mulberry';
SELECT @RequestMsg = N'<?xml version="1.0" encoding="utf-16" ?>
<TFor2:afternoonTeaOrder schemaVersion="10"
xmlns:TFor2="http://Tfor2.com/schemas/actions/orderAfternoonTea">
<TFor2:potsOfTea>' + CAST(@potsOfTea as NVARCHAR(20))
+ '</TFor2:potsOfTea>
<TFor2:cakes>' + CAST(@cakes as NVARCHAR(20)) + '</TFor2:cakes>
<TFor2:fruitedSconesWithCream>'
+ CAST(@fruitedSconesWithCream as NVARCHAR(20))
+ '</TFor2:fruitedSconesWithCream>
<TFor2:jams>' + @jams + '</TFor2:jams>
</TFor2:afternoonTeaOrder>';
SELECT @RequestXml = CAST(CAST(@RequestMsg AS VARBINARY(MAX)) AS XML) ;
with xmlnamespaces('http://Tfor2.com/schemas/actions/orderAfternoonTea'
as tea)
select
cast( x.Rec.value('.[1]/@schemaVersion','nvarchar(20)') as bigint )
as schemaVersion,
cast( x.Rec.query('./tea:potsOfTea')
.value('.','nvarchar(20)') as bigint ) as potsOfTea,
cast( x.Rec.query('./tea:cakes')
.value('.','nvarchar(20)') as bigint ) as cakes,
cast( x.Rec.query('./tea:fruitedSconesWithCream')
.value('.','nvarchar(20)') as bigint )
as fruitedSconesWithCream,
x.Rec.query('./tea:jams').value('.','nvarchar(50)') as jams
from @RequestXml.nodes('/tea:afternoonTeaOrder') as x(Rec);
select @RequestXml.query('/*')
In the case of your label snippet, it doesn't really matter. I would go for the simpler syntax (plain HTML).
Most helper methods also don't allow you to surround another element. This can be a consideration when choosing to use/not use one.
However, it's worth noting that what you use the @Html.[Element]For<T>()
methods that you gain important features. Note the "For" at the end of the method name.
Example:
@Html.TextBoxFor( o => o.FirstName )
This will handle ID/Name creation based on object hierarchy (which is critical for model binding). It will also add unobtrusive validation attributes. These methods take an Expression as an argument which refers to a property within the model. The metadata of this property is obtained by the MVC framework, and as such it "knows" more about the property than its string-argument counterpart.
It also allows you to deal with UI code in a strongly-typed fashion. Visual Studio will highlight syntax errors, whereas it cannot do so with a string. Views can also be optionally compiled along with the solution, allowing for additional compile-time checks.
Occasionally a HTML helper method will also perform additional tasks which are useful, such as Html.Checkbox
and Html.CheckboxFor
which also create a hidden field to go along with the checkbox. Another example are the URL-related methods (such as for a hyperlink) which are route-aware.
<!-- bad -->
<a href="/foo/bar/123">my link</a>
<!-- good -->
@Html.ActionLink( "my link", "foo", "bar", new{ id=123 } )
<!-- also fine (perhaps you want to wrap something with the anchor) -->
<a href="@Url.Action( "foo", "bar", new{ id=123 } )"><span>my link</span></a>
There is a slight performance benefit to using plain HTML versus code which must be executed whenever the view is rendered, although this should not be the deciding factor.
WOOCOMMERCE ORDERS IN VERSION 3.0+
Since Woocommerce mega major Update 3.0+ things have changed quite a lot:
WC_Order
Object, properties can't be accessed directly anymore as before and will throw some errors.WC_Order
and WC_Abstract_Order
getter and setter methods are now required on the WC_Order
object instance.WC_Data
Abstract class allow to access Order and order items data using get_data()
, get_meta_data()
and get_meta()
methods.Related:
• How to get Customer details from Order in WooCommerce?
• Get Order items and WC_Order_Item_Product in WooCommerce 3
So the Order items properties will not be accessible as before in a foreach
loop and you will have to use these specific getter and setter methods instead.
Using some WC_Order
and WC_Abstract_Order
methods (example):
// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );
$order_id = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)
$user_id = $order->get_user_id(); // Get the costumer ID
$user = $order->get_user(); // Get the WP_User object
$order_status = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency = $order->get_currency(); // Get the currency used
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)
$billing_country = $order->get_billing_country(); // Customer billing country
// ... and so on ...
For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):
if ( $order->has_status('completed') ) { // Do something }
Get and access to the order data properties (in an array of values):
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_data = $order->get_data(); // The Order data
$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];
## Creation and modified WC_DateTime Object date string ##
// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');
// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();
$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on
## BILLING INFORMATION:
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
## SHIPPING INFORMATION:
$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
Get the order items and access the data with WC_Order_Item_Product
and WC_Order_Item
methods:
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):
## Using WC_Order_Item methods ##
// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item->get_id();
## Using WC_Order_Item_Product methods ##
$product = $item->get_product(); // Get the WC_Product object
$product_id = $item->get_product_id(); // the Product id
$variation_id = $item->get_variation_id(); // the Variation id
$item_type = $item->get_type(); // Type of the order item ("line_item")
$item_name = $item->get_name(); // Name of the product
$quantity = $item->get_quantity();
$tax_class = $item->get_tax_class();
$line_subtotal = $item->get_subtotal(); // Line subtotal (non discounted)
$line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
$line_total = $item->get_total(); // Line total (discounted)
$line_total_tax = $item->get_total_tax(); // Line total tax (discounted)
## Access Order Items data properties (in an array of values) ##
$item_data = $item->get_data();
$product_name = $item_data['name'];
$product_id = $item_data['product_id'];
$variation_id = $item_data['variation_id'];
$quantity = $item_data['quantity'];
$tax_class = $item_data['tax_class'];
$line_subtotal = $item_data['subtotal'];
$line_subtotal_tax = $item_data['subtotal_tax'];
$line_total = $item_data['total'];
$line_total_tax = $item_data['total_tax'];
// Get data from The WC_product object using methods (examples)
$product = $item->get_product(); // Get the WC_Product object
$product_type = $product->get_type();
$product_sku = $product->get_sku();
$product_price = $product->get_price();
$stock_quantity = $product->get_stock_quantity();
endforeach;
So using
get_data()
method allow us to access to the protected data (associative array mode) …
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
If you are not using redux-form and you are using local state for changes then your react-select component might look like this:
class MySelect extends Component {
constructor() {
super()
}
state = {
selectedValue: 'default' // your default value goes here
}
render() {
<Select
...
value={this.state.selectedValue}
...
/>
)}
This will only work for windows which are opened by using window.open(); method. Try this
var tmp=window.open(params);
tmp.close();
This solution works with unittest
and nose
for Python 2 and Python 3:
#!/usr/bin/env python
import unittest
def make_function(description, a, b):
def ghost(self):
self.assertEqual(a, b, description)
print(description)
ghost.__name__ = 'test_{0}'.format(description)
return ghost
class TestsContainer(unittest.TestCase):
pass
testsmap = {
'foo': [1, 1],
'bar': [1, 2],
'baz': [5, 5]}
def generator():
for name, params in testsmap.iteritems():
test_func = make_function(name, params[0], params[1])
setattr(TestsContainer, 'test_{0}'.format(name), test_func)
generator()
if __name__ == '__main__':
unittest.main()
The following code worked very well for me:
SELECT
o.name as tableName,
c.name as columnName,
o.[type],
s.name as schemaName,
o.type_desc
FROM
sys.objects AS o
INNER JOIN sys.[columns] AS c ON c.[object_id] = o.[object_id]
INNER JOIN sys.schemas AS s ON o.[schema_id] = s.[schema_id]
WHERE
o.type_desc='USER_TABLE'
AND c.name='YourColumnName' --if comment this line,show all columns
ORDER BY
o.name,
c.column_id
you just replace your Column name with 'YourColumnName'. then run query
In short: It's a shorthand notation for a mathematical hack.
Long explanation:
You can't do a cross product with vectors in 2D space. The operation is not defined there.
However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.
If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.
That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.
From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.
I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
optionsBuilder.UseSqlServer(connectionString);
}
}
This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.
Some options without REGEXMATCH
, since you might want to be case insensitive and not want say blast
or ablative
to trigger a YES
. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:
First very similar to @user1598086's answer:
=FIND("bla",A1)
Is case sensitive but returns #VALUE! rather than NO
and a number rather than YES
(both of which can however be changed to NO/YES respectively).
=SEARCH("bla",A1)
Case insensitive, so treats Black
and black
equally. Returns as above.
The former (for the latter equivalent) to indicate whether bla
present after the first three characters in A1:
=FIND("bla",A1,4)
Returns a number for blazer, black
but #VALUE!
for blazer, blue
.
To find Bla
only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):
=SEARCH(" Bla ",A1)
Since the return in all cases above is either a number ("found", so YES
preferred) or #VALUE!
we can use ISERROR to test for #VALUE!
within an IF formula, for instance taking the first example above:
=if(iserror(FIND("bla",A1)),"NO","YES")
Longer than the regexmatch
but the components are easily adjustable.
Inline-block is a halfway point between setting an element’s display to inline or to block. It keeps the element in the inline flow of the document like display:inline does, but you can manipulate the element’s box attributes (width, height and vertical margins) like you can with display:block.
We must not use block elements within inline elements. This is invalid and there is no reason to do such practices.
You can use finishAndRemoveTask ()
from API 21
public void finishAndRemoveTask ()
Finishes all activities in this task and removes it from the recent tasks list.
The error can be caused by mixing together debug builds and release builds in same executable or dll.
try this:
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Check out the HTML5 PDF viewer:
I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:
Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.
I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.
Some code:
namespace ROS.WebService.Common
{
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public static class DataAccess
{
public static string ConnectionString { get; private set; }
static DataAccess()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
}
public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
{
using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
{
foreach (var p in sqlParams) cmd.Parameters.Add(p);
cmd.Connection.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
}
Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout
Array and Object is passed as pass by reference or pass by value based on these two condition.
if you are changing value of that Object or array with new Object or Array then it is pass by Value.
object1 = {item: "car"};
array1=[1,2,3];
here you are assigning new object or array to old one.you are not changing the value of property of old object.so it is pass by value.
if you are changing a property value of an object or array then it is pass by Reference.
object1.item= "car";
array1[0]=9;
here you are changing a property value of old object.you are not assigning new object or array to old one.so it is pass by reference.
Code
function passVar(object1, object2, number1) {
object1.key1= "laptop";
object2 = {
key2: "computer"
};
number1 = number1 + 1;
}
var object1 = {
key1: "car"
};
var object2 = {
key2: "bike"
};
var number1 = 10;
passVar(object1, object2, number1);
console.log(object1.key1);
console.log(object2.key2);
console.log(number1);
Output: -
laptop
bike
10
decimal pay = 1.994444M;
Math.Round(pay , 2);
It's not a clever choice to move all .git*
by hand, particularly when these .git
files are hidden in sub-folders just like my condition: when I installed Skeleton Zend 2 by composer+git, there are quite a number of .git
files created in folders and sub-folders.
I tried rm -rf .git
on my GitHub shell, but the shell can not recognize the parameter -rf
of Remove-Item.
www.montanaflynn.me introduces the following shell command to remove all .git
files one time, recursively! It's really working!
find . | grep "\.git/" | xargs rm -rf
Referring to SimpleDataFormat JavaDoc:
Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
H | Hour in day (0-23) | Number | 0
h | Hour in am/pm (1-12) | Number | 12
Wikipedia has the answer. Read syntax (programming languages) & semantics (computer science) wikipages.
Or think about the work of any compiler or interpreter. The first step is lexical analysis where tokens are generated by dividing string into lexemes then parsing, which build some abstract syntax tree (which is a representation of syntax). The next steps involves transforming or evaluating these AST (semantics).
Also, observe that if you defined a variant of C where every keyword was transformed into its French equivalent (so if
becoming si
, do
becoming faire
, else
becoming sinon
etc etc...) you would definitely change the syntax of your language, but you won't change much the semantics: programming in that French-C won't be easier!
On git version 2.8.1: following works for me.
To save modified and untracked files in stash without a name
git stash save -u
To save modified and untracked files in stash with a name
git stash save -u <name_of_stash>
You can use either pop or apply later as follows.
git stash pop
git stash apply stash@{0}
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
This updates the answers with the latest Fetch API and doesn't need jQuery.
Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.
Basic Fetch
It could be as simple as:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => console.log(response.text()))
Fetch with Error Handling
After adding error handling, it could look like:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => {
if (response.ok) return response;
else throw Error(`Server returned ${response.status}: ${response.statusText}`)
})
.then(response => console.log(response.text()))
.catch(err => {
alert(err);
});
PHP Code
This is the server-side code in upload.php.
<?php
// gets entire POST body
$data = file_get_contents('php://input');
// write the data out to the file
$fp = fopen("path/to/file", "wb");
fwrite($fp, $data);
fclose($fp);
?>
I just came across this so I am sharing here. Here is the option
https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly
Here is the code.
HTML
<br/>
<!-- padding for jsfiddle -->
<div class="input-group date" id="arrival_date_div">
<input type="text" class="form-control" id="arrival_date" name="arrival_date" required readonly="readonly" />
<span class="input-group-addon">
<span class="glyphicon-calendar glyphicon"></span>
</span>
</div>
JS
$('#arrival_date_div').datetimepicker({
format: "YYYY-MM-DD",
ignoreReadonly: true
});
Here is the fiddle:
http://jsfiddle.net/matbaric/wh1cb6cy/
My version of bootstrap-datetimepicker.js is 4.17.45
If once solved a similar issue by simply checking out a new working copy and replacing the .svn directory throwing the commit errors with this newly checked out one. The reason in my case was that after a repository corruption and restore from a backup the working copy was pointing towards a revision that didn't exist in the restored repository. Also got "item out of date" errors. Updating the working copy before commit didn't solve this but replacing the .svn as described above did.
I think what you are looking for is something like this:
$(field).closest("form").submit();
For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
$(this).closest("form").submit();
});
If, for some reason you aren't using jQuery 1.3 or above, you can call parents
instead of closest
.
Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}
first install apt-get install python-setuptools
then try easy_install psycopg2
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:
<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>
I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.
When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.
Considering that both strings may be very large, there are 2 main approaches bitwise search
and localeCompare
I recommed this function
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case
So
var result = text.split(' ').join('')
operates faster than
var result = text.replace(/\s+/g, '')
On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.
On the other hand, \s+
handles wider variety of space characters. Among with \n
and \t
, it also matches \u00a0
character, and that is what
is turned in, when getting text using textDomNode.nodeValue
.
So I think that conclusion in here can be made as follows: if you only need to replace spaces ' '
, use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')
If you want to access a server running on your PC from your Android device via your wireless network, first run the command ipconfig on your PC (use run (Windows logo + R), cmd, ipconfig).
Note the IPv4 address: (it should be 192.168.0.x) for some x. Use this as the server IP address, together with the port number, e.g. 192.168.0.7:8080, in your code.
Your Android device will then access the server via your wireless network router.
I downgraded ruby from 2.5.x to 2.4.x in my particular case.
Use animation-fill-mode: forwards;
animation-fill-mode: forwards;
The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).
Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.
Working example
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: red;_x000D_
position :relative;_x000D_
-webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
animation: bubble 3s forwards;_x000D_
/* animation-name: bubble; _x000D_
animation-duration: 3s;_x000D_
animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
Bash4 supports this natively. Do not use grep
or eval
, they are the ugliest of hacks.
For a verbose, detailed answer with example code see: https://stackoverflow.com/questions/3467959
If you are trying to loop over a NodeList
like this:
const allParagraphs = document.querySelectorAll("p");
I highly recommend loop it this way:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList
, but this one works like a charm, give it a try!
The NodeList
isn't an Array, but we treat it as an Array, using Array.
So, you need to know that it is not supported in older browsers!
Need more information about NodeList
? Please read its documentation on MDN.
vehicle[] car = new vehicle[N];
The "pause" command was a function button underneath my right shift key, so the below combination of keys did the trick for me.
Ctrl + Fn + Shift
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
Try this shell script
DBENGINE='InnoDB' ;
DBUSER='your_db_user' ;
DBNAME='your_db_name' ;
DBHOST='your_db_host'
DBPASS='your_db_pass' ;
mysqldump --add-drop-table -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME > mtest.sql; mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "SHOW TABLES;" | while read TABLE ; do mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "ALTER TABLE $TABLE ENGINE=$DBENGINE;" ; done
var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser
function expects a function in its third argument, which is bound to the name next
. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser
is done (unless a user could not be found).
There's nothing special about the name next
in this example; we could have named it anything.
Your PHP script (external file 'email.php') should look like this:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("[email protected]", "51 Deep comment from" .$email, $message);
}
?>
It means that there is no initial context :)
But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".
An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.
UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.
This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:
If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True
Advantages of this approach:
1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.
Another way:
md5=$(md5sum ${my_iso_file} | sed '/ .*//' )
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
Update: This answer is outdated as newer versions of libraries mentioned are released since then.
Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.
"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.
See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539
Path.GetFileName( Request.Url.AbsolutePath )
SOLUTION 1 (combine find
and grep
)
The purpose of this solution is not to deal with grep
performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.
Use find
, for excluding directories foo and bar :
find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
Then combine find
and the non-recursive use of grep
, as a portable solution :
find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
SOLUTION 2 (using the --exclude-dir
option of grep
):
You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.
grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
To exclude multiple directories, use --exclude-dir
as:
--exclude-dir={node_modules,dir1,dir2,dir3}
SOLUTION 3 (Ag)
If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in .gitignore
, so you don't have to keep passing the same cumbersome exclude options to grep
or find
.
In Eclipse:
Project -> properties -> java Build Path -> libraries
Remove existing JRE System Library, then Add Library -> JRE System library -> next -> ok
Error will be removed.
I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.
function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }
SWIFT 2
I was able to successfully change the appearance of the status bar background by adding the following in my viewWillAppear:
let statusBar: UIView = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
if statusBar.respondsToSelector(Selector("setBackgroundColor:")) {
statusBar.backgroundColor = .redColor()
}
I fixed the error with virtualenv by doing this:
Copied pkg_resources.py from
/Library/Python/2.7/site-packages/setuptools
to
/Library/Python/2.7/site-packages/
This may be a cheap workaround, but it worked for me.
.
If setup tools doesn't exist, you can try installing system-site-packages by typing virtualenv --system-site-packages /DESTINATION DIRECTORY
, changing the last part to be the directory you want to install to. pkg_rousources.py
will be under that directory in lib/python2.7/site-packages
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
If you don't want git-fetch to update your local .git, just copy your local repo to a temp dir and do a pull there. Here is a shor-hand:
$ alias gtp="tar -c . | (cd /tmp && mkdir tp && cd tp && tar -x && git pull; rm -rf /tmp/tp)"
Ex.:
$ git status
# On branch master
nothing to commit (working directory clean)
$ gtp
remote: Finding sources: 100% (25/25)
remote: Total 25 (delta 10), reused 25 (delta 10)
Unpacking objects: 100% (25/25), done.
From ssh://my.git.domain/reapO
32d61dc..05287d6 master -> origin/master
Updating 32d61dc..05287d6
Fast-forward
subdir/some.file | 2 +-
.../somepath/by.tes | 3 ++-
.../somepath/data | 11 +++++++++++
3 files changed, 14 insertions(+), 2 deletions(-)
$ git status
# On branch master
nothing to commit (working directory clean)
$ git fetch
remote: Finding sources: 100% (25/25)
remote: Total 25 (delta 10), reused 25 (delta 10)
Unpacking objects: 100% (25/25), done.
From ssh://my.git.domain/reapO
32d61dc..05287d6 master -> origin/master
$ git status
# On branch master
# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.
#
nothing to commit (working directory clean)
In Groovy, null == null
gets a true
. At runtime, you won't know what happened.
In Java, ==
is comparing two references.
This is a cause of big confusion in basic programming, Whether it is safe to use equals. At runtime, a null.equals will give an exception. You've got a chance to know what went wrong.
Especially, you get two values from keys not exist in map(s), ==
makes them equal.
This seems to work for me:
SELECT FORMAT(@mins / 60 * 100 + @mins % 60, '#:0#')
Since these are member functions, call it as a member function on the instance, self
.
def isNear(self, p):
self.distToPoint(p)
...
You should firstly put this code in your AppManifest.xml in the application tag:
android:supportsRtl="true"
then in your activity_main.xml file, put this piece of code:
android:layout_direction="rtl"
try this formula in column E:
=IF( AND( ISNUMBER(D2), D2=G2), H2, "")
your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )
you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.
I hope you understand my explanation.
You can use this function:
def frange(start,end,step):
return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String
or the char
primitive -- you should only be using byte[]
arrays or ByteBuffer
objects. Then, you can use java.nio.charset.Charset
to convert between encodings:
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
I wanted a solution that did not create any extra objects (ie listeners) that would have to be garbage collected later, and did not require nesting a view holder inside an adapter class.
In the ViewHolder
class
private static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView ....// declare the fields in your view
private ClickHandler ClickHandler;
public MyHolder(final View itemView) {
super(itemView);
nameField = (TextView) itemView.findViewById(R.id.name);
//find other fields here...
Button myButton = (Button) itemView.findViewById(R.id.my_button);
myButton.setOnClickListener(this);
}
...
@Override
public void onClick(final View view) {
if (clickHandler != null) {
clickHandler.onMyButtonClicked(getAdapterPosition());
}
}
Points to note: the ClickHandler
interface is defined, but not initialized here, so there is no assumption in the onClick
method that it was ever initialized.
The ClickHandler
interface looks like this:
private interface ClickHandler {
void onMyButtonClicked(final int position);
}
In the adapter, set an instance of 'ClickHandler' in the constructor, and override onBindViewHolder
, to initialize `clickHandler' on the view holder:
private class MyAdapter extends ...{
private final ClickHandler clickHandler;
public MyAdapter(final ClickHandler clickHandler) {
super(...);
this.clickHandler = clickHandler;
}
@Override
public void onBindViewHolder(final MyViewHolder viewHolder, final int position) {
super.onBindViewHolder(viewHolder, position);
viewHolder.clickHandler = this.clickHandler;
}
Note: I know that viewHolder.clickHandler is potentially getting set multiple times with the exact same value, but this is cheaper than checking for null and branching, and there is no memory cost, just an extra instruction.
Finally, when you create the adapter, you are forced to pass a ClickHandler
instance to the constructor, as so:
adapter = new MyAdapter(new ClickHandler() {
@Override
public void onMyButtonClicked(final int position) {
final MyModel model = adapter.getItem(position);
//do something with the model where the button was clicked
}
});
Note that adapter
is a member variable here, not a local variable
Strings are immutable. You can use the string builder class to help!:
string str = "valta is the best place in the World";
StringBuilder strB = new StringBuilder(str);
strB[0] = 'M';
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
if Linux users still have the same error, probably they have used "sudo" for adding android platform.. a quick solution for this here, or you have installed cordova using sudo, also there is a solution for this problem here.
Hope this help!
I found the answer is git reset --merge
- it clears the conflicted cherry-pick attempt.
If you want to check your URL. I suppose you are using Chrome. You can go to chrome console and URL will be displayed under "XHR finished loading:"
matplotlib svn has a new function to save images as just an image -- no axes etc. it's a very simple function to backport too, if you don't want to install svn (copied straight from image.py in matplotlib svn, removed the docstring for brevity):
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
canvas = FigureCanvas(fig)
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
fig.savefig(fname, dpi=1, format=format)
I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.
It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.
Pick the values in a servlet ie.
String username = request.getParameter("username");
String password = request.getParameter("password");
Then Store the Values inside the Session:
HttpSession sess = request.getSession();
sess.setAttribute("username", username);
sess.setAttribute("password", password);
These values Will be available anywhere in the Application as long as the session is valid.
HttpSession sess = request.getSession(false); //use false to use the existing session
sess.getAttribute("username");//this will return username anytime in the session
sess.getAttribute("password");//this will return password Any time in the session
I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl
in the JSPs:
${username}//this will give you the username in the JSP
${password}// this will give you the password in the JSP
If you have a table called memos that has two columns id
and text
you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text
is equal to 'text to insert' and id
is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer
below.
After losing time and reading for a while, I just wanted something simple, this css worked for my requirements.
.gm-style-iw > div { overflow: hidden !important; }
Also is not an instant solution but starring/commenting on the issue might make them fix it, as they believe it is fixed: http://code.google.com/p/gmaps-api-issues/issues/detail?id=5713
I think we can improve the best answer a little bit, I'm using:
len = sum(1 for _ in reader)
Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.
Alternative solution if all above solutions are not working for you
By default, Volley set timeout equally for both setConnectionTimeout()
and setReadTimeout()
with the value from RetryPolicy
. In my case, Volley
throws timeout exception for large data chunk see:
com.android.volley.toolbox.HurlStack.openConnection().
My solution is create a class which extends HttpStack
with my own setReadTimeout()
policy. Then use it when creates RequestQueue
as follow:
Volley.newRequestQueue(mContext.getApplicationContext(), new MyHurlStack())