For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
You can use this:
select count(customer) as count, pets
from table
group by pets
I use tortoiseGit. I had the same problem. Then in push settings I unchecked "autoload putty key", tried to push, then I checked it again, and pushed, and it worked. But seriously, I don't know why.
Here's a simplified example based on of your problem:
if (test)
{//begin scope 1
int y = 1;
}//end scope 1
else
{//begin scope 2
int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope
In the above version you have a variable called y
that is confined to scope 1, and another different variable called y
that is confined to scope 2. You then try to refer to a variable named y
after the end of the if
, and not such variable y
can be seen because no such variable exists in that scope.
You solve the problem by placing y
in the outermost scope which contains all references to it:
int y;
if (test)
{
y = 1;
}
else
{
y = 2;
}
int x = y;
I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.
A Radio Button List instead of a Radio button creates unique id tags name_0, name_1 etc. An easy way to test which is selected is by assigning a css class like
var deliveryService;
$('.deliveryservice input').each(function () {
if (this.checked) {
deliveryService = this.value
}
I have seen problems with the "for each" using objects and prototype and arrays
my understanding is that the for each is for properties of objects and NOT arrays
value="<?php echo htmlspecialchars($name); ?>"
I'm on Windows 10 Pro x64, VS 19..
When trying to install mod_wsgi for apache in cmd.
C:\>python -m pip install mod_wsgi
This is the error I was getting from my command prompt.
LINK : fatal error LNK1158: cannot run 'rc.exe'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158
I had to copy rc.exe & rcdll.dll from
C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86
and add it to
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64
result from cmd
C:\>python -m pip install mod_wsgi
Collecting mod_wsgi
Using cached mod_wsgi-4.7.1.tar.gz (498 kB)
Installing collected packages: mod-wsgi
Running setup.py install for mod-wsgi ... done
Successfully installed mod-wsgi-4.7.1
Hope this helps someone.
If you have python various versions of python installed,you can launch any of them using pythonx.x.x
where x.x.x
represents your versions.
I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:
while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.
assertTrue
will fail if the second parameter evaluates to false
(in other words, it ensures that the value is true). assertFalse
does the opposite.
assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);
assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);
As with many other things, the best way to become familiar with these methods is to just experiment :-).
Use "
That should work.
When dealing with C++ strings (std::string), you're looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().
#include <iostream>
#include <string.h>
int main(int argc, char **argv)
{
std::string str = "Hello!";
const char *otherstr = "Hello!"; // C-Style string
std::cout << str.size() << std::endl;
std::cout << str.length() << std::endl;
std::cout << strlen(otherstr) << std::endl; // C way for string length
std::cout << strlen(str.c_str()) << std::endl; // convert C++ string to C-string then call strlen
return 0;
}
Output:
6
6
6
6
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
this is pretty useful:
https://github.com/JedWatson/classnames
You can do stuff like
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
or use it like this
var btnClass = classNames('btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES
, regardless of whether you use JavaScript to submit.
HTML form:
<form enctype="multipart/form-data" action="/test.php"
method="post" class="putImages">
<input name="media[]" type="file" multiple/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
PHP produces this $_FILES
, when submitted without JavaScript:
Array
(
[media] => Array
(
[name] => Array
(
[0] => Galata_Tower.jpg
[1] => 518f.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpIQaOYo
[1] => /tmp/phpJQaOYo
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 258004
[1] => 127884
)
)
)
If you do progressive enhancement, using Raphael's JS to submit the files...
var data = new FormData($('input[name^="media"]'));
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax({
type: ppiFormMethod,
data: data,
url: ppiFormActionURL,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
... this is what PHP's $_FILES
array looks like, after using that JavaScript to submit:
Array
(
[0] => Array
(
[name] => Galata_Tower.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpAQaOYo
[error] => 0
[size] => 258004
)
[1] => Array
(
[name] => 518f.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpBQaOYo
[error] => 0
[size] => 127884
)
)
That's a nice array, and actually what some people transform $_FILES
into, but I find it's useful to work with the same $_FILES
, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:
// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)
That code does two things.
input
name attribute automatically, making the HTML more maintainable. Now, as long as form
has the class putImages, everything else is taken care of automatically. That is, the input
need not have any special name.With these changes, submitting with JavaScript now produces precisely the same $_FILES
array as submitting with simple HTML.
I like to keep things simple therefore:
int tot_seconds = 5000;
int hours = tot_seconds / 3600;
int minutes = (tot_seconds % 3600) / 60;
int seconds = tot_seconds % 60;
String timeString = String.format("%02d Hour %02d Minutes %02d Seconds ", hours, minutes, seconds);
System.out.println(timeString);
The result will be: 01 Hour 23 Minutes 20 Seconds
I think this might be the simplest solution:
<tr onclick="location.href='http://www.mywebsite.com'" style="cursor: pointer">
<td>...</td>
<td>...</td>
</tr>
The cursor CSS property sets the type of cursor, if any, to show when the mouse pointer is over an element.
The inline css defines that for that element the cursor will be formatted as a pointer, so you don't need the 'hover'.
There are only two cases when the circle intersects with the rectangle:
Note that this does not require the rectangle to be axis-parallel.
(One way to see this: if none of the edges has a point in the circle (if all the edges are completely "outside" the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)
With that insight, something like the following will work, where the circle has centre P
and radius R
, and the rectangle has vertices A
, B
, C
, D
in that order (not complete code):
def intersect(Circle(P, R), Rectangle(A, B, C, D)):
S = Circle(P, R)
return (pointInRectangle(P, Rectangle(A, B, C, D)) or
intersectCircle(S, (A, B)) or
intersectCircle(S, (B, C)) or
intersectCircle(S, (C, D)) or
intersectCircle(S, (D, A)))
If you're writing any geometry you probably have the above functions in your library already. Otherwise, pointInRectangle()
can be implemented in several ways; any of the general point in polygon methods will work, but for a rectangle you can just check whether this works:
0 = AP·AB = AB·AB and 0 = AP·AD = AD·AD
And intersectCircle()
is easy to implement too: one way would be to check if the foot of the perpendicular from P
to the line is close enough and between the endpoints, and check the endpoints otherwise.
The cool thing is that the same idea works not just for rectangles but for the intersection of a circle with any simple polygon — doesn't even have to be convex!
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<---------Content Here --------------->
</LinearLayout>
</ScrollView>
</LinearLayout>
1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.
2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).
Say you have a table containing courses that are taken in a certain semester, and you have the following data:
|-----Primary Key----| uh oh |
V
CourseID | SemesterID | #Places | Course Name |
------------------------------------------------|
IT101 | 2009-1 | 100 | Programming |
IT101 | 2009-2 | 100 | Programming |
IT102 | 2009-1 | 200 | Databases |
IT102 | 2010-1 | 150 | Databases |
IT103 | 2009-2 | 120 | Web Design |
This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.
Primary Key |
CourseID | Course Name |
---------------------------|
IT101 | Programming |
IT102 | Databases |
IT103 | Web Design |
No redundancy!
Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:
|-----Primary Key----| uh oh |
V
Course | Semester | #Places | TeacherID | TeacherName |
---------------------------------------------------------------|
IT101 | 2009-1 | 100 | 332 | Mr Jones |
IT101 | 2009-2 | 100 | 332 | Mr Jones |
IT102 | 2009-1 | 200 | 495 | Mr Bentley |
IT102 | 2010-1 | 150 | 332 | Mr Jones |
IT103 | 2009-2 | 120 | 242 | Mrs Smith |
Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.
Primary Key |
TeacherID | TeacherName |
---------------------------|
332 | Mr Jones |
495 | Mr Bentley |
242 | Mrs Smith |
No redundancy!!
One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.
I thought it might be worth submitting a counter-example to the general consensus on this page that "instanceof" is not expensive enough to worry about. I found I had some code in an inner loop that (in some historic attempt at optimization) did
if (!(seq instanceof SingleItem)) {
seq = seq.head();
}
where calling head() on a SingleItem returns the value unchanged. Replacing the code by
seq = seq.head();
gives me a speed-up from 269ms to 169ms, despite the fact that there are some quite heavy things happening in the loop, like string-to-double conversion. It's possible of course that the speed-up is more due to eliminating the conditional branch than to eliminating the instanceof operator itself; but I thought it worth mentioning.
In cs file
DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;
In xaml file
<DataGrid Name="gridEmployees" ItemsSource="{Binding}">
Check that you are building a 64-bit process, and not a 32-bit one, which is the default compilation mode of Visual Studio. To do this, right click on your project, Properties -> Build -> platform target : x64. As any 32-bit process, Visual Studio applications compiled in 32-bit have a virtual memory limit of 2GB.
64-bit processes do not have this limitation, as they use 64-bit pointers, so their theoretical maximum address space (the size of their virtual memory) is 16 exabytes (2^64). In reality, Windows x64 limits the virtual memory of processes to 8TB. The solution to the memory limit problem is then to compile in 64-bit.
However, object’s size in Visual Studio is still limited to 2GB, by default. You will be able to create several arrays whose combined size will be greater than 2GB, but you cannot by default create arrays bigger than 2GB. Hopefully, if you still want to create arrays bigger than 2GB, you can do it by adding the following code to you app.config file:
<configuration>
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>
</configuration>
Doing this by date looks like this if the commit happened within the last 90 days:
git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt
Note that HEAD@{2013-02-25}
means "where HEAD was on 2013-02-25" in this repository (using the reflog), not "the last commit before 2013-02-25 in this branch in history".
This is important! It means that, by default, this method only works for history within the last 90 days. Otherwise, you need to do this:
git show $(git rev-list -1 --before="2013-02-26" HEAD):./fileInCurrentDirectory.txt
I think you are confused about the difference between sourcing and executing a script.
Executing a script means creating a new process, and running the program. The program can be a shell script, or any other type of program. As it is a sub process, any environmental variables changed in the program will not affect the shell.
Sourcing a script can only be used with a bash script (if you are running bash). It effectively types the commands in as if you did them. This is useful as it lets a script change environmental variables in the shell.
Running a script is simple, you just type in the path to the script. .
is the current directory. So ./script.sh
will execute the file script.sh
in the current directory. If the command is a single file (eg script.sh
), it will check all the folders in the PATH variable to find the script. Note that the current directory isn't in PATH, so you can't execute a file script.sh
in the current directory by running script.sh
, you need to run ./script.sh
(unless the current directory is in the PATH, eg you can run ls
while in the /bin
dir).
Sourcing a script doesn't use the PATH, and just searches for the path. Note that source
isn't a program - otherwise it wouldn't be able to change environmental variables in the current shell. It is actually a bash built in command. Search /bin
and /usr/bin
- you won't find a source
program there. So to source a file script.sh
in the current directory, you just use source script.sh
.
How does sudo interact with this? Well sudo takes a program, and executes it as root. Eg sudo ./script.sh
executes script.sh
in a sub process but running as root.
What does sudo source ./script.sh
do however? Remember source
isn't a program (rather a shell builtin)? Sudo expects a program name though, so it searches for a program named source
. It doesn't find one, and so fails. It isn't possible to source a file running as root, without creating a new subprocess, as you cannot change the runner of a program (in this case, bash) after it has started.
I'm not sure what you actually wanted, but hopefully this will clear it up for you.
Here is a concrete example. Make the file script.sh
in your current directory with the contents:
#!/bin/bash
export NEW_VAR="hello"
whoami
echo "Some text"
Make it executable with chmod +x script.sh
.
Now observe what happens with bash:
> ./script.sh
david
Some text
> echo $NEW_VAR
> sudo ./script.sh
root
Some text
> echo $NEW_VAR
> source script.sh
david
Some text
> echo $NEW_VAR
hello
> sudo source script.sh
sudo: source: command not found
This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.
Here are my test implementations:
import re
hex_digits = set("ABCDEF1234567890")
hex_match = re.compile(r'^[A-F0-9]+\Z')
hex_search = re.compile(r'[^A-F0-9]')
def test_set(input):
return set(input) <= hex_digits
def test_not_any(input):
return not any(c not in hex_digits for c in input)
def test_re_match1(input):
return bool(re.compile(r'^[A-F0-9]+\Z').match(input))
def test_re_match2(input):
return bool(hex_match.match(input))
def test_re_match3(input):
return bool(re.match(r'^[A-F0-9]+\Z', input))
def test_re_search1(input):
return not bool(re.compile(r'[^A-F0-9]').search(input))
def test_re_search2(input):
return not bool(hex_search.search(input))
def test_re_search3(input):
return not bool(re.match(r'[^A-F0-9]', input))
And the tests, in Python 3.4.0 on Mac OS X:
import cProfile
import pstats
import random
# generate a list of 10000 random hex strings between 10 and 10009 characters long
# this takes a little time; be patient
tests = [ ''.join(random.choice("ABCDEF1234567890") for _ in range(l)) for l in range(10, 10010) ]
# set up profiling, then start collecting stats
test_pr = cProfile.Profile(timeunit=0.000001)
test_pr.enable()
# run the test functions against each item in tests.
# this takes a little time; be patient
for t in tests:
for tf in [test_set, test_not_any,
test_re_match1, test_re_match2, test_re_match3,
test_re_search1, test_re_search2, test_re_search3]:
_ = tf(t)
# stop collecting stats
test_pr.disable()
# we create our own pstats.Stats object to filter
# out some stuff we don't care about seeing
test_stats = pstats.Stats(test_pr)
# normally, stats are printed with the format %8.3f,
# but I want more significant digits
# so this monkey patch handles that
def _f8(x):
return "%11.6f" % x
def _print_title(self):
print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream)
print('filename:lineno(function)', file=self.stream)
pstats.f8 = _f8
pstats.Stats.print_title = _print_title
# sort by cumulative time (then secondary sort by name), ascending
# then print only our test implementation function calls:
test_stats.sort_stats('cumtime', 'name').reverse_order().print_stats("test_*")
which gave the following results:
50335004 function calls in 13.428 seconds Ordered by: cumulative time, function name List reduced from 20 to 8 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.005233 0.000001 0.367360 0.000037 :1(test_re_match2) 10000 0.006248 0.000001 0.378853 0.000038 :1(test_re_match3) 10000 0.010710 0.000001 0.395770 0.000040 :1(test_re_match1) 10000 0.004578 0.000000 0.467386 0.000047 :1(test_re_search2) 10000 0.005994 0.000001 0.475329 0.000048 :1(test_re_search3) 10000 0.008100 0.000001 0.482209 0.000048 :1(test_re_search1) 10000 0.863139 0.000086 0.863139 0.000086 :1(test_set) 10000 0.007414 0.000001 9.962580 0.000996 :1(test_not_any)
where:
The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different.
It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.
test_set was twice as slow as re_search and thrice as slow as re_match
test_not_any was a full order of magnitude slower than test_set
TL;DR: Use re.match or re.search
I would store it as a char(36).
For me, I have to disconnect (change workgroup/domain) from the Domain and reconnect.
MSDN says that:
The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.
So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.
protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
int rowIndex = Convert.ToInt32( e.CommandArgument );
...
}
Using Apache Commons-Lang's SystemUtils.isJavaVersionAtLeast(JavaVersion)
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)
System.out.println("Java version was 8 or greater!");
For Swift3
let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
UITextView_Message.attributedText = theAttributedString
Essentially the same as Gringo Suave's answer, but with a generator:
from datetime import datetime, timedelta
def datetime_range(start=None, end=None):
span = end - start
for i in xrange(span.days + 1):
yield start + timedelta(days=i)
Then you can use it as follows:
In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out:
[datetime.datetime(2014, 1, 1, 0, 0),
datetime.datetime(2014, 1, 2, 0, 0),
datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 1, 4, 0, 0),
datetime.datetime(2014, 1, 5, 0, 0)]
Or like this:
In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
...: print date
...:
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
I'm late to the party, but I had this same issue working with Java 8.
This is what worked for me, on the HttpServletRequest request
object.
request.getHeader("origin");
and
request.getHeader("referer");
How I came to that conclusion:
I have a java app running on http://localhost:3000 making a Http Post to another java app I have running on http://localhost:8080.
From the Java code running on http://localhost:8080 I couldn't get the http://localhost:3000 from the HttpServletRequest using the answers above. For me using the getHeader
method with the correct string input worked.
request.getHeader("origin")
gave me "http://localhost:3000" which is what I wanted.
request.getHeader("referer")
gave me "http://localhost:3000/xxxx" where xxxx is full URL I have from the requesting app.
There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.
bower install bootstrap-css
Thanks Nico.
GLib and gnulib
These are your likely best bets if you don't have more specific requirements, since they are widely available, portable and likely efficient.
GLib: https://developer.gnome.org/glib/ by GNOME project. Several containers documented at: https://developer.gnome.org/glib/stable/glib-data-types.html including "Hash Tables" and "Balanced Binary Trees". License: LGPL
gnulib: https://www.gnu.org/software/gnulib/ by the GNU project. You are meant to copy paste the source into your code. Several containers documented at: https://www.gnu.org/software/gnulib/MODULES.html#ansic_ext_container including "rbtree-list", "linkedhash-list" and "rbtreehash-list". GPL license.
See also: Are there any open source C libraries with common data structures?
I'm posting a more declarative way of sync Base64 converting. While async fetch().blob()
is very neat and I like this solution a lot, it doesn't work on Internet Explorer 11 (and probably Edge - I haven't tested this one), even with the polyfill - take a look at my comment to Endless' post for more details.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
If you want to print it you could do something like:
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // Or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
If you're able to do some preprocessing of the Base64 string on the server you could expose it under some URL and use the link in printJS
:)
sing the CSS @import Rule here
@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;
http://bootstrapfooter.codeplex.com/
This should solve your problem.
<div id="wrap">
<div id="main" class="container clear-top">
<div class="row">
<div class="span12">
Your content here.
</div>
</div>
</div>
</div>
<footer class="footer" style="background-color:#c2c2c2">
</footer>
CSS:
html,body
{
height:100%;
}
#wrap
{
min-height: 100%;
}
#main
{
overflow:auto;
padding-bottom:150px; /* this needs to be bigger than footer height*/
}
.footer
{
position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;
padding-top:20px;
color:#fff;
}
I was having same problem as a7madx7, but with stable release of EF (v6.1.1), and found resolution posted in:
http://cybarlab.com/context-has-changed-since-the-database-was-created
with variation in: http://patrickdesjardins.com/blog/the-model-backing-the-context-has-changed-since-the-database-was-created-ef4-3
2nd link includes specific mention for VB..... "you can simply add all the databasecontext that are having this problem on your app_start method in the global.asax file like this":
Database.SetInitializer(Of DatabaseContext)(Nothing)
NB: i had to replace "DatabaseContext" with the name of my class implementing DbContext
Update: Also, when using codefirst approach to connect to existing tables, check database to see if EF has created a table "_migrationhistory" to store mappings. I re-named this table then was able to remove SetInitializer from global.asax.
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment
Jason caught an error, so this works...
Can anyone confirm the other platform versions?
SQL Server:
SELECT
CASE LEN(ISNULL(last_name,''))
WHEN 0 THEN ''
ELSE ' ' + last_name
END AS newlastName
MySQL:
SELECT
CASE LENGTH(IFNULL(last_name,''))
WHEN 0 THEN ''
ELSE ' ' + last_name
END AS newlastName
Oracle:
SELECT
CASE LENGTH(NVL(last_name,''))
WHEN 0 THEN ''
ELSE ' ' + last_name
END AS newlastName
issue = “UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”
And this worked for me
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')
First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.
In the end, there are three widespread ways to check for a null pointer:
if ( p != NULL ) ...
if ( p != 0 ) ...
if ( p ) ...
All work, regardless of the representation of a null pointer on the
machine. And all, in some way or another, are misleading; which one you
choose is a question of choosing the least bad. Formally, the first two
are indentical for the compiler; the constant NULL
or 0
is converted
to a null pointer of the type of p
, and the results of the conversion
are compared to p
. Regardless of the representation of a null
pointer.
The third is slightly different: p
is implicitly converted
to bool
. But the implicit conversion is defined as the results of p
!= 0
, so you end up with the same thing. (Which means that there's
really no valid argument for using the third style—it obfuscates
with an implicit conversion, without any offsetting benefit.)
Which one of the first two you prefer is largely a matter of style,
perhaps partially dictated by your programming style elsewhere:
depending on the idiom involved, one of the lies will be more bothersome
than the other. If it were only a question of comparison, I think most
people would favor NULL
, but in something like f( NULL )
, the
overload which will be chosen is f( int )
, and not an overload with a
pointer. Similarly, if f
is a function template, f( NULL )
will
instantiate the template on int
. (Of course, some compilers, like
g++, will generate a warning if NULL
is used in a non-pointer context;
if you use g++, you really should use NULL
.)
In C++11, of course, the preferred idiom is:
if ( p != nullptr ) ...
, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**_x000D_
* PT1H30M -> 0130_x000D_
* @param {ISO String} isoString_x000D_
* @return {string} absolute 4 digit number HH:mm_x000D_
*/_x000D_
_x000D_
const parseIsoToAbsolute = (isoString) => {_x000D_
_x000D_
const durations = moment.duration(isoString).as('seconds');_x000D_
const momentInSeconds = moment.duration(durations, 'seconds');_x000D_
_x000D_
let hours = momentInSeconds.asHours().toString().length < 2_x000D_
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();_x000D_
_x000D_
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);_x000D_
_x000D_
const minutes = momentInSeconds.minutes().toString().length < 2_x000D_
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();_x000D_
_x000D_
const absolute = hours + minutes;_x000D_
return absolute;_x000D_
};_x000D_
_x000D_
console.log(parseIsoToAbsolute('PT1H30M'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
You can also send an array via FormData
this way:
var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];
for (var i = 0; i < arr.length; i++) {
formData.append('arr[]', arr[i]);
}
So you can write arr[]
the same way as you do it with a simple HTML form. In case of PHP it should work.
You may find this article useful: How to pass an array within a query string?
I also had the same issue, but the problem was with the Target framework of the assembly.
The referenced assembly was in .NET Framework 4.6 where the project has set to .NET framework 4.5.
Hope this will help to someone who messed up with frameworks.
Are you sure that your address is 168.192.1.2 and not 192.168.1.2?
Notice the swapped first two numbers.
There is one way to implement multiple interface.
Just extend one interface from another or create interface that extends predefined interface Ex:
public interface PlnRow_CallBack extends OnDateSetListener {
public void Plan_Removed();
public BaseDB getDB();
}
now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces
public class Calculator extends FragmentActivity implements PlnRow_CallBack {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
@Override
public void Plan_Removed() {
}
@Override
public BaseDB getDB() {
}
}
hope this helps
By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.
Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.
int i = 7122960;
decimal d = (decimal)i / 100;
From this version, you can use native Node.js function from util library.
const fs = require('fs')
const { promisify } = require('util')
const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)
const run = async () => {
const res = await readFileAsync('./data.json')
console.log(res)
}
run()
const fs = require('fs')
const readFile = (path, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.readFile(path, opts, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
const writeFile = (path, data, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.writeFile(path, data, opts, (err) => {
if (err) reject(err)
else resolve()
})
})
module.exports = {
readFile,
writeFile
}
...
// in some file, with imported functions above
// in async block
const run = async () => {
const res = await readFile('./data.json')
console.log(res)
}
run()
Always use try..catch
for await blocks, if you don't want to rethrow exception upper.
I lost hours and hours to resolve this issue, but it's fixed by just restarting MAC...
Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.
var lineString = " line 1\r\n";
linestring += " line 2";
Will correctly display:
line 1
line 2
It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.
Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.
(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)
I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php
all the time, or fiddle around with your server settings on each addition (I do not like both).
TLTR
You can add a filter on the actual WP permalink function you need (for me it was post_link
, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.
This is ok, because the post is an alias, so you won't need the content anyways.
First step is to open the alias post and put the ID of the referenced post as content (and nothing else):
Next, open your functions.php
and add:
function prefix_filter_post_permalink($url, $post) {
// if the content of the post to get the permalink for is just a number...
if (is_numeric($post->post_content)) {
// instead, return the permalink for the post that has this ID
return get_the_permalink((int)$post->post_content);
}
return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );
That's it
Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.
This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP
code is far from ideal, but like this for making the point readable.
Use Tortoise's RENAME command, and type in a relative path ("folder/file.ext").
It can be done this way as well:
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
This may work for you:
Scenario 1: primitive types
string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};
if(!dictToUpdate.ContainsKey(keyToMatchInDict))
dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;
Scenario 2: The approach I used for a List as Value
int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...
if(!dictToUpdate.ContainsKey(keyToMatch))
dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
dictToUpdate[keyToMatch] = objInValueListToAdd;
Hope it's useful for someone in need of help.
Simply place this line in your Model:
public $timestamps = false;
And that's it!
Example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $timestamps = false;
//
}
To disable timestamps for one operation (e.g. in a controller):
$post->content = 'Your content';
$post->timestamps = false; // Will not modify the timestamps on save
$post->save();
To disable timestamps for all of your Models, create a new BaseModel
file:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
public $timestamps = false;
//
}
Then extend each one of your Models with the BaseModel
, like so:
<?php
namespace App;
class Post extends BaseModel
{
//
}
/aa([^a]|a[^a])*aa/
In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
If you don't, unless there's some Join()
override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):
db.Services.Join(db.ServiceAssignments,
s => s.Id,
sa => sa.ServiceId,
(s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);
Breakpoints and especially conditional breakpoints are your friends.
Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)
The easiest way to achieve this is to create only 1 table with both Table A and B fields NOT NULL. This way it is impossible to have one without the other.
The above answers are bit outdated. Although those method work, but by using below method, you can share any text to a predefined number. The below method works for android, WhatsApp web, IOS etc.
You just need to use this format:
<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>
UPDATE-- Use this from now(Nov-2018)
<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.
Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing
After clicking on the link, you will be shown a list of contacts you can send your message to.
For more information, see https://www.whatsapp.com/faq/en/general/26000030
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
You need to use the Convert()
method in the Encoding
class:
Encoding
object that represents ASCII encodingEncoding
object that represents Unicode encodingEncoding.Convert()
with the source encoding, the destination encoding, and the string to be encodedThere is an example here:
using System;
using System.Text;
namespace ConvertExample
{
class ConvertExampleClass
{
static void Main()
{
string unicodeString = "This string contains the unicode character Pi(\u03a0)";
// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;
// Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiString = new string(asciiChars);
// Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString);
Console.WriteLine("Ascii converted string: {0}", asciiString);
}
}
}
From a maintainability standpoint, it's much simpler to manage one item in one file, than it is to manage multiple items in possibly multiple files.
Separating your styling will help make your life much easier, especially when job duties are distributed amongst different individuals. Reusability and portability will save you plenty of time down the road.
When using an inline style, that will override any external properties that are set.
No, unfortunately this will not be possible because ConverterParameter
is not a DependencyProperty
so you won't be able to use bindings
But perhaps you could cheat and use a MultiBinding
with IMultiValueConverter
to pass in the 2 Tag
properties.
if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs
using jQuery it's easy...
$('YOUR CLASS SELECTOR').click(function(){
$(this).toggle();
});
As stated in a comment at
with System.Net.Mail, use port 25 instead of 465:
You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
# Original code
df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5],
'b': [0.1, 0.2, 0.3, 0.4, 0.5],
'item': ['a', 'b', 'c', 'd', 'e']})
df = df.set_index('item')
Convert to numeric using 'coerce' which fills bad values with 'nan'
a = pd.to_numeric(df.a, errors='coerce')
Use isna to return a boolean index:
idx = a.isna()
Apply that index to the data frame:
df[idx]
Returns the row with the bad data in it:
a b
item
d bad 0.4
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
There is existing npm package: url-regex, just install it with yarn add url-regex
or npm install url-regex
and use as following:
const urlRegex = require('url-regex');
const replaced = 'Find me at http://www.example.com and also at http://stackoverflow.com or at google.com'
.replace(urlRegex({strict: false}), function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
The answer given by Matt K works perfectly fine.
However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -
<div style="position:absolute; hei...">
<div style="position:relative; display: table-cell; vertical-align:middle; hei...">
<!-- here position MUST be relative, this div acts as a wrapper-->
...
</div>
</div>
sometimes unchecked means other values, for instance checked could mean yes unchecked no or 0,1 etc it depends on the meaning you want to give.. so could be another state besides "unchecked means it's not in the querystring at all"
"It would make it a lot easier to store information in DB. Because then the number of fields from Serialize would equal the number of fields in table. Now I have to contrll which ones are missing", youre right this is my problem too... so it appears i have to check for this nonexisting value....
but maybe this could be a solution? http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/
This code work well in order to get SSID.
#import <SystemConfiguration/CaptiveNetwork.h>
@implementation IODAppDelegate
@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CFArrayRef myArray = CNCopySupportedInterfaces();
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
NSLog(@"Connected at:%@",myDict);
NSDictionary *myDictionary = (__bridge_transfer NSDictionary*)myDict;
NSString * BSSID = [myDictionary objectForKey:@"BSSID"];
NSLog(@"bssid is %@",BSSID);
// Override point for customization after application launch.
return YES;
}
And this is the results :
Connected at:{
BSSID = 0;
SSID = "Eqra'aOrange";
SSIDDATA = <45717261 27614f72 616e6765>;
}
Thumbnailator is an open-source image resizing library for Java with a fluent interface, distributed under the MIT license.
I wrote this library because making high-quality thumbnails in Java can be surprisingly difficult, and the resulting code could be pretty messy. With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.
A simple example
For a simple example, taking a image and resizing it to 100 x 100 (preserving the aspect ratio of the original image), and saving it to an file can achieved in a single statement:
Thumbnails.of("path/to/image")
.size(100, 100)
.toFile("path/to/thumbnail");
An advanced example
Performing complex resizing tasks is simplified with Thumbnailator's fluent interface.
Let's suppose we want to do the following:
0.85
,thumbnail.
appended to the beginningTranslated to Thumbnailator, we'd be able to perform the above with the following:
Thumbnails.of(new File("path/to/directory").listFiles())
.size(100, 100)
.outputFormat("JPEG")
.outputQuality(0.85)
.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
A note about image quality and speed
This library also uses the progressive bilinear scaling method highlighted in Filthy Rich Clients by Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.
On Oracle's own Linux (Version 7.7, PRETTY_NAME="Oracle Linux Server 7.7"
in /etc/os-release
), if you installed the 18.3 client libraries with
sudo yum install oracle-instantclient18.3-basic.x86_64
sudo yum install oracle-instantclient18.3-sqlplus.x86_64
then you need to put the following in your .bash_profile
:
export ORACLE_HOME=/usr/lib/oracle/18.3/client64
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME
in order to be able to invoke the SQLPlus client, which, incidentally, is called sqlplus64
on this platform.
By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.
I would suggest to have a class implement compare method of Comparator-interface as :
public int compare(Object o1, Object o2) {
return o1.toString().compareToIgnoreCase(o2.toString());
}
and from the calling method invoke the Arrays.sort method with custom Comparator as :
Arrays.sort(inputArray, customComparator);
Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"
output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani
Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep
Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.
for more understanding of natural and alphabetical/lexical order visit discussion here
Use REG to save/modify/restore what ever values are most useful for your bat file. This is windows 7, for other versions you may need a different key name.
reg save "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
If the list contains numbers, you can use map()
with join()
.
Eg:
>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459
You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:
public class ArrayUtils {
public static <T> E[] appendToArray(E[] array, E item) {
E[] result = (E[])new Object[array.length+1];
result[array.length] = item;
return result;
}
}
Have a look at the below code snippet.
@RequestMapping(value="/Add/{type}")
public ModelAndView addForm(@PathVariable String type ){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("addContent");
modelAndView.addObject("typelist",contentPropertyDAO.getType() );
modelAndView.addObject("property",contentPropertyDAO.get(type,0) );
return modelAndView;
}
Hope it helps in constructing your code.
By default, *.sh
files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command
. By default, these are sent to Terminal, which will execute the file as a shell script.
You will also need to ensure the file is executable, e.g.:
chmod +x file.command
Without this, Terminal will refuse to execute it.
Note that the script does not have to begin with a #!
prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #!
line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)
Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd
command if you actually need it to run with a particular working directory.
You need to add runat="server"
and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
Here's something I put together a while ago, it's windows only but may help you get part of what you need done.
Derived from: "for sys available mem" http://msdn2.microsoft.com/en-us/library/aa455130.aspx
"individual process information and python script examples" http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this, then may want to investigate the WMI tools a vailable.
WMI for python:
http://tgolden.sc.sabren.com/python/wmi.html
The code:
'''
Monitor window processes
derived from:
>for sys available mem
http://msdn2.microsoft.com/en-us/library/aa455130.aspx
> individual process information and python script examples
http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
NOTE: the WMI interface/process is also available for performing similar tasks
I'm not using it here because the current method covers my needs, but if someday it's needed
to extend or improve this module, then may want to investigate the WMI tools available.
WMI for python:
http://tgolden.sc.sabren.com/python/wmi.html
'''
__revision__ = 3
import win32com.client
from ctypes import *
from ctypes.wintypes import *
import pythoncom
import pywintypes
import datetime
class MEMORYSTATUS(Structure):
_fields_ = [
('dwLength', DWORD),
('dwMemoryLoad', DWORD),
('dwTotalPhys', DWORD),
('dwAvailPhys', DWORD),
('dwTotalPageFile', DWORD),
('dwAvailPageFile', DWORD),
('dwTotalVirtual', DWORD),
('dwAvailVirtual', DWORD),
]
def winmem():
x = MEMORYSTATUS() # create the structure
windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes
return x
class process_stats:
'''process_stats is able to provide counters of (all?) the items available in perfmon.
Refer to the self.supported_types keys for the currently supported 'Performance Objects'
To add logging support for other data you can derive the necessary data from perfmon:
---------
perfmon can be run from windows 'run' menu by entering 'perfmon' and enter.
Clicking on the '+' will open the 'add counters' menu,
From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key.
--> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent)
For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary,
keyed by the 'Performance Object' name as mentioned above.
---------
NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly.
Initially the python implementation was derived from:
http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
'''
def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]):
'''process_names_list == the list of all processes to log (if empty log all)
perf_object_list == list of process counters to log
filter_list == list of text to filter
print_results == boolean, output to stdout
'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
self.process_name_list = process_name_list
self.perf_object_list = perf_object_list
self.filter_list = filter_list
self.win32_perf_base = 'Win32_PerfFormattedData_'
# Define new datatypes here!
self.supported_types = {
'NETFramework_NETCLRMemory': [
'Name',
'NumberTotalCommittedBytes',
'NumberTotalReservedBytes',
'NumberInducedGC',
'NumberGen0Collections',
'NumberGen1Collections',
'NumberGen2Collections',
'PromotedMemoryFromGen0',
'PromotedMemoryFromGen1',
'PercentTimeInGC',
'LargeObjectHeapSize'
],
'PerfProc_Process': [
'Name',
'PrivateBytes',
'ElapsedTime',
'IDProcess',# pid
'Caption',
'CreatingProcessID',
'Description',
'IODataBytesPersec',
'IODataOperationsPersec',
'IOOtherBytesPersec',
'IOOtherOperationsPersec',
'IOReadBytesPersec',
'IOReadOperationsPersec',
'IOWriteBytesPersec',
'IOWriteOperationsPersec'
]
}
def get_pid_stats(self, pid):
this_proc_dict = {}
pythoncom.CoInitialize() # Needed when run by the same process in a thread
if not self.perf_object_list:
perf_object_list = self.supported_types.keys()
for counter_type in perf_object_list:
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)
colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread
if len(colItems) > 0:
for objItem in colItems:
if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess:
for attribute in self.supported_types[counter_type]:
eval_str = 'objItem.%s' % (attribute)
this_proc_dict[attribute] = eval(eval_str)
this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]
break
return this_proc_dict
def get_stats(self):
'''
Show process stats for all processes in given list, if none given return all processes
If filter list is defined return only the items that match or contained in the list
Returns a list of result dictionaries
'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
proc_results_list = []
if not self.perf_object_list:
perf_object_list = self.supported_types.keys()
for counter_type in perf_object_list:
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)
colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread
try:
if len(colItems) > 0:
for objItem in colItems:
found_flag = False
this_proc_dict = {}
if not self.process_name_list:
found_flag = True
else:
# Check if process name is in the process name list, allow print if it is
for proc_name in self.process_name_list:
obj_name = objItem.Name
if proc_name.lower() in obj_name.lower(): # will log if contains name
found_flag = True
break
if found_flag:
for attribute in self.supported_types[counter_type]:
eval_str = 'objItem.%s' % (attribute)
this_proc_dict[attribute] = eval(eval_str)
this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]
proc_results_list.append(this_proc_dict)
except pywintypes.com_error, err_msg:
# Ignore and continue (proc_mem_logger calls this function once per second)
continue
return proc_results_list
def get_sys_stats():
''' Returns a dictionary of the system stats'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
x = winmem()
sys_dict = {
'dwAvailPhys': x.dwAvailPhys,
'dwAvailVirtual':x.dwAvailVirtual
}
return sys_dict
if __name__ == '__main__':
# This area used for testing only
sys_dict = get_sys_stats()
stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[])
proc_results = stats_processor.get_stats()
for result_dict in proc_results:
print result_dict
import os
this_pid = os.getpid()
this_proc_results = stats_processor.get_pid_stats(this_pid)
print 'this proc results:'
print this_proc_results
http://monkut.webfactional.com/blog/archive/2009/1/21/windows-process-memory-logging-python
First, you need to add a shebang line in the Python script which looks like the following:
#!/usr/bin/env python3
This path is necessary if you have multiple versions of Python installed and /usr/bin/env
will ensure that the first Python interpreter in your $$PATH
environment variable is taken. You can also hardcode the path of your Python interpreter (e.g. #!/usr/bin/python3
), but this is not flexible and not portable on other machines. Next, you’ll need to set the permissions of the file to allow execution:
chmod +x test.py
Now you can run the script with nohup which ignores the hangup signal. This means that you can close the terminal without stopping the execution. Also, don’t forget to add &
so the script runs in the background:
nohup /path/to/test.py &
If you did not add a shebang
to the file you can instead run the script with this command:
nohup python /path/to/test.py &
The output will be saved in the nohup.out
file, unless you specify the output file like here:
nohup /path/to/test.py > output.log &
nohup python /path/to/test.py > output.log &
If you have redirected the output of the command somewhere else - including /dev/null
- that's where it goes instead.
# doesn't create nohup.out
nohup command >/dev/null 2>&1
If you're using nohup
, that probably means you want to run the command in the background by putting another &
on the end of the whole thing:
# runs in background, still doesn't create nohup.out
nohup command >/dev/null 2>&1 &
You can find the process
and its process ID
with this command:
ps ax | grep test.py
# or
# list of running processes Python
ps -fA | grep python
ps
stands for process status
If you want to stop the execution, you can kill it with the kill command:
kill PID
You need to declare the desired function before your main function:
#include <stdio.h>
int yourfunc(void);
int main(void) {
yourfunc();
}
AndAlso is much like And, except it works like && in C#, C++, etc.
The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".
This is sometimes very useful, e.g. in an expression such as:
If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
...
End If
Using the old And in the above expression would throw a NullReferenceException if myObj were null.
It can be done inside styles.xml using
<item name="android:navigationBarColor">@color/theme_color</item>
or
window.setNavigationBarColor(@ColorInt int color)
http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)
Note that the method was introduced in Android Lollipop and won't work on API version < 21.
The second method (works on KitKat) is to set windowTranslucentNavigation to true in the manifest and place a colored view beneath the navigation bar.
The parser is having trouble concatenating your string. Try this:
write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])
Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
If you just want the button to have different styling while the mouse is pressed you can use the :active
pseudo class.
.button:active {
}
If on the other hand you want the style to stay after clicking you will have to use javascript.
You can only get the URI arguments with JavaScript.
// get query arguments
var $_GET = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:
function Person() {
this.name = "John";
return this;
}
var person = new Person();
alert("name: " + person.name);**
In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.
On our build server, we explicitly delete the bin and obj directories, via nant scripts.
Each project build script is responsible for it's output/temp directories. Works nicely that way. So when we change a project and add a new one, we base the script off a working script, and you notice the delete stage and take care of it.
If you doing it on you logic development machine, I'd stick to clean via Visual Studio as others have mentioned.
Add Days in Date in SQL
DECLARE @NEWDOB DATE=null
SET @NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
Item.objects.values("contest").annotate(Count("id"))
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
public String UpperCaseWords(String line)
{
line = line.trim().toLowerCase();
String data[] = line.split("\\s");
line = "";
for(int i =0;i< data.length;i++)
{
if(data[i].length()>1)
line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
else
line = line + data[i].toUpperCase();
}
return line.trim();
}
You can use VARRAY for a fixed-size array:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
for i in 1..array.count loop
dbms_output.put_line(array(i));
end loop;
end;
Or TABLE for an unbounded array:
...
type array_t is table of varchar2(10);
...
The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.
With either of these you need to both initialise and extend the collection before adding elements:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t(); -- Initialise it
begin
for i in 1..3 loop
array.extend(); -- Extend it
array(i) := 'x';
end loop;
end;
The first index is 1 not 0.
You need to add tabs plugin to your code
<script type="text/javascript" src="assets/twitterbootstrap/js/bootstrap-tab.js"></script>
Well, it didn't work. I made some tests and it started working when:
<head>
section data-toggle="tab"
to links and id for <ul>
tab element$(".tabs").tabs();
to $("#tabs").tab();
Here's a code
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Le styles -->
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
</head>
<body>
<div class="container">
<!-------->
<div id="content">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a href="#red" data-toggle="tab">Red</a></li>
<li><a href="#orange" data-toggle="tab">Orange</a></li>
<li><a href="#yellow" data-toggle="tab">Yellow</a></li>
<li><a href="#green" data-toggle="tab">Green</a></li>
<li><a href="#blue" data-toggle="tab">Blue</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane active" id="red">
<h1>Red</h1>
<p>red red red red red red</p>
</div>
<div class="tab-pane" id="orange">
<h1>Orange</h1>
<p>orange orange orange orange orange</p>
</div>
<div class="tab-pane" id="yellow">
<h1>Yellow</h1>
<p>yellow yellow yellow yellow yellow</p>
</div>
<div class="tab-pane" id="green">
<h1>Green</h1>
<p>green green green green green</p>
</div>
<div class="tab-pane" id="blue">
<h1>Blue</h1>
<p>blue blue blue blue blue</p>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#tabs').tab();
});
</script>
</div> <!-- container -->
<script type="text/javascript" src="../bootstrap/js/bootstrap.js"></script>
</body>
</html>
You can use nested query for pagination as follow:
Paging from 4 Row to 8 Row where CustomerId is primary key.
SELECT Top 5 * FROM Customers
WHERE Country='Germany' AND CustomerId Not in (SELECT Top 3 CustomerID FROM Customers
WHERE Country='Germany' order by city)
order by city;
If all you want to do is enumerate them, use the IEnumerable
.
Beware, though, that changing the original collection being enumerated is a dangerous operation - in this case, you will want to ToList
first. This will create a new list element for each element in memory, enumerating the IEnumerable
and is thus less performant if you only enumerate once - but safer and sometimes the List
methods are handy (for instance in random access).
I use a decorator to return the result of jsonfiy
. I think it is more readable when a view has multiple returns. This does not support returning a tuple like content, status
, but I handle returning error statuses with app.errorhandler
instead.
import functools
from flask import jsonify
def return_json(f):
@functools.wraps(f)
def inner(**kwargs):
return jsonify(f(**kwargs))
return inner
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'none of them'
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)
DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)
--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM #temp
SELECT @Month= LEFT(@Month,len(@Month)-1)
SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
ap.YYYYMM ,
ap.UserID ,
ap.AccountNumber
FROM #AccPurch AS ap
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'
EXEC sp_executesql @sql
Select * INTO #final From ##final_Donovan_12345
DROP TABLE ##final_Donovan_12345
Select * From #final AS f
Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."
Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
From the answers for the question System.Net.WebClient unreasonably slow
Try setting Proxy = null;
WebClient wc = new WebClient(); wc.Proxy = null;
Credit to Alex Burtsev
You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.
public static String getNameByCode(int code){
for(RelationActiveEnum e : RelationActiveEnum.values()){
if(code == e.value) return e.name();
}
return null;
}
And call it like this:
RelationActiveEnum.getNameByCode(3);
this
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
Move your mouse in the snippet window :D
<script>
document.addEventListener('mouseover', function (e) {
console.log ("You are in ", e.target.tagName);
});
</script>
_x000D_
You need to set Transaction for every Account.
foreach(Account account : accounts){
account.setTransaction(transactionObj);
}
Or it colud be enough (if appropriate) to set ids to null on many side.
// list of existing accounts
List<Account> accounts = new ArrayList<>(transactionObj.getAccounts());
foreach(Account account : accounts){
account.setId(null);
}
transactionObj.setAccounts(accounts);
// just persist transactionObj using EntityManager merge() method.
After some research I finally got a VBA code to show the filter value in another cell:
Dim bRepresentAsRange As Boolean, bRangeBroken As Boolean
Dim sSelection As String
Dim tbl As Variant
bRepresentAsRange = False
bRangeBroker = False
With Worksheets("Forecast").PivotTables("ForecastbyDivision")
ReDim tbl(.PageFields("Probability").PivotItems.Count)
For Each fld In .PivotFields("Probability").PivotItems
If fld.Visible Then
tbl(n) = fld.Name
sSelection = sSelection & fld.Name & ","
n = n + 1
bRepresentAsRange = True
Else
If bRepresentAsRange Then
bRepresentAsRange = False
bRangeBroken = True
End If
End If
Next fld
If Not bRangeBroken Then
Worksheets("Forecast").Range("ProbSelection") = " >= " & tbl(0)
Else
Worksheets("Forecast").Range("ProbSelection") = Left(sSelection, Len(sSelection) - 1)
End If
End With
You could use list.indexOf(Object)
bug in all honesty what you're describing sounds like you'd be better off using a Map
.
Try this:
Map<String, Object> mapOfObjects = new HashMap<String, Object>();
mapOfObjects.put("objectName", object);
Then later when you want to retrieve the object, use
mapOfObjects.get("objectName");
Assuming you do know the object's name as you stated, this will be both cleaner and will have faster performance besides, particularly if the map contains large numbers of objects.
If you need the objects in the Map
to stay in order, you can use
Map<String, Object> mapOfObjects = new LinkedHashMap<String, Object>();
instead
I found 'Python Script' plugin for Notepad++ more useful since with the plugin, I could write simple macros in the form of python and It has also got very good documentation and sample macros written in python as well. If you are quite comfortable with python, then I think 'Python Script' will provide justice. For more information, refer : http://npppythonscript.sourceforge.net/
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
I Want See This
Example http://jsfiddle.net/35vAN/
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">
function PrintElem(elem)
{
Popup($(elem).html());
}
function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}
</script>
</head>
<body>
<div id="mydiv">
This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante.
</div>
<div>
This will not be printed.
</div>
<div id="anotherdiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />
</body>
</html>
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
So I run a functionally equivalent form of your code in an IPython notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()
I get what I believe to be very reasonable output.
It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?
The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.
import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline
# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
This will delete the local branches for which the remote tracking branches have been pruned. (Make sure you are on master
branch!)
git checkout master
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -d
Details:
git branch -vv
displays "gone" for local branches that the remote has been pruned.
mybranch abc1234 [origin/mybranch: gone] commit comments
-d
will check if it has been merged (-D
will delete it regardless)
error: The branch 'mybranch' is not fully merged.
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
from the yii2 framework
/**
* Generates a random string of specified length.
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* @param int $length the length of the key in characters
* @return string the generated random key
*/
function generateRandomString($length = 10) {
$bytes = random_bytes($length);
return substr(strtr(base64_encode($bytes), '+/', '-_'), 0, $length);
}
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
Applications that are not satisfied with only 256 different characters have the options of either using wide characters (more than 8 bits) or a variable-length encoding (a multibyte encoding in C++ terminology) such as UTF-8. Wide characters generally require more space than a variable-length encoding, but are faster to process. Multi-language applications that process large amounts of text usually use wide characters when processing the text, but convert it to UTF-8 when storing it to disk.
The only difference between a string
and a wstring
is the data type of the characters they store. A string stores char
s whose size is guaranteed to be at least 8 bits, so you can use strings for processing e.g. ASCII, ISO-8859-15, or UTF-8 text. The standard says nothing about the character set or encoding.
Practically every compiler uses a character set whose first 128 characters correspond with ASCII. This is also the case with compilers that use UTF-8 encoding. The important thing to be aware of when using strings in UTF-8 or some other variable-length encoding, is that the indices and lengths are measured in bytes, not characters.
The data type of a wstring is wchar_t
, whose size is not defined in the standard, except that it has to be at least as large as a char, usually 16 bits or 32 bits. wstring can be used for processing text in the implementation defined wide-character encoding. Because the encoding is not defined in the standard, it is not straightforward to convert between strings and wstrings. One cannot assume wstrings to have a fixed-length encoding either.
If you don't need multi-language support, you might be fine with using only regular strings. On the other hand, if you're writing a graphical application, it is often the case that the API supports only wide characters. Then you probably want to use the same wide characters when processing the text. Keep in mind that UTF-16 is a variable-length encoding, meaning that you cannot assume length()
to return the number of characters. If the API uses a fixed-length encoding, such as UCS-2, processing becomes easy. Converting between wide characters and UTF-8 is difficult to do in a portable way, but then again, your user interface API probably supports the conversion.
There are lots of data types you can mention while creating model, some examples are:
:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references
syntax:
field_type:data_type
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer
On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:
public static void main(String[] args) {
int repeat = 10;
long A = 0;
long B = 0;
for (int i = 0; i < repeat; i++) {
A += test();
B += testB();
}
System.out.println(A / repeat + " ms");
System.out.println(B / repeat + " ms");
}
private static long test() {
int n = 0;
for (int i = 0; i < 1000; i++) {
n += multi(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
n += multi(i);
}
long ms = (System.currentTimeMillis() - startTime);
System.out.println(ms + " ms A " + n);
return ms;
}
private static long testB() {
int n = 0;
for (int i = 0; i < 1000; i++) {
n += multiB(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
n += multiB(i);
}
long ms = (System.currentTimeMillis() - startTime);
System.out.println(ms + " ms B " + n);
return ms;
}
private static int multiB(int i) {
return 2 * (i * i);
}
private static int multi(int i) {
return 2 * i * i;
}
Output:
...
405 ms A 785527736
327 ms B 785527736
404 ms A 785527736
329 ms B 785527736
404 ms A 785527736
328 ms B 785527736
404 ms A 785527736
328 ms B 785527736
410 ms
333 ms
So why? The byte code is this:
private static multiB(int arg0) { // 2 * (i * i)
<localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
L1 {
iconst_2
iload0
iload0
imul
imul
ireturn
}
L2 {
}
}
private static multi(int arg0) { // 2 * i * i
<localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
L1 {
iconst_2
iload0
imul
iload0
imul
ireturn
}
L2 {
}
}
The difference being:
With brackets (2 * (i * i)
):
Without brackets (2 * i * i
):
Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.
There is another solution.
Implement IFormatProvider
to return a ICustomFormatter
that will be passed to string.Format :
public class StringPadder : ICustomFormatter
{
public string Format(string format, object arg,
IFormatProvider formatProvider)
{
// do padding for string arguments
// use default for others
}
}
public class StringPadderFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return new StringPadder();
return null;
}
public static readonly IFormatProvider Default =
new StringPadderFormatProvider();
}
Then you can use it like this :
string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");
For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.
This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.
So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.
If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.
I have found some links using Google, they may help.
They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.
One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.
See these links as well:
Try this (see comments in code):
function fixInteger(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseInt(value);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseInt(value);
}
// apply new value to element
$(el).val(newValue);
}
function fixPrice(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseFloat(value.replace(',', '.')).toFixed(2);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseFloat(value).toFixed(2);
}
// apply new value to element
$(el).val(newValue);
}
Close the emulator if already opened. Right click on your project ->Run as -> run configurations -> Run. After the emulator launched: Right click on your project ->Run as ->android project.
You can call JFrame.setLocationRelativeTo(null)
to center the window. Make sure to put this before JFrame.setVisible(true)
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
You can attempt to use the PHP header
function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.
ob_start();
header("Location: " . $website);
ob_end_flush();
This command returns count of commits grouped by committers:
git shortlog -s
Output:
14 John lennon
9 Janis Joplin
You may want to know that the -s
argument is the contraction form of --summary
.
I didn't know the existing sa password so this is what I did:
Open Services in Control Panel
Find the "SQL Server (SQLEXPRESS)" entry and select properties
Stop the service
Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;
Start the service
Open a Command Prompt
Enter the command:
osql -S YourPcName\SQLEXPRESS -E
(change YourPcName to whatever your PC is called).
alter login sa enable go sp_password NULL,'new_password','sa' go quit
Stop the "SQL Server (SQLEXPRESS)" service
Remove the "-m" from the Start parameters field
Start the service
The best and the easiest way, for me was this..
->Simply create a thread with Handler containing sleep().
private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
myImageView.startAnimation(myFadeInAnimation);
new Thread(new Runnable() {
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.w("hendler", "recived");
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout);
myImageView.startAnimation(myFadeOutAnimation);
myImageView.setVisibility(View.INVISIBLE);
}
};
@Override
public void run() {
try{
Thread.sleep(2000); // your fadein duration
}catch (Exception e){
}
handler.sendEmptyMessage(1);
}
}).start();
}
The method you are looking for is .limit.
Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.
Example usage:
df.limit(1000)
You could take the regex that validates YYYY/MM/DD and flip it around to get what you need for DD/MM/YYYY:
/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/
BTW - this regex validates for either DD/MM/YYYY or DD-MM-YYYY
P.S. This will allow dates such as 31/02/4899
It depends. The System.Timers.Timer
has two modes of operation.
If SynchronizingObject
is set to an ISynchronizeInvoke
instance then the Elapsed
event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke
instances are none other than plain old Control
and Form
instances that we are all familiar with. So in that case the Elapsed
event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer
. Otherwise, it really depends on the specific ISynchronizeInvoke
instance that was used.
If SynchronizingObject
is null then the Elapsed
event is invoked on a ThreadPool
thread and it behaves similar to the System.Threading.Timer
. In fact, it actually uses a System.Threading.Timer
behind the scenes and does the marshaling operation after it receives the timer callback if needed.
In events handler you can get id as follows
function show(btn) {_x000D_
console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
For me the solution was to have
"location=0"
in the 3rd parameter. Tested on latest FF/Chrome and an old version of IE11
Full method call I use is below (As I like to use a variable width):
window.open(url, "window" + id, 'toolbar=0,location=0,scrollbars=1,statusbar=1,menubar=0,resizable=1,width=' + width + ',height=800,left=100,top=50');
Alternative to DATEPART
SELECT LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)
This largely repeats the preceding (by time) five (no, six) (no, seven) answers, but:
Yes, the IF EXISTS structure that you have by and large will double the work done by the database. While IF EXISTS will "stop" when it finds the first matching row (it doesn't need to find them all), it's still extra and ultimately pointless effort--for updates and deletes.
So either way, you'll end up reading the entire table or index at least once. But, why bother with the IF EXISTS in the first place?
UPDATE Contacs SET [Deleted] = 1 WHERE [Type] = 1
or the similar DELETE will work fine whether or not there are any rows found to process. No rows, table scanned, nothing modified, you're done; 1+ rows, table scanned, everything that ought to be is modified, done again. One pass, no fuss, no muss, no having to worry about "did the database get changed by another user between my first query and my second query".
INSERT is the situation where it might be useful -- check if the row is present before adding it, to avoid Primary or Unique Key violations. Of course you have to worry about concurrency -- what if someone else is trying to add this row at the same time as you? Wrapping this all into a single INSERT would handle it all in an implicit transaction (remember your ACID properties!):
INSERT Contacs (col1, col2, etc) values (val1, val2, etc) where not exists (select 1 from Contacs where col1 = val1)
IF @@rowcount = 0 then <didn't insert, process accordingly>
On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks
. They will have the extension .job
For example if you create the task "DoWork" it will create the task in
C:\Windows\Tasks\DoWork.job
Just replace it:
<li><a href="" data-toggle="modal" data-target="#modalRegister">Register</a></li>
Instead of:
<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>
Spent much of my time with this! My bad! Later found that the class on which I declared the annotation Service
or Component
was of type abstract. Had enabled debug logs on Springframework but no hint was received. Please check if the class if of abstract type. If then, the basic rule applied, can't instantiate an abstract class.
If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
You can create a DIV
component using the <h:panelGroup/>
.
By default, the <h:panelGroup/>
will generate a SPAN in the HTML code.
However, if you specify layout="block"
, then the component will be a DIV
in the generated HTML code.
<h:panelGroup layout="block"/>
I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.
Try Eric Meyer's reset.css.
I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.
I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).
Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.
TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.
create user ro_role identified by ro_role;
grant create session, select any table, select any dictionary to ro_role;
I think you lack to pass Connection
object to your command
object. and it is much better if you will use command
and parameters
for that.
using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
command.Parameters.AddWithValue("@staffName", name);
command.Parameters.AddWithValue("@userID", userId);
command.Parameters.AddWithValue("@idDepart", idDepart);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
}
h = fspecial('average', n);
filter2(h, img);
See doc fspecial
:
h = fspecial('average', n)
returns an averaging filter. n
is a 1-by-2 vector specifying the number of rows and columns in h
.
Try df.mean(axis=0)
, axis=0
argument calculates the column wise mean of the dataframe so the result will be axis=1
is row wise mean so you are getting multiple values.
Worked here too:
Sub test544()
Dim chromePath As String
chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromePath & " -url http:google.ca")
End Sub
This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding
You can change the sources encoding or runtime encoding.
I'm on OSX, I was using Android Studio instead of ADT and I had this issue, my problem was being behind a proxy with authentication, for what ever reason, In Android SDK Manager Window, under Preferences -> Others, I needed to uncheck the
"Force https://... sources to be fetched using http://..."
Also, there was no place to put the proxy credentials, but it will prompt you for them.
I had same issue. I had mistakenly created directory in machine in lower case. Once changed the case , the problem solved(but wasted my 1.5 hrs :( ) Check it out your directory name and remote repo name is same.
In my case, the installation of nlme
package is in trouble:
mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme'
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme':
Permission denied
Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:
sudo R
install.packages('nlme')
q()
In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.
This is normally more an issue with ToMany than ToOnes. For example,
Select e from Employee e
join fetch e.phones p
where p.areaCode = '613'
This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.
Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.
You could also wrap the relevant text with
<span style="white-space: nowrap;"></span>
if your SQL query is like this
SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5 ORDERBY col-2 DESC LIMIT 15;
Then for query() method, we can do as:-
String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";
query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
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 = "";
I successfully used
(function(l){var i,s={touchend:function(){}};for(i in s)l.addEventListener(i,s)})(document);
which was documented on http://fofwebdesign.co.uk/template/_testing/ios-sticky-hover-fix.htm
so a variation of Andrew M answer.
Try below code
public enum SalaryHeadMasterEnum {
BASIC_PAY("basic pay"),
MEDICAL_ALLOWANCE("Medical Allowance");
private String name;
private SalaryHeadMasterEnum(String stringVal) {
name=stringVal;
}
public String toString(){
return name;
}
public static String getEnumByString(String code){
for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
if(e.name.equals(code)) return e.name();
}
return null;
}
}
Now you can use below code to retrieve the Enum by Value
SalaryHeadMasterEnum.getEnumByString("Basic Pay")
Use Below code to get ENUM as String
SalaryHeadMasterEnum.BASIC_PAY.name()
Use below code to get string Value for enum
SalaryHeadMasterEnum.BASIC_PAY.toString()
jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button
Please follow steps
Step 1 - Form tag must have an ID field
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Button which you are going to click
<button>Save</button>
Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
for live demo click on below link
How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
E.g.
x = np.arange(9).reshape(3,3)
print x > 5
yields:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
Add it to your project/application/config/config.php file, and it will work on all over your site.
date_default_timezone_set('Asia/Kolkata');
Found this on a different forum
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
What you are doing is passing 664
which in octal is 1230
In your case you would need
os.chmod("/tmp/test_file", 436)
[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666
Set the colspan
attribute to 2.
A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.
Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.
def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/
You can't. IEnumerable<T>
can only be iterated.
In your second example, you can remove from original collection by iterating over a copy of it
foreach(var u in users.ToArray()) // ToArray creates a copy
{
if(u.userId != 1233)
{
users.Remove(u);
}
}
You aren't doing anything with the return value of replace
. You'll need to assign the result of the method, which is the new String
:
sentence = sentence.replace("and", " ");
A String
is immutable in java. Methods like replace
return a new String
.
Your contains
test is unnecessary: replace
will just no-op if there aren't instances of the text to replace.
You need to
set identity_insert YourTable ON
Then delete your row and reinsert it with different identity.
Once you have done the insert don't forget to turn identity_insert off
set identity_insert YourTable OFF
The same way you make anything else negative: put a negative sign in front of it.
var positive = 6;
var negative = -positive;
Use the Set
type:
A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])
result = A_set - subset_of_A_set
We should make everything easier for everyone because you can simply combine JS to PHP Combining PHP and JS is pretty easy.
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = $house_number; document.forms[0].submit();</script>";
Or a somewhat safer way
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = " . $house_number . "; document.forms[0].submit();</script>";
As a native and efficient approach, you don't need to use ord
or any loop over the characters. Just encode with ascii
and ignore the errors.
The following will just remove the non-ascii characters:
new_string = old_string.encode('ascii',errors='ignore')
Now if you want to replace the deleted characters just do the following:
final_string = new_string + b' ' * (len(old_string) - len(new_string))
remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.
http://en.wikipedia.org/wiki/File:IP_stack_connections.svg
that's the long way of saying, "Yes!"
I Just installed Mountain Lion and had the same problem I use FLashBuilder (which is 32bit) and MountainLion is 64bit, which means by default MacPorts installs everything as 64bit. The version of subclipse I use is 1.8 As i had already installed Subversion and JavaHLBindings I just ran this command:
sudo port upgrade --enforce-variants active +universal
This made mac ports go through everything already installed and also install the 32bit version.
I then restarted FlashBuilder and it no longer showed any JavaHL errors.
Another simple solution using the AppCompatButton
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.Button.Colored"
app:backgroundTint="@color/red"
android:text="UNINSTALL" />