Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var temp : String? // This is an optional.
temp = "I am a programer"
print(temp) // Optional("I am a programer")
var temp1 : String! // This is not optional.
temp1 = "I am a programer"
print(temp1) // "I am a programer"
This is really simple, the String
object has an endsWith
method.
From your question it seems like you want either /
, ,
or .
as the delimiter set.
So:
String str = "This.is.a.great.place.to.work.";
if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
// ...
You can also do this with the matches
method and a fairly simple regex:
if (str.matches(".*([.,/])work\\1$"))
Using the character class [.,/]
specifying either a period, a slash, or a comma, and a backreference, \1
that matches whichever of the alternates were found, if any.
Try to use "uri" segments like:
$this->uri->segment(5); //To get 'ahahaha'
$this->uri->segment(6); //To get 'hihihi
form your first URL...You get '' from second URl also for segment(5),segment(6) also because they are empty.
Every segment function counts starts form localhost as '1' and symultaneous segments
You should be able to use a var_dump() within a pre tag. Otherwise you could look into using a library like dump_r.php: https://github.com/leeoniya/dump_r.php
My solution is incorrect. OP was looking for a solution formatted with spaces to store in a log file.
A solution might be to use output buffering with var_dump, then str_replace() all the tabs with spaces to format it in the log file.
I would try:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
Don't do this!
Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).
The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!
Cocoa offers a cool feature which greatly enhances your capabilities to debug such situations. It is an environment variable which is called NSZombieEnabled, watch this video that explains setting up NSZombieEnabled in objective-C
You can use built-in map
function:
result = map(lambda x: x * P, S)
or list comprehensions that is a bit more pythonic:
result = [x * P for x in S]
Under certain circumstances, IE6 will still cache files even when Cache-Control: no-cache
is in the response headers.
If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server.
In my application, if you visited a page with the no-cache
header, then logged out and then hit back in your browser, IE6 would still grab the page from the cache (without a new/validating request to the server). Adding in the no-store
header stopped it doing so. But if you take the W3C at their word, there's actually no way to control this behavior:
History buffers MAY store such responses as part of their normal operation.
General differences between browser history and the normal HTTP caching are described in a specific sub-section of the spec.
I found very nice solution, that SOLVED my problem. The trick is to edit the svn DB (wc.db).
The solution is described on this page : http://www.exchangeconcept.com/2015/01/svn-e155037-previous-operation-has-not-finished-run-cleanup-if-it-was-interrupted/
If link is down, just look and follow this instructions:
I used sqlite tool from http://sqlitebrowser.org/.
Sounds like you don't have the execute flag set on the file permissions, try:
chmod u+x program_name
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
use this for horizontal divider
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/honeycombish_blue" />
and this for vertical divider
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/honeycombish_blue" />
OR if you can use the LinearLayout divider, for horizontal divider
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:height="1dp"/>
<solid android:color="#f6f6f6"/>
</shape>
and in LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/divider"
android:orientation="vertical"
android:showDividers="middle" >
If you want to user vertical divider then in place of android:height="1dp"
in shape use android:width="1dp"
Tip: Don't forget the android:showDividers
item.
As per the GNU Make manual and also pointed by 'bobbogo' in the below answer, you can use info / warning / error to display text.
$(error text…)
$(warning text…)
$(info text…)
To print variables,
$(error VAR is $(VAR))
$(warning VAR is $(VAR))
$(info VAR is $(VAR))
'error' would stop the make execution, after showing the error string
check program with this input:abc/if you got something like ab ac bc abc program works well and you need a stronger RAM otherwise the program is wrong.
The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration
to suit your needs.
.animated {_x000D_
-webkit-animation-duration: .5s;_x000D_
animation-duration: .5s;_x000D_
-webkit-animation-fill-mode: both;_x000D_
animation-fill-mode: both;_x000D_
-webkit-animation-timing-function: linear;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
0%, 100% {_x000D_
-webkit-transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
-webkit-transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
@keyframes bounce {_x000D_
0%, 100% {_x000D_
transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
.bounce {_x000D_
-webkit-animation-name: bounce;_x000D_
animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: red;_x000D_
position: relative;_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
position: relative;_x000D_
top: 92px;_x000D_
left: -300px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
Here is how your original keyframe
settings would be interpreted by the browser:
translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 5px in Y axis. This results in a gradual upward movement.translate
by 0px in Y axis. This results in a gradual downward movement.translate
by 0px in Y axis.translate
by 0px in Y axis.I work on the SQL Server team and I can hopefully clarify a few points in this thread (I had not seen it previously, so I am sorry the engineering team has not done so previously).
First, there is no semantic difference between select count(1) from table
vs. select count(*) from table
. They return the same results in all cases (and it is a bug if not). As noted in the other answers, select count(column) from table
is semantically different and does not always return the same results as count(*)
.
Second, with respect to performance, there are two aspects that would matter in SQL Server (and SQL Azure): compilation-time work and execution-time work. The Compilation time work is a trivially small amount of extra work in the current implementation. There is an expansion of the * to all columns in some cases followed by a reduction back to 1 column being output due to how some of the internal operations work in binding and optimization. I doubt it would show up in any measurable test, and it would likely get lost in the noise of all the other things that happen under the covers (such as auto-stats, xevent sessions, query store overhead, triggers, etc.). It is maybe a few thousand extra CPU instructions. So, count(1) does a tiny bit less work during compilation (which will usually happen once and the plan is cached across multiple subsequent executions). For execution time, assuming the plans are the same there should be no measurable difference. (One of the earlier examples shows a difference - it is most likely due to other factors on the machine if the plan is the same).
As to how the plan can potentially be different. These are extremely unlikely to happen, but it is potentially possible in the architecture of the current optimizer. SQL Server's optimizer works as a search program (think: computer program playing chess searching through various alternatives for different parts of the query and costing out the alternatives to find the cheapest plan in reasonable time). This search has a few limits on how it operates to keep query compilation finishing in reasonable time. For queries beyond the most trivial, there are phases of the search and they deal with tranches of queries based on how costly the optimizer thinks the query is to potentially execute. There are 3 main search phases, and each phase can run more aggressive(expensive) heuristics trying to find a cheaper plan than any prior solution. Ultimately, there is a decision process at the end of each phase that tries to determine whether it should return the plan it found so far or should it keep searching. This process uses the total time taken so far vs. the estimated cost of the best plan found so far. So, on different machines with different speeds of CPUs it is possible (albeit rare) to get different plans due to timing out in an earlier phase with a plan vs. continuing into the next search phase. There are also a few similar scenarios related to timing out of the last phase and potentially running out of memory on very, very expensive queries that consume all the memory on the machine (not usually a problem on 64-bit but it was a larger concern back on 32-bit servers). Ultimately, if you get a different plan the performance at runtime would differ. I don't think it is remotely likely that the difference in compilation time would EVER lead to any of these conditions happening.
Net-net: Please use whichever of the two you want as none of this matters in any practical form. (There are far, far larger factors that impact performance in SQL beyond this topic, honestly).
I hope this helps. I did write a book chapter about how the optimizer works but I don't know if its appropriate to post it here (as I get tiny royalties from it still I believe). So, instead of posting that I'll post a link to a talk I gave at SQLBits in the UK about how the optimizer works at a high level so you can see the different main phases of the search in a bit more detail if you want to learn about that. Here's the video link: https://sqlbits.com/Sessions/Event6/inside_the_sql_server_query_optimizer
Short version for easy use:
SELECT *
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())
DATEADD
and GETDATE
are available in SQL Server starting with 2008 version.
MSDN documentation: GETDATE and DATEADD.
To avoid double encoding issue described in taras.roshko's answer and to keep possibility to easily work with query parameters, you can use uriBuilder.Uri.ParseQueryString()
instead of HttpUtility.ParseQueryString()
.
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
If you forward-declare Flight
and Landing
in Event.h
, then you should be fixed.
Remember to #include "Flight.h"
and #include "Landing.h"
in your implementation file for Event
.
The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.
You can't use @android:style/TextAppearance
as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.
To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).
res/values/themes.xml
:
<resources>
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<!-- Change default text colour from dark grey to black -->
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
Manifest:
<application
...
android:theme="@style/MyAppTheme">
A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)
As I learned by asking this question, a better way is to define the colour using a drawable:
<item name="android:textColor">@drawable/default_text_color</item>
...with res/drawable/default_text_color.xml
specifying separate state_enabled="false"
colour:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/darker_gray"/>
<item android:color="@android:color/black"/>
</selector>
To solve problems like this I'm using CSS - fastest & simplest way I think... Just modify it by your needs...
@media only screen and (max-width: 480px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 480px) and (max-width: 768px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 959px) {
#your_id {width:000px;height:000px;}
}
try following:
UPDATE `list` SET `test` = `number`
it creates copy of all values from "number" and paste it to "test"
for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.
adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""
#First Example:
from datetime import datetime, timezone
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)
Output: 1572878043380
#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)
Output: 1572878043
Without any prefixes, e.g. at it's simplest:
.loading-spinner {
animation: rotate 1.5s linear infinite;
}
@keyframes rotate {
to {
transform: rotate(360deg);
}
}
"I don't know why this is happening"
Well I have just run into a possible cause:-) Your HTML page is being assembled from separate files. Perhaps you have files which only contain the body or banner portion of your final page. Those files contain a BOM (0xFEFF) marker. Then as part of the merge process you are running HTML tidy or xmllint over the final merged HTML file.
That will cause it!
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
If you're using Xamarin, I found a guide on their official forum explaining how to do this:
Hereafter, you might also need to update the Google Play Services from the Google Play Store.
Hope this helps for anyone else who has troubles finding the documentation.
If the map is to contain only entries that are known at compile time and the keys to the map are integers, then you do not need to use a map at all.
char get_value(int key)
{
switch (key)
{
case 1:
return 'a';
case 2:
return 'b';
case 3:
return 'c';
default:
// Do whatever is appropriate when the key is not valid
}
}
After copying the the app to the iPhone in the way described by @Jason Weathered, make sure to "chmod +x" of the app, otherwise it won't run.
If the type implements IDisposable, it automatically disposes that type.
Given:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
These are equivalent:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
The second is easier to read and maintain.
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
I found the answer :)
Use JsonPath or XmlPath (in case you have XML) to get data from the response body.
In my case:
JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");
Spent hours figuring out the issue, it's due very generic error by xcode. One of my frameworks was failing with codesign on one of the laptop with below error :
XYZ.framework : unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1
However, there is no Codesign set for this framework and still it fails with codesign error.
Below is the answer:
I have generated new development certificate (with new private key) and installed on my new mac.
this error is not relevant to XYZ.frameowrk. Basically codesign failed while archiving coz we newly created certificate asks "codesign wants to sign using key "my account Name" in your keychain"
and the buttons Always Allow, Deny and Allow
.
Issue was I never accepted it. Once I clicked on Allow. It started working.
Hope this helps.
In addition to the "it is a value" answer, one specific scenario for using structs is when you know that you have a set of data that is causing garbage collection issues, and you have lots of objects. For example, a large list/array of Person instances. The natural metaphor here is a class, but if you have large number of long-lived Person instance, they can end up clogging GEN-2 and causing GC stalls. If the scenario warrants it, one potential approach here is to use an array (not list) of Person structs, i.e. Person[]
. Now, instead of having millions of objects in GEN-2, you have a single chunk on the LOH (I'm assuming no strings etc here - i.e. a pure value without any references). This has very little GC impact.
Working with this data is awkward, as the data is probably over-sized for a struct, and you don't want to copy fat values all the time. However, accessing it directly in an array does not copy the struct - it is in-place (contrast to a list indexer, which does copy). This means lots of work with indexes:
int index = ...
int id = peopleArray[index].Id;
Note that keeping the values themselves immutable will help here. For more complex logic, use a method with a by-ref parameter:
void Foo(ref Person person) {...}
...
Foo(ref peopleArray[index]);
Again, this is in-place - we have not copied the value.
In very specific scenarios, this tactic can be very successful; however, it is a fairly advanced scernario that should be attempted only if you know what you are doing and why. The default here would be a class.
I tried a simple progress bar. It is not clickable just displays the actual percentage. There's a good explication and code here: http://ruwix.com/simple-javascript-html-css-slider-progress-bar/
A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status
, etc.
If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:
# initialize your bare repo
$ git init --bare test-repo.git
# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone
# make an initial commit in the clone
$ touch README.md
$ git add .
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
* [new branch] master -> master
The second time you're referring to div2, you're not using the # id selector.
There's no element named div2.
So you want to create a list of lists... We need to start with an empty list
list_of_lists = []
next, we read the file content, line by line
with open('data') as f:
for line in f:
inner_list = [elt.strip() for elt in line.split(',')]
# in alternative, if you need to use the file content as numbers
# inner_list = [int(elt.strip()) for elt in line.split(',')]
list_of_lists.append(inner_list)
A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom
by_cols = zip(*list_of_lists)
Another common use is to give a name to each column
col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
by_names[col_name] = by_cols[i]
so that you can operate on homogeneous data items
mean_apple_prices = [money/fruits for money, fruits in
zip(by_names['apples revenue'], by_names['apples_sold'])]
Most of what I've written can be speeded up using the csv
module, from the standard library. Another third party module is pandas
, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).
Update While in Python 2 zip(*list_of_lists)
returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists)
returns a zip object that is not subscriptable.
If you need indexed access you can use
by_cols = list(zip(*list_of_lists))
that gives you a list of lists in both versions of Python.
On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...
file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column
If you are facing this issue while using Kotlin and have
kotlin.incremental=true
kapt.incremental.apt=true
in the gradle.properties, then you need to remove this temporarily to fix the build.
After the successful build, you can again add these properties to speed up the build time while using Kotlin.
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?
Any programming language of course serves two goals:
The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.
Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.
Now, switch
could always have been compiled by converting it into the equivalent chain of if-else
blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn switch
into the equivalent if-else
, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).
In this case there are two good reasons for allowing fall-through:
It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the switch
-using C into jump-table–using machine code.
Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit break
when necessary was "natural" for the coder too.
At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.
Four decades later though, things are not quite the same, for a few reasons:
switch
either being turned into if-else
because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.switch
blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.Related to those last two points, consider the following quote from the current edition of K&R:
Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.
As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.
So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.
And when you think about it, code like this:
switch(x)
{
case 1:
foo();
/* FALLTHRU */
case 2:
bar();
break;
}
Is adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.
As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†
Finally, the use of goto
here is already a norm from C and other such languages:
switch(x)
{
case 0:
case 1:
case 2:
foo();
goto below_six;
case 3:
bar();
goto below_six;
case 4:
baz();
/* FALLTHRU */
case 5:
below_six:
qux();
break;
default:
quux();
}
In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use goto
. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a switch
, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the case
as a label in C#. In C# we can get rid of the below_six
label and use goto case 5
which is clearer as to what we are doing. (We'd also have to add break
for the default
, which I left out just to make the above C code clearly not C# code).
In summary therefore:
break
, for easier learning of the language by those familiar with similar languages, and easier porting.goto
-based approach for hitting the same block from different case
labels as is used in C. It just generalises it to some other cases.goto
-based approach more convenient, and clearer, than it is in C, by allowing case
statements to act as labels.All in all, a pretty reasonable design decision
*Some forms of BASIC would allow one to do the likes of GOTO (x AND 7) * 50 + 240
which while brittle and hence a particularly persuasive case for banning goto
, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of nop
fillers.
†Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.
For anyone else that may encounter this problem and it is not solved by either of the options above, this is what worked for me.
1. Click on the website in IIS
2. Double Click on Authentication under IIS
3. Enable Anonymous Authentication
I had disabled this because we were using our own Auth, but that lead to this same problem and the accepted answer did not help in any way.
You can do objects the JavaScript way... It makes no sense but it works ;)
>>> def FakeObject():
... def test():
... print "foo"
... FakeObject.test = test
... return FakeObject
>>> x = FakeObject()
>>> x.test()
foo
Foreach-object operation statement:
$a,$b = 'hi.there' | foreach split .
$a,$b
hi
there
This will keep the \n character, but you can also just wrap the quote in parentheses. Especially useful in RMarkdown.
t <- ("
this is a long
string
")
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
A concise way is to use a tuple as key-value pair:
const keyVal: [string, string] = ["key", "value"] // explicit type
// or
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
[key, value]
tuples also ensure compatibility to JS built-in objects:
Object
, esp. Object.entries
, Object.fromEntries
Map
, esp. Map.prototype.entries
and new Map()
constructorSet
, esp. Set.prototype.entries
You can create a generic KeyValuePair
type for reusability:
type KeyValuePair<K extends string | number, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]
Upcoming TS 4.0 provides named/labeled tuples for better documentation and tooling support:
type KeyValuePairNamed = [key: string, value: string] // add `key` and `value` labels
const [key, val]: KeyValuePairNamed = ["key", "val"] // array destructuring for convenience
No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large
error if headers size exceeds that limit.
Related question: How big can a user agent string get?
you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
Assuming the psql
command-line tool, you may use \copy
instead of copy
.
\copy
opens the file and feeds the contents to the server, whereas copy
tells the server the open the file itself and read it, which may be problematic permission-wise, or even impossible if client and server run on different machines with no file sharing in-between.
Under the hood, \copy
is implemented as COPY FROM stdin
and accepts the same options than the server-side COPY
.
In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation
The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE)
where each window is related to image container by the name arg, make sure to use same name
eg:
import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)
Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.
If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.
If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime
along with session_set_cookie_params
should work for you like this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.
If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.
GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime
, but the upper bound will be unpredictable.
If you don't set session.gc_maxlifetime
to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.
You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.
Do this by saving the upper bound together with the rest of the session data:
session_start(); // ready to go!
$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
// this session has worn out its welcome; kill it and start a brand new one
session_unset();
session_destroy();
session_start();
}
// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;
So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id
when required.
You could use a pseudo element for this, and have your image on a hover:
.image {_x000D_
position: relative;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
transition: all 0.8s;_x000D_
opacity: 0;_x000D_
background: url(http://lorempixel.com/300/200);_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName()
to load a JDBC driver. The JDBC driver should namely register itself in DriverManager
inside a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class MyDriver implements Driver {
static {
DriverManager.registerDriver(new MyDriver());
}
public MyDriver() {
//
}
}
Invoking Class#forName()
will execute all static initializers. This way the DriverManager
can find the associated driver among the registered drivers by connection URL during getConnection()
which roughly look like follows:
public static Connection getConnection(String url) throws SQLException {
for (Driver driver : registeredDrivers) {
if (driver.acceptsURL(url)) {
return driver.connect(url);
}
}
throw new SQLException("No suitable driver");
}
But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver
as well known example, which incorrectly registers itself inside the Constructor instead of a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class BadDriver implements Driver {
public BadDriver() {
DriverManager.registerDriver(this);
}
}
The only way to get it to work dynamically is to call newInstance()
afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance()
away.
I suggest Oj as it is waaaaaay faster than the standard JSON library.
IMHO, There is no need to install all the additional applications/packages.
Check available versions using the command:
> /usr/libexec/java_home -V
Matching Java Virtual Machines (8):
11, x86_64: "Java SE 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9.0.1, x86_64: "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
1.8.0_181-zulu-8.31.0.1, x86_64: "Zulu 8" /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
1.8.0_151, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home
1.6.0_65-b14-468, x86_64: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
1.6.0_65-b14-468, i386: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Now if you want to pick Azul JDK 8 in the above list, and NOT Oracle's Java SE 8, invoke the command as below:
> /usr/libexec/java_home -v 1.8.0_181
/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
To pick Oracle's Java SE 8 you would invoke the command:
> /usr/libexec/java_home -v 1.8.0_151
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
As you can see the version number provided shall be the unique set of strings: 1.8.0_181 vs 1.8.0_151
To get last record from your table..
String selectQuery = "SELECT * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.
Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.
Simply delete that column using: del df['column_name']
I had the same problem, but it turned out to be a chrome extension called hola (or Proxy SwitchySharp), that messed with the proxy settings. Removing Hola fixed the problem
If you could use List
as a data structure to store your data, instead of using Map
to store the result in the value of the Map, you can use following snippet and store the result in the same object.
Here is a Node class:
private class Node {
public int row, col, distance;
public Node(int row, int col, int distance) {
this.row = row;
this.col = col;
this.distance = distance;
}
public boolean equals(Object o) {
return (o instanceof Node &&
row == ((Node) o).row &&
col == ((Node) o).col);
}
}
If you store your result in distance variable and the items in the list are checked based on their coordinates, you can use the following to change the distance to a new one with the help of lastIndexOf method as long as you only need to store one element for each data:
List<Node> nodeList;
nodeList = new ArrayList<>(Arrays.asList(new Node(1, 2, 1), new Node(3, 4, 5)));
Node tempNode = new Node(1, 2, 10);
if(nodeList.contains(tempNode))
nodeList.get(nodeList.lastIndexOf(tempNode)).distance += tempNode.distance;
It is basically reimplementing Set
whose items can be accessed and changed.
The solution to this issue is:
Step 1: Stop Tomcat(By service or by .bat/.sh what ever the case may be ).
Step 2: Delete the already configured Apache Tomcat on eclipse.
Step 3: Now reconfigure the apache on the eclipse and start the server using UI as provided by eclipse.
I have the same issue and it has worked.
when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:
$(function() {
$("#my-iframe").bind("load",function(){
$(this).contents().find("[tokenid=" + token + "]").html();
});
});
The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new
can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.
To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.
A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.
As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.
Required Launch Icon And Splash Image size
I hosted my Flask Application on Google Cloud Platform Virtual Machine.
I started the app using python main.py
But the problem was ctrl+c did not work to stop the server.
This command $ sudo netstat -tulnp | grep :5000
terminates the server.
My Flask app runs on port 5000 by default.
It works for this. Haven't tested for other platforms. Feel free to update or comment if it works for other versions too.
To specify any additional asset folder I've used this with my Gradle. This adds moreAssets
, a folder in the project root, to the assets.
android {
sourceSets {
main.assets.srcDirs += '../moreAssets'
}
}
I wanted to remotely watch a yum upgrade process that had been run locally, so while there were probably more efficient ways to do this, here's what I did:
watch cat /dev/vcsa1
Obviously you'd want to use vcsa2, vcsa3, etc., depending on which terminal was being used.
So long as my terminal window was of the same width as the terminal that the command was being run on, I could see a snapshot of their current output every two seconds. The other commands recommended elsewhere did not work particularly well for my situation, but that one did the trick.
Quick solution in NetBeans 6.8.
In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.
You also can see my short Video How-To.
drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:
newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)
and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.
Let's try to take an example and understand:
I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.
Where Y <commit-id> = <master> branch commits - few commits
Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:
Step 1:
git checkout -b local origin/new
where local is the branch name. Any name can be given.
Step 2:
git merge origin/master --no-ff --stat -v --log=300
Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.
For more information and parameters about Git merge, please refer to:
git merge --help
Also if you need to merge a specific commit, then you can use:
git cherry-pick <commit-id>
That is usually all that you need to do...
Are you sure that after 20 minutes, the reason that the session is being lost is from being idle though...
There are many reasons as to why the session might be cleared. You can enable event logging for IIS and can then use the event viewer to see reasons why the session was cleared...you might find that it is for other reasons perhaps?
You can also read the documentation for event messages and the associated table of events.
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
The reason it is throwing that exception is because you have the argument rb
, which opens the file in binary mode. Change that to r
, which will by default open the file in text mode.
Your code:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
New code:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)
Simply use the administrative shares to copy files between systems. It's much easier this way.
Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;
By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.
This only works when a PowerShell session runs under the user who has rights to both administrative shares.
I suggest to use regular network share on server B with read-only access to everyone and simply call (from Server A):
Copy-Item -Path "\\\ServerB\SharedPathToSourceFile" -Destination "$Env:USERPROFILE" -Force -PassThru -Verbose
you need to write this structure on your bean configuration (this is your datasource):
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="${hibernate.dataSourceClassName}" />
<property name="maximumPoolSize" value="${hibernate.hikari.maximumPoolSize}" />
<property name="idleTimeout" value="${hibernate.hikari.idleTimeout}" />
<property name="dataSourceProperties">
<props>
<prop key="url">${dataSource.url}</prop>
<prop key="user">${dataSource.username}</prop>
<prop key="password">${dataSource.password}</prop>
</props>
</property>
</bean>
<!-- HikariCP configuration -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
This is my example and it is working. You just need to put your properties on hibernate.properties and set it before:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>
Obs.: the versions are
log4j: 1.2.16
springframework: 3.1.4.RELEASE
HikariCP: 1.4.0
Properties file (hibernate.properties):
hibernate.dataSourceClassName=oracle.jdbc.pool.OracleDataSource
hibernate.hikari.maximumPoolSize=10
hibernate.hikari.idleTimeout=30000
dataSource.url=jdbc:oracle:thin:@localhost:1521:xe
dataSource.username=admin
dataSource.password=
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
I solved the problem like this:
It works perfectly.
DATA : V_LINES TYPE I. "declare variable
DESCRIBE TABLE <ITAB> LINES V_LINES. "get no of rows
WRITE:/ V_LINES. "display no of rows
Refreance: http://www.sapnuts.com/courses/core-abap/internal-table-work-area.html
Just go to http://java.com/en/download/ and update your version of JRE
Node.js as a background service in WINDOWS XP
Installation:
Create c:\node\helloworld.js
// http://howtonode.org/hello-node
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Open command console and type the following (setx only if Resource Kit is installed)
C:\node> set path=%PATH%;%CD%
C:\node> setx path "%PATH%"
C:\node> set NODE_PATH="C:\Program Files\nodejs\node_modules"
C:\node> git config --system http.sslcainfo /bin/curl-ca-bundle.crt
C:\node> git clone --recursive git://github.com/isaacs/npm.git
C:\node> cd npm
C:\node\npm> node cli.js install npm -gf
C:\node> cd ..
C:\node> nssm.exe install node-helloworld "C:\Program Files\nodejs\node.exe" c:\node\helloworld.js
C:\node> net start node-helloworld
A nifty batch goodie is to create c:\node\ServiceMe.cmd
@echo off
nssm.exe install node-%~n1 "C:\Program Files\nodejs\node.exe" %~s1
net start node-%~n1
pause
Service Management:
Dictionary:
Hashtable:
you can set the default value with empty_data
$builder->add('myField', 'number', ['empty_data' => 'Default value'])
On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)
My Mac decided to restart itself randomly; causing a whole slew of errors. One of which, was mysql refusing to start up properly. I went through many SO questions/answers as well as other sites.
Ultimately what ended up resolving MY issue was this:
1) Creating the file (/usr/local/mysql/data/.local.pid
2) chmod 777 on that file
3) executing mysql.server start (mine was located in/usr/local/bin/mysql.server)
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
This Error comes due to same table exist in 2 database like you have a database for project1 and in which you have table emp and again you have another database like project2 and in which you have table emp then when you try to insert something inside the database with-out your database name then you will get an error like about
Solution for that when you use mysql query then also mention database name along with table name.
OR
Don't Use Reserved key words like KEY as column name
To render SVG file you can use Macaw. Also Macaw supports transformations, user events, animation and various effects.
You can render SVG file with zero lines of code. For more info please check this article: Render SVG file with Macaw.
DISCLAIMER: I am affiliated with this project.
If you're on CentOS make sure you have the YUM package "python-setuptools" installed
yum install python-setuptools
Fixed it for me.
The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads:
The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request.
Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case).
I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore?
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
Swift 5
button.layer.borderWidth = 2
To change the colour of the border use
button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
This is perfectly legal:
public static void main(String[] args) {
}
public static void main(String argv) {
System.out.println("hello");
}
In case you were struggling to change linetypes
, the following answer should be helpful. (This is an addition to the solution by Andy W.)
We will try to extend the learned pattern:
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) + #red
geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) + #blue
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_linetype_manual(values=line_types)+
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
However, what we get is the following result:
The problem is that the linetype
is not merged in the main legend.
Note that we did not give any name to the method scale_linetype_manual
.
The trick which works here is to give it the same name as what you used for naming scale_colour_manual
.
More specifically, if we change the corresponding line to the following we get the desired result:
scale_linetype_manual(name="Error Bars",values=line_types)
Now, it is easy to change the size of the line with the same idea.
Note that the geom_bar
has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar
with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.
Had the same issue. It was resolved as described above.
In my index.js
var port = 1338,
express = require('express'),
app = express().use(express.static(__dirname + '/')),
http = require('http').Server(app),
io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(port, function(){
console.log("Node server listening on port " + port);
});
and in my index.html
<!doctype html>
<html>
<head>
<title>
My page
</title>
</head>
<body>
<script src = "lib/socket.io.js"></script>
<script src = "lib/three.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js">
through some dark magic (since there is physically a node_modules and lib directory in between) .
If You installed SQL Express or any .Net Server then you need to stop. open cmd in administrator mode and type this line ...
net stop Was
now start apache
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:
https://github.com/facebook/facebook-android-sdk.git
git://github.com/facebook/facebook-android-sdk.git
You can add your custom Css:
.pagination{
display:table;
margin:0 auto;
}
Thank you
You can use sp_rename
to rename a column.
USE YourDatabase;
GO
EXEC sp_rename 'TableName.OldColumnName', 'NewColumnName', 'COLUMN';
GO
The first parameter is the object to be modified, the second parameter is the new name that will be given to the object, and the third parameter COLUMN informs the server that the rename is for the column
, and can also be used to rename tables
, index
and alias data type
.
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.
Http GET returning 204 is perfectly fine, and so is returning 404.
The important thing is that you define the design standards/guidelines for your API, so that all your endpoints use status codes consistently.
For example:
GET /complaints/year/2019/month/04
may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204). OTOH, GET /complaints/12345
may return 404 if complaint number 12345 doesn't exist.This is a little bit to old but: Solutions like is obsolete. Let the server handle the cache or not cache (in the response). The only way to guarantee no caching (thinking about new versions in production) is to change the js or css file with a version number. I do this with webpack.
datetime.strptime
is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
The resulting datetime
object is timezone-naive.
Links:
Python documentation for strptime
/strftime
format strings: Python 2, Python 3
strftime.org is also a really nice reference for strftime
Notes:
strptime
= "string parse time"strftime
= "string format time"I know this question was asked 2 years ago, but I run into the same issue and the answer for the problem is since ES2017, that you can simply await
the functions return value (as of now, only works in async
functions), like:
let AuthUser = function(data) {
return google.login(data.username, data.password).then(token => { return token } )
}
let userToken = await AuthUser(data)
console.log(userToken) // your data
I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.
print("code sample");
select top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18 union
select 19 union
select 20 union
select 21
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");
Use setTimeout function with either of the following
// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";
setTimeout(function(){
window.location.replace("http://www.google.com");
}, 1000)
In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did.
@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)
Well, it might help someone. I was stupid enough to put var_dump('testing');
in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json
response, and with dataType
set to json
defined, the request fails.
Include this dependencies in your POM.xml and run Maven -> Update
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.
If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.
If you prefer using method (lambda) syntax as I do, you could do the same thing like this:
var result = new TableName();
using(var db = new EFObjectContext)
{
var query = db.TableName;
query = value1 == null
? query.Where(tbl => tbl.entry1 == null)
: query.Where(tbl => tbl.entry1 == value1);
query = value2 == null
? query.Where(tbl => tbl.entry2 == null)
: query.Where(tbl => tbl.entry2 == value2);
result = query
.Select(tbl => tbl)
.FirstOrDefault();
// Inspect the value of the trace variable below to see the sql generated by EF
var trace = ((ObjectQuery<REF_EQUIPMENT>) query).ToTraceString();
}
return result;
EDIT: As pointed out in recent comments, this solution may BREAK your system.
You most likely don't want to remove python3.
Please refer to the other answers for possible solutions.
Outdated answer (not recommended)
sudo apt-get remove 'python3.*'
I assume the array i is ascend sorted, here is another solution with Iterator, it is more generic:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");
int i[] = {1,3,5};
Iterator<String> itr = list.iterator();
int pos = 0;
int index = 0;
while( itr.hasNext() ){
itr.next();
if( pos >= i.length ){
break;
}
if( i[pos] == index ){
itr.remove();
pos++;
}
index++;
}
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
I encountered this issue while importing some of the files from the Add Health data into R (see: http://www.icpsr.umich.edu/icpsrweb/ICPSR/studies/21600?archive=ICPSR&q=21600 ) For example, the following command to read the DS12 data file in tab separated .tsv format will generate the following error:
ds12 <- read.table("21600-0012-Data.tsv", sep="\t", comment.char="",
quote = "\"", header=TRUE)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines,
na.strings, : line 2390 did not have 1851 elements
It appears there is a slight formatting issue with some of the files that causes R to reject the file. At least part of the issue appears to be the occasional use of double quotes instead of an apostrophe that causes an uneven number of double quote characters in a line.
After fiddling, I've identified three possible solutions:
Open the file in a text editor and search/replace all instances of a quote character " with nothing. In other words, delete all double quotes. For this tab-delimited data, this meant only that some verbatim excerpts of comments from subjects were no longer in quotes which was a non-issue for my data analysis.
With data stored on ICPSR (see link above) or other archives another solution is to download the data in a new format. A good option in this case is to download the Stata version of the DS12 and then open it using the read.dta command as follows:
library(foreign)
ds12 <- read.dta("21600-0012-Data.dta")
A related solution/hack is to open the .tsv file in Excel and re-save it as a tab separated text file. This seems to clean up whatever formatting issue makes R unhappy.
None of these are ideal in that they don't quite solve the problem in R with the original .tsv file but data wrangling often requires the use of multiple programs and formats.
pid_t tid = syscall(SYS_gettid);
Linux provides such system call to allow you get id of a thread.
I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.
I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Update (2016-07-22): Type check for Button
and ImageButton
changed to look for IButtonControl
to allow postbacks from third party controls to be recognized.
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
Main advantage of <jsp:include />
over <%@ include >
is:
<jsp:include />
allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%@include file="somefile.jsp" %>
You are trying to use the string as a function:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)
parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format()
:
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
I use the following piece of CSS and JavaScript. It uses an extra class dropdown-submenu
. I tested it with Bootstrap 4 beta.
It supports multi level sub menus.
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {_x000D_
if (!$(this).next().hasClass('show')) {_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
}_x000D_
var $subMenu = $(this).next('.dropdown-menu');_x000D_
$subMenu.toggleClass('show');_x000D_
_x000D_
_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass('show');_x000D_
});_x000D_
_x000D_
_x000D_
return false;_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu a::after {_x000D_
transform: rotate(-90deg);_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: .8em;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
margin-left: .1rem;_x000D_
margin-right: .1rem;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
__call__
is also used to implement decorator classes in python. In this case the instance of the class is called when the method with the decorator is called.
class EnterExitParam(object):
def __init__(self, p1):
self.p1 = p1
def __call__(self, f):
def new_f():
print("Entering", f.__name__)
print("p1=", self.p1)
f()
print("Leaving", f.__name__)
return new_f
@EnterExitParam("foo bar")
def hello():
print("Hello")
if __name__ == "__main__":
hello()
program output:
Entering hello
p1= foo bar
Hello
Leaving hello
You have to use UPDATE instead of INSERT:
For Example:
UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
I see only two options:
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:
import static org.mockito.Mockito.*;
In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:
ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());
List<MyExampleClass> passedArguments = argument.getAllValues();
for (MyExampleClass data : passedArguments){
//assertSometing ...
System.out.println(data.getFoo());
}
The list of all passed arguments during your test is accessible via the argument.getAllValues() method.
The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.
It worked for me, when I set error_reporting in two places at same time
somewhere in PHP code
ini_set('error_reporting', 30711);
and in .htaccess file
php_value error_reporting 30711
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
Because setting the div
's display
style property to ""
doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.
You need to set it to something that has a value:
document.getElementById('mybox').style.display = "block";
What you're doing would work if you were replacing an inline style on the div, like this:
<div id="myBox" style="display: none;"></div>
document.getElementById('mybox').style.display = "";
If the script does its job (relatively) well, then it's running okay. Your problem is probably a single line in the file referencing a program that's either not on the path, not installed, misspelled, or something similar.
One way is to place a set -x
at the top of your script or run it with bash -x
instead of just bash
- this will output the lines before executing them and you usually just need to look at the command output immediately before the error to see what's causing the problem
If, as you say, it's the blank lines causing the problems, you might want to check what's actaully in them. Run:
od -xcb testscript.sh
and make sure there's no "invisible" funny characters like the CTRL-M
(carriage return) you may get by using a Windows-type editor.
you need to prevent the default behavior of your form when submitting
by adding this:
$("#postcontent").on('submit' , function(e) {
e.preventDefault();
//then the rest of your code
}
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
Some useful Excel automation in C# , u can find from the following link.
http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
bolton.
Copy the cell. Paste special as link. Will update with original. No formula though.
Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object. for example when result is a
List<T>
and you're putting the result into a single T object.
In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.
Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...
As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).
On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).
If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.
For example: http://p2pkit.io or google nearby
Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.
To get the last executed query in laravel,We will use DB::getQueryLog()
function of laravel it return all executed queries. To get last query we will use end()
function which return last executed query.
$student = DB::table('student')->get();
$query = DB::getQueryLog();
$lastQuery = end($query);
print_r($lastQuery);
I have taken reference from http://www.tutsway.com/how-to-get-the-last-executed-query-in-laravel.php.
Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).
You've described it as a public instance field; to get this via reflection:
object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);
If it is actually a property (not a field):
string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);
If it is non-public, you'll need to use the BindingFlags
overload of GetField
/GetProperty
.
Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?
Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.
Here is the code
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
onPressed: () {},
child: Icon(
Icons.call,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.message,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.block,
color: Colors.red,
)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
' Call',
),
Text(
'Message',
),
Text(
'Block',
style: TextStyle(letterSpacing: 2.0, color: Colors.red),
),
],
),
],
),
This is an example of using XOR(^), from this answer
byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };
byte[] array_3 = new byte[6];
int i = 0;
for (byte b : array_1)
array_3[i] = b ^ array_2[i++];
Output
0 0 1 1 1 0
You could do this using my Common Node library:
function get(url) {
return new (require('httpclient').HttpClient)({
method: 'GET',
url: url
}).finish().body.read().decodeToString();
}
var a = get('www.example.com/api_1.php'),
b = get('www.example.com/api_2.php'),
c = get('www.example.com/api_3.php');
refer johnml1135
answer, but not fully work.
after self investigate, work now:
as official say:
????
????????????????????? /sdcard/Download ???????? API ?????????????,?? API 22,?????:Settings > Device:Storage & USB > Internal Storage > Explore(?? SD ?)?
and use Drag and Drop
actually worked, but use android self installed app Download
, then you can NOT find the copied file, for not exist so called /sdcard/Download
folder.
finally using other file manager app, like
then can see the really path is
/storage/emulated/0/Download/
which contains the copied files, like
/storage/emulated/0/Download/chenhongyu_lixiangsanxun.mp3
after drag and drop more mp3 files:
The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.
When running publicly rather than in development, you should not use the built-in development server (
flask run
). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:
$ pip install waitress
You need to tell Waitress about your application, but it doesn’t use
FLASK_APP
like flask run does. You need to tell it to import and call the application factory to get an application object.$ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080
Or you can use waitress.serve()
in the code instead of using the CLI command.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
$ python hello.py
You should find them by default in a folder like /etc/my.cnf
, maybe also depends on versions. From MySQL Configuration File:
Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.
There are a few switches to package managers to list specific files.
RPM Sytems:
There are switches to rpm
command, -q
for query, and -c
or --configfiles
to list config files. There is also -l
or --list
The --configfiles
one didn't quiet work for me, but --list
did list a few .cnf
files held by mysql-server
rpm -q --list mysql-server
DEB Systems:
Also with limited success: dpkg --listfiles mysql-server
UPDATE Sept 2015
This answer continues to get upvotes, so I'm going to leave it here since it seems to be helpful to some people, but please check out the other answers from @reexmonkey and @Pressacco first. They may provide better results.
ORIGINAL ANSWER
Give this a shot:
That should cause those messages to disappear.
I saved my web.xsd in the root of my web folder (which might not be the best place for it, but just for demonstration purposes) and my Schemas property looks like this:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\xml\Schemas\DotNetConfig.xsd" "Web.xsd"
There are a few issues here. Firstly, the async load method you specified:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery', '1.3.1');
google.setOnLoadCallback(function() {
// do stuff
});
</script>
has a couple of issues. Script tags pause the page load while they are retrieved (if necessary). Now if they're slow to load this is bad but jQuery is small. The real problem with the above method is that because the jquery.js load happens independently for many pages, they will finish loading and render before jquery has loaded so any jquery styling you do will be a visible change for the user.
The other way is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
Try some simple examples like, have a simple table and change the background of the cells to yellow with the setOnLoadCallback() method vs $(document).ready() with a static jquery.min.js load. The second method will have no noticeable flicker. The first will. Personally I think that's not a good user experience.
As an example run this:
<html>
<head>
<title>Layout</title>
<style type="text/css">
.odd { background-color: yellow; }
</style>
</head>
<body>
<table>
<tr><th>One</th><th>Two</th></tr>
<tr><td>Three</td><td>Four</td></tr>
<tr><td>Five</td><td>Six</td></tr>
<tr><td>Seven</td><td>Nine</td></tr>
<tr><td>Nine</td><td>Ten</td></tr>
</table>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function() {
$(function() {
$("tr:odd").addClass("odd");
});
});
</script>
</body>
</html>
You (should) see the table appear and then the rows go yellow.
The second problem with the google.load() method is that it only hosts a limited range of files. This is a problem for jquery since it is extremely plug-in dependent. If you try and include a jquery plugin with a <script src="...">
tag and google.load()
the plug-in will probably fail with messages of "jQuery is not defined" because it hasn't loaded yet. I don't really see a way around this.
The third problem (with either method) is that they are one external load. Assuming you have some plugins and your own Javascript code you're up to a minimum of two external requests to load your Javascript. You're probably better off getting jquery, all relevant plug-ins and your own code and putting it into one minified file.
From Should You Use Google's Ajax Libraries API for Hosting?:
As to load times, you're actually loading two scripts - the jsapi script and the mootools script (the compressed version from above). So that is two connections, rather than one. In my experience, I found that the load time was actually 2-3 times slower than loading from my own personal shared server, even though it was coming from Google, and my version of the compressed file was a couple of K larger than Google's. This, even after the file had loaded and (presumably) cached. So for me, since the bandwidth doesn't matter much, isn't going to matter.
Lastly you have the potential problem of a paranoid browser flagging the request as some sort of XSS attempt. It's not typically a problem with default settings but on corporate networks where the user may not have control over which browser they use let alone the security settings you may have a problem.
So in the end I can't really see me using the Google AJAX API for jQuery at least (the more "complete" APIs are a different story in some ways) much except to post examples here.
I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):
private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
if (updateSales == null) {
updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
}
updateSales.setInt(1, sales);
updateSales.setString(2, cof_name);
updateSales.executeUpdate();
}
At that point, it is then just a matter of calling:
updateSales(75, "Colombian");
Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...
Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.
There are at least these two issues I have observed for this problem: 1) It could be either because your sender username or password might not be correct 2) Or it could be as answered by Avinash above, the security condition on the account. Once you try SendMail using SMTP, you normally get a notification in to your account that it may be an unauthorized attempt to access your account, if not user can follow the link to turn the settings to lessSecureApp. Once this is done and smtp SendMail is tried again, it works.
Yes, you can do this using introspection. Make a GraphQL query like (for type UserType)
{
__type(name:"UserType") {
fields {
name
description
}
}
}
and you'll get a response like (actual field names will depend on your actual schema/type definition)
{
"data": {
"__type": {
"fields": [
{
"name": "id",
"description": ""
},
{
"name": "username",
"description": "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
},
{
"name": "firstName",
"description": ""
},
{
"name": "lastName",
"description": ""
},
{
"name": "email",
"description": ""
},
( etc. etc. ...)
]
}
}
}
You can then read this list of fields in your client and dynamically build a second GraphQL query to get all of these fields.
This relies on you knowing the name of the type that you want to get the fields for -- if you don't know the type, you could get all the types and fields together using introspection like
{
__schema {
types {
name
fields {
name
description
}
}
}
}
NOTE: this is the over-the-wire GraphQL data -- you're on your own to figure out how to read and write with your actual client. Your graphQL javascript library may already employ introspection in some capacity, for example the apollo codegen command uses introspection to generate types.
In addition to Salvador Dali's answer:
on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.
Otherwise decoding won't work: the image will be saved but it will be an unreadable file.
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
I just went through this on Mountain Lion. Homebrew blocked on libiconv which it thought was missing but was actually up to date. After an hour of trying to get it to recognize libiconv, I gave up and installed it the old fashion way, which took all of five minutes...
(download your php version)
$ wget http://www.php.net/get/php-5.3.21.tar.gz/from/a/mirror
$ tar -xvzf php-5.3.21.tar.gz
$ cd php-5.3.21/ext/mcrypt
$ phpize
$ ./configure
$ make
$ make test
$ sudo make install
mcrypt.so is now in your PHP ext dir (/usr/lib/php/extensions/no-debug-non-zts-20090626/
in my case), now you need to add to php.ini as a module
$ vi /etc/php.ini
$ (insert) extension=mcrypt.so
$ sudo apachectl restart
Done - no brew necessary. HTH someone.
Have you considered using the "xcopy" command?
The xcopy command will do all that for you.
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
Depending on the device, sometimes you are getting "The folder you specified doesn't contain a compatible software" error because the first interface isn't actually the ADB interface.
Try installing it as a generic "USB composite device" instead (from the 'pick from a list' driver install option); once the standard composite driver installs it will allow Windows to communicate with the device and detect the associated ADB driver interface and install it properly.
If you define operator<<
as a member function it will have a different decomposed syntax than if you used a non-member operator<<
. A non-member operator<<
is a binary operator, where a member operator<<
is a unary operator.
// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
struct MyObj
{
// This is a member unary-operator, hence one argument
MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
int value = 8;
};
// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
return os << myObj.value;
}
So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...)
syntax in your head to make things make sense.
MyObj mo;
// Calling the unary operator
mo << std::cout;
// which decomposes to...
mo.operator<<(std::cout);
Or you could attempt to call the non-member binary operator:
MyObj mo;
// Calling the binary operator
std::cout << mo;
// which decomposes to...
operator<<(std::cout, mo);
You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int)
to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.
Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.
Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)
struct MyObj
{
// Note that we now return the ostream
std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
int value = 8;
};
This syntax will irritate many coders now....
MyObj mo;
mo << std::cout << "Words words words";
// this decomposes to...
mo.operator<<(std::cout) << "Words words words";
// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");
Note how the cout
is the second argument in the chain here.... odd right?
AppData ? Local aka (C:\Users\<user>\AppData\Local
):
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
AppData ? Roaming aka (C:\Users\<user>\AppData\Roaming
):
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Additionally, it could be handy to know:
Environment.SpecialFolder.ProgramFiles
- for Program files X64 folderEnvironment.SpecialFolder.ProgramFilesX86
- for Program files X86 folderFor the full list check here.
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
or this way:
std::set<int, decltype(&cmp)> s(&cmp);
()
operatorstruct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
Finally, use the struct as comparator
std::set<X, Cmp> set;
Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.
Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en
from os import system, remove
from uuid import uuid4
def bash_(shell_command: str) -> tuple:
"""
:param shell_command: your shell command
:return: ( 1 | 0, stdout)
"""
logfile: str = '/tmp/%s' % uuid4().hex
err: int = system('%s &> %s' % (shell_command, logfile))
out: str = open(logfile, 'r').read()
remove(logfile)
return err, out
# Example:
print(bash_('cat /usr/bin/vi | wc -l'))
>>> (0, '3296\n')```
SELECT
CASE WHEN LEN(listing.OfferText) > 0 THEN listing.OfferText
ELSE COALESCE(Company.OfferText, '') END
AS Offer_Text,
...
In this example, if listing.OfferText
is NULL, the LEN() function should also return NULL, but that's still not > 0.
Update
I've learned some things in the 5 1/2 years since posting this, and do it much differently now:
COALESCE(NULLIF(listing.OfferText,''), Company.OfferText, '')
This is similar to the accepted answer, but it also has a fallback in case Company.OfferText
is also null. None of the other current answers using NULLIF()
also do this.
function ArrayToObject( arr ) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
var name = arr[i].name;
var value = arr[i].value;
obj[name] = arr[i].value;
}
return obj;
}
var form_data = $('#my_form').serializeArray();
form_data = ArrayToObject( form_data );
form_data.action = event.target.id;
form_data.target = event.target.dataset.event;
console.log( form_data );
$.post("/api/v1/control/", form_data, function( response ){
console.log(response);
}).done(function( response ) {
$('#message_box').html('SUCCESS');
})
.fail(function( ) { $('#message_box').html('FAIL'); })
.always(function( ) { /*$('#message_box').html('SUCCESS');*/ });
One way(in one line) to do it is like this:
listemail.Add(new EmailData {FirstName = "John", LastName = "Smith", Location = "Los Angeles"});
I have a code very similar to yours and if it works onPause () and onResume (). When changing the fragment, these functions are activated respectively.
Code in fragment:
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, proximidad, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, brillo, SensorManager.SENSOR_DELAY_NORMAL);
Log.e("Frontales","resume");
}
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
Log.e("Frontales","Pause");
}
Log when change of fragment:
05-19 22:28:54.284 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:28:57.002 2371-2371/madi.cajaherramientas E/Frontales: Pause
05-19 22:28:58.697 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:29:00.840 2371-2371/madi.cajaherramientas E/Frontales: Pause
05-19 22:29:02.248 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:29:03.718 2371-2371/madi.cajaherramientas E/Frontales: Pause
Fragment onCreateView:
View rootView;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_proximidad, container, false);
ButterKnife.bind(this,rootView);
inflar();
setTextos();
return rootView;
}
Action when I pulse back (in the activity where I load the fragment):
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
How about this:
< jQuery 1.7
$("#input").bind("propertychange change keyup paste input", function(){
// do stuff;
});
> jQuery 1.7
$("#input").on("propertychange change keyup paste input", function(){
// do stuff;
});
This works in IE8/IE9, FF, Chrome
I just ran over this one and I found by accident that CLOBs can be used in a like query:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE TEST_SCRIPT LIKE '%something%'
AND ID = '10000239'
This worked also for CLOBs greater than 4K
The Performance won't be great but that was no problem in my case.
To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.
It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.
You may want to consider posting your second question in another topic.
Add the outerheight to the top and you have the bottom, relative to the parent element:
var $el = $('#bottom'); //record the elem so you don't crawl the DOM everytime
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin
With absolutely positioned elements or when positioning relative to the document, you will need to instead evaluate using offset:
var bottom = $el.offset().top + $el.outerHeight(true);
As pointed out by trnelson this does not work 100% of the time. To use this method for positioned elements, you also must account for offset. For an example see the following code.
var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);
Is it acceptable & safe to run
pip install
undersudo
?
It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'?
To install Python package in your home directory you don't need root privileges. See description of --user
option to pip.
In addition with what @Camilo Silva already mentioned, if you want to give free access to create databases, read, write databases, etc, but you don't want to create a root role, you can change the 3rd step with the following:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" } ]
}
)
Maybe this way:
const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map((k, v) => [k, v * 2]); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
You would only need to monkey patch Map
before:
Map.prototype.map = function(func){
return new Map(Array.from(this, ([k, v]) => func(k, v)));
}
We could have wrote a simpler form of this patch:
Map.prototype.map = function(func){
return new Map(Array.from(this, func));
}
But we would have forced us to then write m.map(([k, v]) => [k, v * 2]);
which seems a bit more painful and ugly to me.
We could also map values only, but I wouldn't advice going for that solution as it is too specific. Nevertheless it can be done and we would have the following API:
const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map(v => v * 2); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
Just like before patching this way:
Map.prototype.map = function(func){
return new Map(Array.from(this, ([k, v]) => [k, func(v)]));
}
Maybe you can have both, naming the second mapValues
to make it clear that you are not actually mapping the object as it would probably be expected.
I think you are a bit confused on the purpose of custom data attributes. From the w3 spec
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
By itself an attribute of data-toggle=value
is basically a key-value pair, in which the key is "data-toggle" and the value is "value".
In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.
Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".
Button Toggle
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
The context that the code provides shows that Bootstrap is using the data-toggle
attribute as a custom query selector to process the particular element.
From what I see these are the data-toggle options:
You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle
attribute toggles the element to active or not.
If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':
$pdf->Output('name.pdf', 'D');
If you are working with Application Pool authentication (instead of IUSR), which you should, then this list of checks by Jean Sun is the very best I could find to deal with 401 errors in IIS:
Open IIS Manager, navigate to your website or application folder where the site is deployed to.
Run the following command:
icacls <path_to_site> /grant "IIS APPPOOL\<app_pool_name>"(CI)(OI)(M)
For example:
icacls C:\inetpub\wwwroot\mysite\ /grant "IIS APPPOOL\DEFAULTAPPPOOL":(CI)(OI)(M)
Especially steps 5. & 6. are often overlooked and rarely mentioned on the web.
There is an excellent tutorial on how to create a library for the Arduino platform. A library is basically a class, so it should show you how its all done.
On Arduino you can use classes, but there are a few restrictions:
You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE.
Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n
string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe";
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();
I don't have an 11g instance available today but could you not use:
SELECT group_id,
LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
FROM (
SELECT UNIQUE
group_id,
name
FROM demotable
)
GROUP BY group_id
create_function
did not work for me inside a class. I had to use call_user_func
.
<?php
class Dispatcher {
//Added explicit callback declaration.
var $callback;
public function Dispatcher( $callback ){
$this->callback = $callback;
}
public function asynchronous_method(){
//do asynch stuff, like fwrite...then, fire callback.
if ( isset( $this->callback ) ) {
if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
}
}
}
Then, to use:
<?php
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();
function do_callback( $data ){
print 'Data is: ' . $data . "\n";
}
?>
[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.
As an addition to the main answers, which are good, comprehensive and accurate, I would like to comment about the article you reference - the one that says "throwing exceptions in destructors is not so bad".
The article takes the line "what are the alternatives to throwing exceptions", and lists some problems with each of the alternatives. Having done so it concludes that because we can't find a problem-free alternative we should keep throwing exceptions.
The trouble is is that none of the problems it lists with the alternatives are anywhere near as bad as the exception behaviour, which, let's remember, is "undefined behaviour of your program". Some of the author's objections include "aesthetically ugly" and "encourage bad style". Now which would you rather have? A program with bad style, or one which exhibited undefined behaviour?
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
If you are using Cloudflare then this is always the Cloudflare IP address from the node which is serving you.
In this case you get the real IP address from the $_SERVER['HTTP_FORWARDED_FOR']
entry as described in the the other answers.
If you know the type of numbers you are going to store, your can choose accordingly. In this case your have 'id' which can never be negative. So you can use unsigned int. Range of signed int: -n/2 to +n/2 Range of unsigned int: 0 to n So you have twice the number of positive numbers available. Choose accordingly.
I think the best way to use react-router-dom Link in a MenuItem (and other MaterialUI component such as buttons) is to pass the Link in the "component" prop
<Menu>
<MenuItem component={Link} to={'/first'}>Team 1</MenuItem>
<MenuItem component={Link} to={'/second'}>Team 2</MenuItem>
</Menu>
you need to pass the route path in the 'to' prop of the "MenuItem" (which will be passed down to the Link component). In this way you don't need to add any style as it will use the MenuItem style
Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly or when they are not needed. The correct statement is below:
Update Table1
Set SomeField = t2.SomeFieldValue
From Table1 t1
Inner Join Table2 as t2
On t1.ID = t2.ID
Notice that SomeField
column from Table1 doesn't have the t1
qualifier as t1.SomeField
but is just SomeField
.
If one tries to update it by specifying t1.SomeField
the statement will return the multi-part error that you have noticed.
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
A simple navbar with bootstrap can be done as:
<li class="{{ Request::is('user/profile')? 'active': '' }}">
<a href="{{ url('user/profile') }}">Profile </a>
</li>
It's a very interesting question.
You can use both of them, there's not any strict rule about this subject, but using URI path variables has some advantages:
But if you use path variables, all of this services can cache your GET requests.
It gives the user more information about the structure of the data.
But if your data doesn't have any hierarchy relation you can still use Path variables, using comma or semi-colon:
/City/longitude,latitude
As a rule, use comma when the ordering of the parameters matter, use semi-colon when the ordering doesn't matter:
/IconGenerator/red;blue;green
Apart of those reasons, there are some cases when it's very common to use query string variables:
http:// www.google.com/search?q=rest
To sum up, there's not any strong reason to use one of this methods but whenever you can, use URI variables.
If you're comparing them in unit test, a handy alternative is EqualValues function in testify.
This is the best method for select text in dropdownlist.
$("#dropdownid option:contains(your selected text)").attr('selected', true);
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
You can use the Number.isFinite()
function:
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite('0'); // false
Number.isFinite(null); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
Note: there's a significant difference between the global function isFinite()
and the latter Number.isFinite()
. In the case of the former, string coercion is performed - so isFinite('0') === true
whilst Number.isFinite('0') === false
.
Also, note that this is not available in IE!
I've come across the same problem and I have a solution. A function called ExpandSelect() that emulates mouse clicking on "select" element, it does so by creating an another <select>
element that is absolutely posioned and have multiple options visible at once by setting the size
attribute. Tested in all major browsers: Chrome, Opera, Firefox, Internet Explorer. Explanation of how it works, along with the code here:
Edit (link was broken).
I've created a project at Google Code, go for the code there:
http://code.google.com/p/expandselect/
There is a little difference in GUI when emulating click, but it does not really matter, see it for yourself:
When mouse clicking:
(source: googlecode.com)
When emulating click:
(source: googlecode.com)
More screenshots on project's website, link above.