FILENAME = 'StarWars.avi'
with ftplib.FTP(FTP_IP, FTP_LOGIN, FTP_PASSWD) as ftp:
ftp.cwd('movies')
with open(FILENAME, 'wb') as f:
ftp.retrbinary('RETR ' + FILENAME, f.write)
Of course it would we be wise to handle possible errors.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
I want to complement polygenelubricants answer:
I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.
To have type compatibility check at compilation time, declare and use a custom function in your enum.
public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable
With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.
I also recommend to add an UNDEFINED value for enum.
uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic
The script webpack-dev-server
is already installed inside ./node_modules directory.
You can either install it again globally by
sudo npm install -g webpack-dev-server
or run it like this
./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config webpack.dev.config.js --content-base public/ --progress --colors
.
means look it in current directory.
You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.
On the other hand, you have PAGE that seems active and works in python 2.7 and py3k
As you indicate on your comment, none of these use the grid
geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.
It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:
By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.
Your syntax is incorrect, you should pass the value as the second parameter:
jQuery(this).prev("li").attr("id","newId");
You can use the class selector along with descendant selector
$("#my_id .my_class")
By convention, the directory src/main/resources
contains the resources that will be used by the application. So Maven will include them in the final JAR
.
Thus in your application, you will access them using the getResourceAsStream()
method, as the resources are loaded in the classpath.
If you need to have them outside your application, do not store them in src/main/resources
as they will be bundled by Maven. Of course, you can exclude them (using the link given by chkal) but it is better to create another directory (for example src/main/external-resources
) in order to keep the conventions regarding the src/main/resources
directory.
In the latter case, you will have to deliver the resources independently as your JAR file (this can be achieved by using the Assembly plugin). If you need to access them in your Eclipse environment, go to the Properties
of your project, then in Java Build Path
in Sources
tab, add the folder (for example src/main/external-resources
). Eclipse will then add this directory in the classpath.
You can pull apps with ADB. They are in /data/App/, I believe.
adb pull (location on device) (where to save)
Note that you have to root your phone to pull copy protected apps.
Clear the cache and cookies and restart the browser .As the style is not suppose to change frequently for a website browser kinda store it .
There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
Demo here: http://jsfiddle.net/hW7Ch/
ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.
Ravel:
A = M.ravel()
print A, A.shape
>>> [1 2 3 4] (4,)
Flatten:
M = np.array([[1], [2], [3], [4]])
A = M.flatten()
print A, A.shape
>>> [1 2 3 4] (4,)
numpy.ravel()
is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are using numpy.ravel()
.
numpy.flatten()
is slower than numpy.ravel()
. But if you are using numpy.flatten()
to create A, then changes in A will not get carried over to the original array M.
numpy.squeeze()
and M.reshape(-1)
are slower than numpy.flatten()
and numpy.ravel()
.
%timeit M.ravel()
>>> 1000000 loops, best of 3: 309 ns per loop
%timeit M.flatten()
>>> 1000000 loops, best of 3: 650 ns per loop
%timeit M.reshape(-1)
>>> 1000000 loops, best of 3: 755 ns per loop
%timeit np.squeeze(M)
>>> 1000000 loops, best of 3: 886 ns per loop
Only IE and WebKit support zoom, and yes, in theory it does exactly what you're saying.
Try it out on an image to see it's full effect :)
In most cases, the %USERNAME% variable will be what you want.
echo %USERNAME%
However, if you're running an elevated cmd shell, then %USERNAME% will report the administrator name instead of your own user name. If you want to know the latter, run:
for /f "tokens=2" %u in ('query session ^| findstr /R "^>"') do @echo %u
As of jQuery 1.7 there's a new way to handle events. I thought I'd answer here just to demonstrate how I might go about doing this the "new" way. If you haven't, I recommend you read the jQuery docs for the "on" method.
var handler = function(event){
// if the target is a descendent of container do nothing
if($(event.target).is(".container, .container *")) return;
// remove event handler from document
$(document).off("click", handler);
// dostuff
}
$(document).on("click", handler);
Here we're abusing jQuery's selectors and bubbling of events. Note that I make sure I clean the event handler up afterwards. You can automate this behaviour with $('.container').one
(see: docs) but because we need to do conditionals within the handler that isn't applicable here.
This works fine for me,
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];
NSError* theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
attributes:nil error:&theError])
{
NSLog(@"not created");
}
You can get and store the server root certificate using next bash script:
CERTS=$(echo -n | openssl s_client -connect $HOST_NAME:$PORT -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p')
echo "$CERTS" | awk -v RS="-----BEGIN CERTIFICATE-----" 'NR > 1 { printf RS $0 > "'$SERVER_ROOT_CERTIFICATE'"; close("'$SERVER_ROOT_CERTIFICATE'") }'
Just overwrite required variables.
I used the above logic but modified it slightly. My input is of format : "apple:100|pinapple:200|orange:300" stored in a variable @updtAdvanceKeyVal
Here is the function block :
set @res = "";
set @i = 1;
set @updtAdvanceKeyVal = updtAdvanceKeyVal;
REPEAT
-- set r = replace(SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
-- LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1),"|","");
-- wrapping the function in "replace" function as above causes to cut off a character from
-- the 2nd splitted value if the value is more than 3 characters. Writing it in 2 lines causes no such problem and the output is as expected
-- sample output by executing the above function :
-- orange:100
-- pi apple:200 !!!!!!!!strange output!!!!!!!!
-- tomato:500
set @r = SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1);
set @r = replace(@r,"|","");
if @r <> "" then
set @key = SUBSTRING_INDEX(@r, ":",1);
set @val = SUBSTRING_INDEX(@r, ":",-1);
select @key, @val;
end if;
set @i = @i + 1;
until @r = ""
END REPEAT;
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt
project of ours. We needed a newer version of connect, since 2.7.3
. was causing trouble for us. So I created a file named npm-shrinkwrap.json
:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
npm
should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
For Safari, -khtml-user-select: none
, just like Mozilla's -moz-user-select
(or, in JavaScript, target.style.KhtmlUserSelect="none";
).
Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable
jQuery(function(){
//here it is a closure variable
var a_href;
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
To make the variable global, one solution is to declare the variable in global scope
var a_href;
jQuery(function(){
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
another is to set the variable as a property of the window object
window.a_href = $(this).attr('href')
Why console printing undefined
You are getting the output as undefined
because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a
element is clicked till that time the variable will have the value undefined
. If you are not declaring the variable it will throw a ReferenceError
Many of the other answers here do not take into account unicode characters (e.g. öäüß??îû??????? ). In this case you can use the following:
$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $string);
There's a strange class of characters in the range \x80-\x9F
(Just above the 7-bit ASCII range of characters) that are technically control characters, but over time have been misused for printable characters. If you don't have any problems with these, then you can use:
$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $string);
If you wish to also strip line feeds, carriage returns, tabs, non-breaking spaces, and soft-hyphens, you can use:
$string = preg_replace('/[\x00-\x1F\x7F-\xA0\xAD]/u', '', $string);
Note that you must use single quotes for the above examples.
If you wish to strip everything except basic printable ASCII characters (all the example characters above will be stripped) you can use:
$string = preg_replace( '/[^[:print:]]/', '',$string);
For reference see http://www.fileformat.info/info/charset/UTF-8/list.htm
You can view which modules (compiled in) are available via terminal through php -m
I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.
If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.
However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:
import StringIO
s = StringIO.StringIO(myString)
for line in s:
do_something_with(line)
if it's just the highest ID you want. and ID is unique/auto_increment:
SELECT MAX(ID) FROM tablename
You probably had a stray build process that was locking the executable, and it (the stray process) didn't get cleaned up. In that case, shut down visual studio, open up process explorer, and nuke every process you can find that is related to visual studio. Then open up visual studio again and try rebuilding your project.
Recently, I faced similar problem and I solved it using following approach
def round(value: Either[Double, Float], places: Int) = {
if (places < 0) 0
else {
val factor = Math.pow(10, places)
value match {
case Left(d) => (Math.round(d * factor) / factor)
case Right(f) => (Math.round(f * factor) / factor)
}
}
}
def round(value: Double): Double = round(Left(value), 0)
def round(value: Double, places: Int): Double = round(Left(value), places)
def round(value: Float): Double = round(Right(value), 0)
def round(value: Float, places: Int): Double = round(Right(value), places)
I used this SO issue. I have couple of overloaded functions for both Float\Double and implicit\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.
When you say "called" I'm going to assume you mean an ID tag.
To make it cross-brower, I wouldn't suggest using the CSS3 []
, although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".
Then:
#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }
This assumes you are using the same classes elsewhere, if not, this will suffice:
.tb { width: 150px }
.rb { width: 20px }
As @David mentioned, to access anything within the division itself:
#divContainer [element] { ... }
Where [element] is whatever HTML element you need.
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
To resolve this issue you have to do two things :
You will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates.
Change few settings of Internet Explorer browser on that machine (where you desire to run automation).
1 . Setting Registry Key / Entry :
To set registry key or entry, you need to open "Registry Editor".
To open "Registry Editor" press windows button key + r alphabet key which will open "Run Window" and then type "regedit" and press enter.
Or Press Windows button key and enter "regedit" at start menu and press enter. Now depending upon your OS type whether 32/64 bit follow the corresponding steps.
Windows 32 bit : go to this location - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl" and check for "FEATURE_BFCACHE" key.
Windows 64 bit : go to this location - HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl and check for "FEATURE_BFCACHE" key. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present.
Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.
2 . Change Settings of Internet Explorer Browser :
Click on setting button and select "Internet options".
On "Internet options" window go to "Security" tab
Now select "Internet" option and unchecked the "Enable Protected Mode" check box and change the "Security level" to low.
Now select "Local Intranet" Option and change the "Security level" to low.
Now select "Trusted Sites" Option and change the "Security level" to low.
I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.
foreach($xml->children() as $newInstr){
$iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
$arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
}
app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
$scope.post = {url: 'http://', title: ''};
$scope.createVariable = function(url) {
$window.location.href = url;
};
$scope.createFixed = function() {
$window.location.href = '/tab/newpost';
};
});
HTML
<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>
As stated it is not allowed. But in JavaScript this is:
var a = Array()
for(let i=1; i<=5; i++) {
a.push(i)
}
var s = "[" + a.join(",") + "]"
(works fine in Firefox, Chrome, Edge, IE11, and without the let in IE9, 8, 7, 5)
Here is my little utility helper for splitting paths int file, path tokens:
import os
# usage: file, path = splitPath(s)
def splitPath(s):
f = os.path.basename(s)
p = s[:-(len(f))-1]
return f, p
Using the Gnumeric spreadsheet application which comes which a commandline utility called ssconvert is indeed super simple:
find . -name '*.xlsx' -exec ssconvert -T Gnumeric_stf:stf_csv {} \;
and you're done!
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
.Skip((pages -1) * 2)_x000D_
.Take(2));
_x000D_
Found out by adding this to your url parameters
approval_prompt=force
Update:
Use access_type=offline&prompt=consent
instead.
approval_prompt=force
no longer works
https://github.com/googleapis/oauth2client/issues/453
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
is it possible to extend query results with literals like this?
Yes.
Select Name
From Customers
UNION ALL
Select 'Jason'
UNION
to add Jason if it isn't already in the result set.UNION ALL
to add Jason whether or not he's already in the result set.Yep. Cloudflare uses it for its DNS instructions homepage: https://1.1.1.1
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Your code doesn't work (parse) because you have an extra )
at the end that causes a Parse Error. Count, you have 2 (
and 3 )
. It would work fine if you fix that, but strtotime()
returns a timestamp, so to get a human readable time use date()
.
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the )
is the main issue here.
If the assembly is referenced and the Class visible :
typeof(namespace.a.b.ClassName)
GetType returns null because the type is not found, with typeof, the compiler may help you to find out the error.
Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php
Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.
I agree with the answers 1 and 2. However, I prefer to specify each library separately. This makes the depencencies clearer in big projects. Yet, there is the danger of mistyping the (case-sensitive) variable names. In that case there is no direct cmake error but some undefined references linker issues later on, which may take some time to resolve. Therefore I use the following cmake function:
function(VerifyVarDefined)
foreach(lib ${ARGV})
if(DEFINED ${lib})
else(DEFINED ${lib})
message(SEND_ERROR "Variable ${lib} is not defined")
endif(DEFINED ${lib})
endforeach()
endfunction(VerifyVarDefined)
For the example mentioned above, this looks like:
VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY)
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )
If I had written "BOOST_PROGRAM_OPTIONS_LIBRARY" there would have been an error triggered by cmake and not much later triggered by the linker.
As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned
$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml
You could always iterate over a copy of the list, leaving you free to modify the original:
for item in list(somelist):
...
somelist.remove(item)
Sometimes you need SPECIFICITY to make sure your styles are applied with strongest factor id
Thanks for @Rob Fletcher for his great answer, in our company we have used
So please consider adding styles prefixed with the id of the app container
#app input:focus::-webkit-input-placeholder, #app textarea:focus::-webkit-input-placeholder {_x000D_
color: #FFFFFF;_x000D_
}_x000D_
_x000D_
#app input:focus:-moz-placeholder, #app textarea:focus:-moz-placeholder {_x000D_
color: #FFFFFF;_x000D_
}
_x000D_
This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().
Here is my code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
The simple way is to create table as textfile and move the file to the appropriate location
CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;
Copy the file to the HDFS Location where table is created.
Hope this helps!!!
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.
I've done this before, and it's not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
Here is a sample. Find only the digits in a String and Process formation as needed.
text.replaceAll("\\d(?!$)", "$0 ");
For more info check google Docs https://developer.android.com/reference/java/util/regex/Pattern Where you can use Pattern
The reason you're getting the unhashable type: 'list'
exception is because k = list[0:j]
sets k
to be a "slice" of the list, which is logically another, often shorter, list. What you need is to get just the first item in list, written like so k = list[0]
. The same for v = list[j + 1:]
which should just be v = list[2]
for the third element of the list returned from the call to readline.split(" ")
.
I noticed several other likely problems with the code, of which I'll mention a few. A big one is you don't want to (re)initialize d
with d = {}
for each line read in the loop. Another is it's generally not a good idea to name variables the same as any of the built-ins types because it'll prevent you from being able to access one of them if you need it — and it's confusing to others who are used to the names designating one of these standard items. For that reason, you ought to rename your variable list
variable something different to avoid issues like that.
Here's a working version of your with these changes in it, I also replaced the if
statement expression you used to check to see if the key was already in the dictionary and now make use of a dictionary's setdefault()
method to accomplish the same thing a little more succinctly.
d = {}
with open("nameerror.txt", "r") as file:
line = file.readline().rstrip()
while line:
lst = line.split() # Split into sequence like ['AAA', 'x', '111'].
k, _, v = lst[:3] # Get first and third items.
d.setdefault(k, []).append(v)
line = file.readline().rstrip()
print('d: {}'.format(d))
Output:
d: {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}
For Cordova based project, run cordova clean android
before build again, as @mkimmet suggested.
The simplest solution with filter:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var mergedArrayWithoutDuplicates = array1.concat(
array2.filter(seccondArrayItem => !array1.includes(seccondArrayItem))
);
Clunky, but it'll work.
SELECT TOP 10 * FROM table WHERE id NOT IN (SELECT TOP 10 id FROM table ORDER BY id) FROM table ORDER BY id
MSSQL's omission of a LIMIT clause is criminal, IMO. You shouldn't have to do this kind of kludgy workaround.
ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);
This worked for me.
The solution mentioned in ".gitignore file not ignoring" is a bit extreme, but should work:
# rm all files
git rm -r --cached .
# add all files as per new .gitignore
git add .
# now, commit for new .gitignore to apply
git commit -m ".gitignore is now working"
(make sure to commit first your changes you want to keep, to avoid any incident as jball037 comments below.
The --cached
option will keep your files untouched on your disk though.)
You also have other more fine-grained solution in the blog post "Making Git ignore already-tracked files":
git rm --cached `git ls-files -i --exclude-standard`
Bassim suggests in his edit:
In case you get an error message like
fatal: path spec '...' did not match any files
, there might be files with spaces in their path.You can remove all other files with option
--ignore-unmatch
:
git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`
but unmatched files will remain in your repository and will have to be removed explicitly by enclosing their path with double quotes:
git rm --cached "<path.to.remaining.file>"
Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".
/// <summary>
/// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not
/// let the JsonProperty control everything.
/// </summary>
/// <typeparam name="T"></typeparam>
public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public IgnoreJsonPropertyResolver()
{
this.PropertyMappings = new Dictionary<string, string>();
var properties = ReflectionHelper<T>.GetGetProperties(false)();
foreach (var propertyInfo in properties)
{
var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
if (jsonProperty != null)
{
PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
}
}
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
var model = new PlanViewModel() {Amount = 100};
var strModel = JsonConvert.SerializeObject(model,settings);
Model:
public class PlanViewModel
{
/// <summary>
/// The customer is charged an amount over an interval for the subscription.
/// </summary>
[JsonProperty(PropertyName = "RecurringPrice")]
public double Amount { get; set; }
/// <summary>
/// Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
/// months or years depending on the value for interval_unit.
/// </summary>
public int Interval { get; set; } = 1;
/// <summary>
/// Number of free trial days that can be granted when a customer is subscribed to this plan.
/// </summary>
public int TrialPeriod { get; set; } = 30;
/// <summary>
/// This indicates a one-time fee charged upfront while creating a subscription for this plan.
/// </summary>
[JsonProperty(PropertyName = "SetupFee")]
public double SetupAmount { get; set; } = 0;
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "TypeId")]
public string Type { get; set; }
/// <summary>
/// Billing Frequency
/// </summary>
[JsonProperty(PropertyName = "BillingFrequency")]
public string Period { get; set; }
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "PlanUseType")]
public string Purpose { get; set; }
}
Static variables are used when only one copy of it is required. Let me explain this with an example:
class circle
{
public float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * this._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now here we have created 2 instances for our class
circle , i.e 2 sets of copies of _PI
along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI
will be created occupying memory. So in such cases it is better to make such variables like _PI
static
and operate on them.
class circle
{
static float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * Circle._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now no matter how many instances are made for the class
circle , only one copy exists of variable _PI
saving our memory.
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.
First use z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
All you should need to do is:
# if the file in the right place isn't already committed:
git add <path to desired file>
# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai
# commit the merge:
git commit
For Swift 3.0 you have to use this:
var postString = ""
do {
let data = try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
} catch {
print(error.localizedDescription)
}
request.httpBody = postString.data(using: .utf8)
100% working TESTED
You can use
%matplotlib qt
If you got the error ImportError: Failed to import any qt binding
then install PyQt5 as: pip install PyQt5
and it works for me.
You could just use REPLACE
:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as [email protected]
will be updated to [email protected]
.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT
, and append .org
to the SUBSTRING
manually instead. Notice the usage of UPPER
to make the search for the .com
ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
In the android\app\build.gradle file,
Replace the version details
implementation 'com.android.support:appcompat-v7:26.1.0'
with
implementation 'com.android.support:appcompat-v7:+'
Android Studio will use a suitable version to make it work for you.
if (v < 0) System.out.println("negative"); else System.out.println("positive");
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
I use the following implementation of round in asm for x86 architecture and MS VS specific C++:
__forceinline int Round(const double v)
{
int r;
__asm
{
FLD v
FISTP r
FWAIT
};
return r;
}
UPD: to return double value
__forceinline double dround(const double v)
{
double r;
__asm
{
FLD v
FRNDINT
FSTP r
FWAIT
};
return r;
}
Output:
dround(0.1): 0.000000000000000
dround(-0.1): -0.000000000000000
dround(0.9): 1.000000000000000
dround(-0.9): -1.000000000000000
dround(1.1): 1.000000000000000
dround(-1.1): -1.000000000000000
dround(0.49999999999999994): 0.000000000000000
dround(-0.49999999999999994): -0.000000000000000
dround(0.5): 0.000000000000000
dround(-0.5): -0.000000000000000
You could set your _JAVA_OPTIONS
environmental variable. For example in bash this would do the trick:
export _JAVA_OPTIONS=-Djava.io.tmpdir=/new/tmp/dir
I put that into my bash login script and it seems to do the trick.
To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.
Just restart the apache2 and mysql:
apache2: sudo /etc/init.d/apache2 restart
mysql: sudo /etc/init.d/mysql restart
then refresh your browser, enjoy phpmyadmin :)
select * from [schema_name].sys.tables
This should work. Make sure you are on the server which consists of your "[schema_name]"
How about
l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]
You can generate a key
by the following command:
php artisan key:generate
The key will be written automatically in your .env
file.
APP_KEY=YOUR_GENERATED_KEY
If you want to see your key
after generation use --show
option
php artisan key:generate --show
Note: The .env
is a hidden file in your project folder.
I think you are creating a document that looks like this:
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in
<mydocument>
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
....
</mydocument>
It refers to the instance of the current class, as meder said.
See the PHP Docs. It's explained under the first example.
Presuming you have a .dmp file created by oracle exp then
imp help=y
will be your friend. It will lead you to
imp file=<file>.dmp show=y
to see the contents of the dump and then something like
imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>
to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
</settings>
Window > Preferences > Maven > User Settings
Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices.
This way you don't need to setEPS()
cairo_ps("image.eps")
plot(1, 10)
dev.off()
WEEK
select TRUNC(sysdate, 'iw') AS iso_week_start_date,
TRUNC(sysdate, 'iw') + 7 - 1/86400 AS iso_week_end_date
from dual;
MONTH
select
TRUNC (sysdate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (sysdate, 'mm')) + 1 - 1/86400 AS month_end_date
from dual;
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
How do I rename a specific column in pandas?
From v0.24+, to rename one (or more) columns at a time,
DataFrame.rename()
with axis=1
or axis='columns'
(the axis
argument was introduced in v0.21
.
Index.str.replace()
for string/regex based replacement.
If you need to rename ALL columns at once,
DataFrame.set_axis()
method with axis=1
. Pass a list-like sequence. Options are available for in-place modification as well.rename
with axis=1
df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df
y gdp cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
With 0.21+, you can now specify an axis
parameter with rename
:
df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
(Note that rename
is not in-place by default, so you will need to assign the result back.)
This addition has been made to improve consistency with the rest of the API. The new axis
argument is analogous to the columns
parameter—they do the same thing.
df.rename(columns={'gdp': 'log(gdp)'})
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
rename
also accepts a callback that is called once for each column.
df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')
y g c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For this specific scenario, you would want to use
df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)
Index.str.replace
Similar to replace
method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace
method for string and regex-based replacement.
df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
The advantage of this over the other methods is that str.replace
supports regex (enabled by default). See the docs for more information.
set_axis
with axis=1
Call set_axis
with a list of header(s). The list must be equal in length to the columns/index size. set_axis
mutates the original DataFrame by default, but you can specify inplace=False
to return a modified copy.
df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)
cap log(gdp) y
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
Note: In future releases, inplace
will default to True
.
Method Chaining
Why choose set_axis
when we already have an efficient way of assigning columns with df.columns = ...
? As shown by Ted Petrou in this answer set_axis
is useful when trying to chain methods.
Compare
# new for pandas 0.21+
df.some_method1()
.some_method2()
.set_axis()
.some_method3()
Versus
# old way
df1 = df.some_method1()
.some_method2()
df1.columns = columns
df1.some_method3()
The former is more natural and free flowing syntax.
One situation where it is quite useful to be able to handle the x-button click event is when you are using a Form that is an MDI container. The reason is that the closeing and closed events are raised first with children and lastly with the parent. So in one scenario a user clicks the x-button to close the application and the MDI parent asks for a confirmation to proceed. In case he decides to not close the application but carry on whatever he is doing the children will already have processed the closing event potentially lost information/work whatever. One solution is to intercept the WM_CLOSE message from the Windows message loop in your main application form (i.e. which closed, terminates the application) like so:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0010) // WM_CLOSE
{
// If we don't want to close this window
if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
}
base.WndProc(ref m);
}
You can use this attributes:
background-size: contain;
background-repeat: no-repeat;
and you code is then like this:
<div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.
I had a similar problem where Xcode would spend lots of time indexing and would frequently hang building the project, at which point I had to force-quit and relaunch Xcode. It was very annoying.
Then I noticed a warning in the project about improperly assigning self
as a delegate. Sure enough, there was a missing protocol in the class declaration. Note that there is a similar assignment in the OP's sample code (though it is impossible to tell from the sample whether the correct protocol is declared):
leaderboardController.leaderboardDelegate == self;
After resolving that warning (by correctly declaring the implemented protocol), Xcode stopped misbehaving. Also, I should note that the project did execute correctly since the protocol methods were implemented. It was just that Xcode could not confirm that the protocol should in fact implemented by the class.
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
Microsoft IE does not support a name as second argument.
window.open('url', 'window name', 'window settings');
Problem is window name
. This will work:
window.open('url', '', 'window settings')
Microsoft only allows the following arguments, If using that argument at all:
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...)
of the ActionListener
registered with the Start button, not for the Start button itself.
You can add a simple ActionListener
like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final
in the above example if you want to create the anonymous listener in local scope.
An ideal solution will:
Using a simple ul
menu inside of an nav
container, we can build a solution that meets the above requirements.
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Basic Services</li>
<li>Specialty Services</li>
<li>Our Staff</li>
<li>Contact Us</li>
</ul>
</nav>
First, we need to force the ul
to have the full width of its nav
container. To accomplish this, we will use the :after
psuedo-element with width: 100%
.
This achieves our goal perfectly, but adds trailing whitespace from the psuedo-element. We can remove this whitespace across all browsers through IE8 by setting the line-height
of the ul
to 0 and setting it back to 100% on its li
children. See the example CodePen and solution below:
nav {
width: 900px;
}
nav ul {
text-align: justify;
line-height: 0;
margin: 0;
padding: 0;
}
nav ul:after {
content: '';
display: inline-block;
width: 100%;
}
nav ul li {
display: inline-block;
line-height: 100%;
}
Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
Everything else ie. Params, Authorization, Body, Pre-request Script, Tests is empty, just open the Headers tab and add as shown in image. Its the same for GET request as well.
A JTextField
was designed to use an ActionListener
just like a JButton
is. See the addActionListener()
method of JTextField
.
For example:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.
JButton button = new JButton("Do Something");
button.addActionListener( action );
Note, this example uses an Action
, which implements ActionListener
because Action
is a newer API with addition features. For example you could disable the Action
which would disable the event for both the text field and the button.
What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.
Without using connect by or regexp:
with mytable as (
select 108 name, 'test' project, 'Err1,Err2,Err3' error from dual
union all
select 109, 'test2', 'Err1' from dual
)
,x as (
select name
,project
,','||error||',' error
from mytable
)
,iter as (SELECT rownum AS pos
FROM all_objects
)
select x.name,x.project
,SUBSTR(x.error
,INSTR(x.error, ',', 1, iter.pos) + 1
,INSTR(x.error, ',', 1, iter.pos + 1)-INSTR(x.error, ',', 1, iter.pos)-1
) error
from x, iter
where iter.pos < = (LENGTH(x.error) - LENGTH(REPLACE(x.error, ','))) - 1;
Tumblr has a public API that provides JSON. You can get a dump of posts using a simple url like http://puppygifs.tumblr.com/api/read/json
.
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
You need a pointer to the first char to have an ANSI string.
printf("%s", source + i);
will do the job
Plus, of course you should have meant strlen(source)
, not sizeof(source)
.
I just happened to have started my home business application in windows forms for the convenience. I'm currently using Visual C# Express 2010 / SQL Server 2008 R2 Express to develop it. I got the same problem as OP where I need to connect to an instance of SQL server. I'm skipping details here but that database will be a merged database synched between 2-3 computers that will also use the application I'm developing right now.
I found a quick workaround, at least, I think I did because I'm now able to use my stored procedures in tableadapters without any issues so far.
I copy pasted an SQL connection that I used in a different project at work (VS2010 Premium) in the app.config and changed everything I needed there. When I went back to my Settings.settings, I just had to confirm that I wanted what was inside the app.config file. The only downsides I can see is that you can't "test" the connection since when you go inside the configuration of the connection string you can't go anywhere since "SQL Server" is not an option. The other downside is that you need to input everything manually since you can't use any wizards to make it work.
I don't know if I should have done it that way but at least I can connect to my SQL server now :).
EDIT :
It only works with SQL Server 2008 R2 Express instances. If you try with SQL Server 2008 R2 Workgroup and up, you'll get a nasty warning from Visual C# 2010 Express telling you that "you can't use that connection with the current version of Visual Studio". I got that when I was trying to modify some of my tableadapters. I switched back to an SQL Express instance to develop and it's working fine again.
If you want the #header
to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).
Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:
#container {
position: relative;
width: 80%;
}
#header {
position: relative;
height: 50px;
padding: 10px;
}
You can see it in action here.
The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block
child with no width set.
Update
Another option for dealing with this is to use the box-sizing CSS rule:
#container {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
/* Since this element now uses border-box sizing, the 10px of horizontal
padding will be drawn inside the 80% width */
width: 80%;
padding: 0 10px;
}
Here's a post talking about how box-sizing works.
Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:
For satisfying multiple (all) conditions:
select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] # 1 < x <5
For satisfying multiple (or) conditions:
select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.
Here's an example from the ARIA spec:
<ul role="menubar">
<!-- Rule 2A: "File" label via aria-labelledby -->
<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
<ul role="menu">
<!-- Rule 2C: "New" label via Namefrom:contents -->
<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>
...
</ul>
</li>
...
</ul>
Note the role
attribute on the outer <ul>
element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
A scriptless, CSS-only experimental approach with image pre-loadingBONUS! and which only works in Firefox:
<style>
a.zoom .full { display: none; }
a.zoom:active .thumb { display: none; }
a.zoom:active .full { display: inline; }
</style>
<a class="zoom" href="#">
<img class="thumb" src="thumbnail.png"/>
<img class="full" src="fullsize.png"/>
</a>
Shows the thumbnail by default. Shows the full size image while the mouse button is clicked and held down. Goes back to the thumbnail as soon as the button is released. I'm in no way suggesting that this method be used; it's just a demo of a CSS-only approach that [very] partially solves the problem. With some z-index + relative position tweaks, it could work in other browsers too.
You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
I use layers to describe the architect or technology stack within a component of my solutions. I use tiers to logically group those components typically when network or interprocess communication is involved.
A better way worked for me.
chown root:root /tmp
chmod 1777 /tmp
/etc/init.d/mysqld restart
That is it.
http://smashingweb.info/solved-mysql-tmp-error-cant-createwrite-to-file-tmpmykbo3bl-errcode-13/
As far as the actual loading image, check out this site for a bunch of options.
As far as displaying a DIV with this image when a request begins, you have a few choices:
A) Manually show and hide the image:
$('#form').submit(function() {
$('#wait').show();
$.post('/whatever.php', function() {
$('#wait').hide();
});
return false;
});
B) Use ajaxStart and ajaxComplete:
$('#wait').ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
Using this the element will show/hide for any request. Could be good or bad, depending on the need.
C) Use individual callbacks for a particular request:
$('#form').submit(function() {
$.ajax({
url: '/whatever.php',
beforeSend: function() { $('#wait').show(); },
complete: function() { $('#wait').hide(); }
});
return false;
});
You should use any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
<?php
$subject = "this is a subject";
$message = "testing a message";
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: The Sender <[email protected]>\r\n";
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
mail("[email protected]", $subject, $message, $headers);
?>
I had the same issue, and the following syntax worked for me:
df.filter(df("state")==="TX").show()
I'm using Spark 1.6.
A new twist on an old favorite:
public bool IsWithinRange(int number, int topOfRange, int bottomOfRange, bool includeBoundaries) {
if (includeBoundaries)
return number <= topOfRange && number >= bottomOfRange;
return number < topOfRange && number > bottomOfRange;
}
I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project
. Instead of creating objects using new operator
you can also use static method
to instantiate a class. Code listing:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.
Another example taken from Effective Java.
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean)
method illustrates us, it never creates an object. The ability of static factory methods
to return the same object from repeated invocations
allows classes to maintain strict control over what instances exist at any time.
Static factory methods
is that, unlike constructors
, they can return an object
of any subtype
of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.
Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar
, JapaneseImperialCalendar
or by default one Georgian
.
Another example which i could think is Singleton pattern
, where you make your constructors private create an own getInstance
method where you make sure, that there is always just one instance available.
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
I don't have MySQL, but there are RDBMS (Postgres, among others) in which you can use the hack
SELECT id || '' FROM some_table;
The concatenate does an implicit conversion.
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
Now the <b>
element is deprecated. <strong>
renders as <b>
, and <em>
renders as <i>
.
tv.setText(Html.fromHtml("<strong>bold</strong> and <em>italic</em> "));
Adding my two cents, based on a performance issue I observed.
If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.
In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP
) are mentioned as important settings to check.
Note: Paul White mentioned max server memory
aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server
Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP
.
Why is cost threshold for parallelism ignored?
Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.
Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
Include below property in application.properties
server.port=8080
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :
LAST UPDATE :
In v10.12.0, NodeJS impletement recursive options :
// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
UPDATE :
// Get modules node
const fs = require('fs');
const path = require('path');
// Create
function mkdirpath(dirPath)
{
if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
{
try
{
fs.mkdirSync(dirPath);
}
catch(e)
{
mkdirpath(path.dirname(dirPath));
mkdirpath(dirPath);
}
}
}
// Create folder path
mkdirpath('my/new/folder/create');
There is no inbuilt function to get you the week number. I dont think dividing will help you anyway as the number of weeks in a month is not constant.
http://msdn.microsoft.com/en-us/library/bb675168.aspx
I guess you can divide the number(48) by 4 and take the modules of the same and project that as the week number of that month, by adding one to the result.
Windows Solution
Windows-Key + R
putty.exe -ssh [username]@[hostname] -pw [password]
Here's a solution using a negative lookahead (not supported in all regex engines):
^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$
Test that it works as expected:
import re
tests = [
('a', True),
('_', False),
('zz', True),
('a0', True),
('A_', False),
('a0_b', True),
('a__b', False),
('a_1_c', True),
]
regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
is_match = re.match(regex, test[0]) is not None
if is_match != test[1]:
print "fail: " + test[0]
If you are using Python 3 it might be because you are typing Tkinter
not tkinter
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in
clause...
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.
When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.
Hope this helps any others having a similar issue.
UPDATE users
SET first_name = CONCAT(UCASE(LEFT(first_name, 1)),
LCASE(SUBSTRING(first_name, 2)))
,last_name = CONCAT(UCASE(LEFT(last_name, 1)),
LCASE(SUBSTRING(last_name, 2)));
Swift 5:
extension UIImage {
func cropped(rect: CGRect) -> UIImage? {
guard let cgImage = cgImage else { return nil }
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0.0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.draw(cgImage, in: CGRect(x: rect.minX, y: rect.minY, width: self.size.width, height: self.size.height), byTiling: false)
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return croppedImage
}
}
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
A dozen pages is not a big deal when using OFFSET
. But when you have hundreds of pages, you will find that OFFSET
is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
as prior ans remove the height attrib. if u want your expansion along with its min height then use min-height: 102px
instead of height: 102px.
note ie 6 and min-height http://www.dustindiaz.com/min-height-fast-hack/
You could try in this way.
SOAPMessage msg = messageContext.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
If you want to replace a single semicolon:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Havent tested it though.
I have used the following query. It has worked great for me in the past.
select date(now()) - interval day(now()) day + interval 1 day
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
Probably the password of the account that you trying to send e-mail is expired. Just check your password policy expire date.
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
DESCRIBE <table>;
This is acutally a shortcut for:
SHOW COLUMNS FROM <table>;
In any case, there are three possible values for the "Key" attribute:
PRI
UNI
MUL
The meaning of PRI
and UNI
are quite clear:
PRI
=> primary keyUNI
=> unique keyThe third possibility, MUL
, (which you asked about) is basically an index that is neither a primary key nor a unique key. The name comes from "multiple" because multiple occurrences of the same value are allowed. Straight from the MySQL documentation:
If
Key
isMUL
, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.
There is also a final caveat:
If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order
PRI
,UNI
,MUL
.
As a general note, the MySQL documentation is quite good. When in doubt, check it out!
Center vertically and horizontally:
.parent{
height: 100%;
position: absolute;
width: 100%;
top: 0;
left: 0;
}
.c{
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
}
Here is an example of how to send email through GMail which also uses SSL/465. Minor tweaking of the code below should work!
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}
I would suggest this to hide elements (as others have suggested):
document.getElementById(id).style.display = 'none';
But to make elements visible, I'd suggest this (instead of display = 'block'):
document.getElementById(id).style.display = '';
The reason is that using display = 'block' is causing additional margin/whitespace next to the element being made visible in both IE (11) and Chrome (Version 43.0.2357.130 m) on the page I'm working on.
When you first load a page in Chrome, an element without a style attribute will appear like this in the DOM inspector:
element.style {
}
Hiding it using the standard JavaScript makes it this, as expected:
element.style {
display: none;
}
Making it visible again using display = 'block' changes it to this:
element.style {
display: block;
}
Which is not the same as it originally was. This could very well not make any difference in the majority of cases. But in some cases, it does introduce abnormalities.
Using display = '' does restore it to its original state in the DOM inspector, so it seems like the better approach.
Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)
then... v. SQL> connect /as sysdba
Connected. [SQL prompt response]
vi. SQL> alter user SYS identified by "newpassword";
User altered. [SQL prompt response]
Thank you. This minimized a headache
I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.
I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
Here's a solution that should always work and doesn't remove the hash.
let currentPage = new URL(window.location.href);
currentPage.searchParams.set('r', (+new Date * Math.random()).toString(36).substring(0, 5));
window.location.href = currentPage.href;
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
You can use this JQuery for uncheck radiobutton
$('input:radio[name="IntroducerType"]').removeAttr('checked');
$('input:radio[name="IntroducerType"]').prop('checked', false);
I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.
Some of the answers I've seen explain how to make the contents of a cell invisible, but not how to hide the entire column, which is what I wanted to do.
If you have AutoGenerateColumns = "false"
and are actually using BoundField
for the column you want to hide, Bala's answer is slick. But if you are using TemplateField
for the column, you can handle the DataBound
event and do something like this:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
This may not be what the OP was looking for, but it's the solution I was looking for when I found myself asking the same question.
has_key has been deprecated in Python 3.0. Alternatively you can use 'in'
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
Numpy arrays do not have an append method. Use the Numpy append function instead:
import numpy as np
array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely
For example, if array_1 and array_2 have the following values:
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
If you call np.append without specifying an axis value, like so:
array_3 = np.append(array_1, array_2)
array_3 will have the following value:
array([1, 2, 3, 4])
Else, if you call np.append with an axis value of 0, like so:
array_3 = np.append(array_1, array_2, axis=0)
array_3 will have the following value:
array([[1, 2],
[3, 4]])
More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";
// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
yield mb_substr($str, $i, 1);
}
})($str);
var_dump(
true === $gen instanceof Traversable,
// PHP 7.1
true === is_iterable($gen)
);
foreach ($gen as $char) {
echo $char, PHP_EOL;
}
There are a lot of answers on here but I think the most idiomatic way to do this with Flags would be Letters.AB.HasFlag(letter) or (Letters.A | Letters.B).HasFlag(letter) if you didn't already have Letters.AB. letter.HasFlag(Letters.AB) only works if it has both.
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
This seems to work:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
var endpoint = socket.manager.handshaken[socket.id].address;
console.log('Client connected from: ' + endpoint.address + ":" + endpoint.port);
});
new Guid()
makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).
Guid.NewGuid()
makes an actual guid with a unique value, what you probably want.
LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.
Changing your lists to numpy
arrays will do the job!!
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15
plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()
String[] value_split = rat_values.split(Pattern.quote("|"));
//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)
String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters)
{
StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
while(StrTkn.hasMoreTokens())
{
ArrLis.add(StrTkn.nextToken());
}
return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 , Service 3 , Atmosphere 3 , Value for money 1 ]
For those getting this error in a Jenkins pipeline, it can be fixed by using an SSH Agent plugin. Then wrap your git commands in something like this:
sshagent(['my-ssh-key']) {
git remote set-url origin [email protected]:username/reponame.git
sh 'git push origin branch_name'
}
If you are converting a varchar to int make sure you do not have decimal places.
For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.
CONVERT(int, replace(FIELD_NAME,'.0',''))
For those wondering, @edward-coast
If you want to set the keep alive for the server, add this to /etc/ssh/sshd_config
:
ClientAliveInterval 60
ClientAliveCountMax 2
ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client.
ClientAliveCountMax: Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.
On Java 9 or later, Map.entry
can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry
(as suggested in another answer) or AbstractMap.SimpleImmutableEntry
would be the way to go.
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream().map(e ->
Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
I have had success with the solution proposed within this article, a class called GifMovieView
, which renders a View
which can then be displayed or added to a specific ViewGroup
. Check out the other methods presented in parts 2 and 3 of the specified article.
The only drawback to this method is that the antialiasing on the movie is not that good (must be a side-effect of using the "shady" Android Movie
Class). You are then better off setting the background to a solid color within your animated GIF.
Option Explicit
Public myarray (1 To 10)
Public Count As Integer
myarray(1) = "A"
myarray(2) = "B"
myarray(3) = "C"
myarray(4) = "D"
myarray(5) = "E"
myarray(6) = "F"
myarray(7) = "G"
myarray(8) = "H"
myarray(9) = "I"
myarray(10) = "J"
Private Function unwrapArray()
For Count = 1 to UBound(myarray)
MsgBox "Letters of the Alphabet : " & myarray(Count)
Next
End Function
I found a nicer way in a comment on this issue on github:
git branch --merged master --no-color | grep -v master | grep -v stable | xargs git branch -d
edit: added no-color option and excluding of stable branch (add other branches as needed in your case)
All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
You could simply use
return
which does exactly the same as
return None
Your function will also return None
if execution reaches the end of the function body without hitting a return
statement. Returning nothing is the same as returning None
in Python.
sklearn.model_selection.train_test_split(*arrays, **options)[source]
Split arrays or matrices into random train and test subsets
Parameters: ...
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune
Well, its true that we can use Vb Script for what you intended to do. We can open an application through the code like Internet Explorer. We can navigate to site you intend for. Later we can check the element names of Text Boxes which require username and password; can set then and then Login. It works fine all of using code.
No manual interaction with the website. And eventually you will end up signing in by just double clicking the file.
To get you started :
Set objIE = CreateObject("InternetExplorer.Application")
Call objIE.Navigate("https://gmail.com")
This will open an instance of internet explore and navigate to gmail. Rest you can learn and apply.
You need to use cat
to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.
test="$(cat DSC_0251.JPG | base64)"
However, base64
can read from the file itself:
test=$( base64 DSC_0251.JPG )
In my case PDFGenerator was producing an info.plist file, I just deleted it.
see NSURLError.h Define
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}]
quite a bit. I would only do this if:
Without checking your code, I think what you are describing is that your pages are out of sync and you have stale data.
You say you are changing the number of pages, then crashing because you are accessing the old set of pages. This sounds to me like you are not calling pageAdapter.notifyDataSetChanged()
after changing your data.
When your viewPager
is showing page 3 of a set of 10 pages, and you change to a set with only 5, then call notifyDataSetChanged()
, what you'll find is you are now viewing page 3 of the new set. If you were previously viewing page 8 of the old set, after putting in the new set and calling notifyDataSetChanged()
you will find you are now viewing the last page of the new set without crashing.
If you simply change your current page, you may just be masking the problem.
use DateTime.Now
try this:
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
name
not Name
.The following code is functionally equivalent to Jon Skeet's answer.
Tested on .NET 4.5, should work on any earlier version of LINQ.
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
return source.Where(element => seenKeys.Add(keySelector(element)));
}
Incidentially, check out Jon Skeet's latest version of DistinctBy.cs on Google Code.
Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.
In plain old javascript (new Date()).getTimezoneOffset()/60
will return the current number of hours offset from UTC.
It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset()
return value (from MDN docs):
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.
However, I recommend you use the day.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:
> dayjs().format("Z")
"-08:00"
It probably bears mentioning that the client can easily falsify this information.
(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)
It's really useful, I used it with a slight change:
filename=directory.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.startsWith(ipro);
}
});
It's good practice to use a context manager or call close()
in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.
Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE
. If you're using FileSystemStorage
you can write a custom mixin.
You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT
. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.
Here's an example where self
is the model instance where my_file
is the FileField / ImageFile, calling save()
on the whole model instance instead of just FileField:
import os
from django.core.files import File
with open(filepath, 'rb') as fi:
self.my_file = File(fi, name=os.path.basename(fi.name))
self.save()
Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.
Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.
To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.
If you are running SQL Server on Linux, there is an app you can add to your systray called "killall" Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program. Hope that helps.
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
Here's a vanilla js example to trigger any event:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
Log4JDBC is a nice solution which prints the exact SQL going to the database with parameters in place rather than the most popular answer here which does not do this. One major convenience of this is that you can copy the SQL straight to your DB front-end and execute as is.
http://log4jdbc.sourceforge.net/
https://code.google.com/p/log4jdbc-remix/
The latter also outputs a tabular representation of query results.
Sample Output showing generated SQL with params in place together with result set table from query:
5. insert into ENQUIRY_APPLICANT_DETAILS (ID, INCLUDED_IN_QUOTE, APPLICANT_ID, TERRITORY_ID, ENQUIRY_ID, ELIGIBLE_FOR_COVER) values (7, 1, 11, 1, 2, 0)
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |ID |CREATED |DELETED |CODESET_ID |NAME |POSITION |PREFIX |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |2 |null |null |1 |Country 2 |1 |60 |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
Most recently I have now been using log4jdbc-log4j2 (https://code.google.com/archive/p/log4jdbc-log4j2/ ) with SLF4j and logback. Maven dependencies required for my set-up are as below:
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>$logback.version}</version>
</dependency>
The Driver and DB Urls then look like:
database.driver.class=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
database.url=jdbc:log4jdbc:hsqldb:mem:db_name #Hsql
#database.url=jdbc:log4jdbc:mysql://localhost:3306/db_name
My logback.xml configuration file looks like the below: this outputs all SQL statements with parameters plus the resultset tables for all queries.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="jdbc.audit" level="ERROR" />
<logger name="jdbc.connection" level="ERROR" />
<logger name="jdbc.sqltiming" level="ERROR" />
<logger name="jdbc.resultset" level="ERROR" />
<!-- UNCOMMENT THE BELOW TO HIDE THE RESULT SET TABLE OUTPUT -->
<!--<logger name="jdbc.resultsettable" level="ERROR" /> -->
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Finally, I had to create a file named log4jdbc.log4j2.properties at the root of the classpath e.g. src/test/resources or src/main/resources in a Mevn project. This file has one line which is the below:
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
The above will depend on your logging library. See the docs at https://code.google.com/archive/p/log4jdbc-log4j2 for further info
Sample Output:
10:44:29.400 [main] DEBUG jdbc.sqlonly - org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
5. select memberrole0_.member_id as member_i2_12_0_, memberrole0_.id as id1_12_0_, memberrole0_.id
as id1_12_1_, memberrole0_.member_id as member_i2_12_1_, memberrole0_.role_id as role_id3_12_1_,
role1_.id as id1_17_2_, role1_.name as name2_17_2_ from member_roles memberrole0_ left outer
join roles role1_ on memberrole0_.role_id=role1_.id where memberrole0_.member_id=104
10:44:29.402 [main] INFO jdbc.resultsettable -
|----------|---|---|----------|--------|---|-----|
|member_id |id |id |member_id |role_id |id |name |
|----------|---|---|----------|--------|---|-----|
|----------|---|---|----------|--------|---|-----|
Assuming employee numbers are in the first column and their names are in the second:
=VLOOKUP(A1, Sheet2!A:B, 2,false)
Go to pom.xml
Add this Dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
using command prompt, find your folder: - mvn clean
Background image fix to screens with browser compatibility css
.full-screen {
height: 100%;
width: 100%;
background-image: url(../images/banner.jpg);
background-size: cover;
background-position: center;
//for browser compatibility
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
}