I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
You can do something like this:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
if (wordList.length == wordCount) {
// expand list
wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
}
wordList[wordCount] = s.next();
wordCount++;
}
}
Using java.util.Arrays.copyOf(String[])
is basically doing the same thing as:
if (wordList.length == wordCount) {
String[] temp = new String[wordList.length + arrayGrowth];
System.arraycopy(wordList, 0, temp, 0, wordList.length);
wordList = temp;
}
except it is one line of code instead of three. :)
"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.
So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.
Here is an example.
int main()
{
const char *filename = "C:\\myfile.txt";
printf("Filename is: %s\n", filename);
}
The file name is "hard coded" as: C:\myfile.txt
The reason the backslash is doubled is because backslashes are special in C strings.
The following might be useful (tested on: Linux/Ubuntu 12.04 (Precise Pangolin)):
cat /dev/ttyUSB0
Using the above, you can then do all the re-directions that you need. For example, to dump output to your console while saving to your file, you'd do:
cat /dev/ttyUSB0 | tee console.log
Actually, looking through MSDN, the functions they recommend using (instead of Protected Storage) are:
CryptProtectData
CryptUnprotectData
The link for CryptProtectData
is at CryptProtectData function.
Don't use firefox profile and try below code:
driver.get("http://UserName:[email protected]");
If you're implementing it in IE browser, there are certain things which you need to do.
In case your authentication server requires username with domain like "domainuser" you need to add double slash /
to the url:
//localdomain\user:[email protected]
The dplyr
package contains summarise_all
for this aim:
library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#> grp a b c d
#> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 3.08 2.98 2.98 2.91
#> 2 2 3.03 3.04 2.97 2.87
#> 3 3 2.85 2.95 2.95 3.06
Alternatively, the purrrlyr
package provides the same functionality:
library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#> grp a b c d
#> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 3.08 2.98 2.98 2.91
#> 2 2 3.03 3.04 2.97 2.87
#> 3 3 2.85 2.95 2.95 3.06
Also don't forget about data.table
(use keyby
to sort sort groups):
library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#> grp a b c d
#> 1: 1 3.079412 2.979412 2.979412 2.914706
#> 2: 2 3.029126 3.038835 2.967638 2.873786
#> 3: 3 2.854701 2.948718 2.951567 3.062678
Let's try to compare performance.
library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
a = sample(1:5, n, replace = TRUE),
b = sample(1:5, n, replace = TRUE),
c = sample(1:5, n, replace = TRUE),
d = sample(1:5, n, replace = TRUE),
grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
data.table = dt[, lapply(.SD, mean), keyby = grp],
check = FALSE
)
#> # A tibble: 3 x 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 dplyr 2.81ms 2.85ms 328. NA 17.3
#> 2 purrrlyr 7.96ms 8.04ms 123. NA 24.5
#> 3 data.table 596.33µs 707.91µs 1409. NA 10.3
Though this question has an answer, I resolved it differently when I had the same issue. I had this issue when I copied folders with the option Create Folder references
; then the above solution of adding the folder to the build_path worked.
But when the folder was added using the Create groups for any added folder
option, the headers were picked up automatically.
What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}
Use json_decode
to convert String into Object (stdClass
) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
You should convert it to Object (stdClass):
$manage = json_decode($data);
But working with stdClass
is more complicated than PHP-Array, then try this (use second param with true
):
$manage = json_decode($data, true);
This way you can use array functions: http://php.net/manual/en/function.array.php
adding an item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
echo '<br>After: <br>';
print_r($manage);
remove first item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
$manage = json_decode($data, true);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}
I hope I have understood your question.
Good luck.
If you just want to determine whether a particular named lock is currently held, you can use IS_USED_LOCK
:
SELECT IS_USED_LOCK('foobar');
If some connection holds the lock, that connection's ID will be returned; otherwise, the result is NULL
.
After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?
Look for lines that start with LoadModule php
...
There probably are configuration files/directories named mods
or something like that, start from there.
You could also check output from php -r 'phpinfo();' | grep php
and compare lines to phpinfo();
from web server.
php
interactively:(so you can paste/write code in the console)
php -a
php -f file.php
php -f file.php > results.html
To run only small part, one line or like, you can use:
php -r '$x = "Hello World"; echo "$x\n";'
If you are running linux then do man php
at console.
if you need/want to run php through fpm, use cli fcgi
SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"
where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.
Here's a simple elvis operator equivalent:
function elvis(object, path) {
return path ? path.split('.').reduce(function (nestedObject, key) {
return nestedObject && nestedObject[key];
}, object) : object;
}
> var o = { a: { b: 2 }, c: 3 };
> elvis(o)
{ a: { b: 2 }, c: 3 }
> elvis(o, 'a');
{ b: 2 }
> elvis(o, 'a.b');
2
> elvis(o, 'x');
undefined
You can use the isdigit() method for strings. In this case, as you said the input is always a string:
user_input = input("Enter something:")
if user_input.isdigit():
print("Is a number")
else:
print("Not a number")
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
Very simple:
#content {
max-height: 100%;
}
If you're using python >= 3.8, you can use the fmean
function introduced in the statistics
module which is part of the standard library:
>>> from statistics import fmean
>>> fmean([0, 1, 2, 3])
1.5
It's faster than the statistics.mean
function, but it converts its data points to float
beforehand, so it can be less accurate in some specific cases.
You can see its implementation here
If you can't rename the original file, you could also use a symlink:
ln -s foo-bar.py foo_bar.py
Then you can just:
from foo_bar import *
Usually, stopping and restarting that particular cell fixes this issue.
A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.
Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.
In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.
Below a useless code is given, but it will suffice to do away with your some confusions about Runnable
. It will print "Hello World".
class NamedRunnable implements Runnable {
public void run() { // The run method prints a message to standard output.
System.out.println("Hello World");
}
public static void main(String[]arg){
NamedRunnable namedRunnable = new NamedRunnable( );
namedRunnable.run();
}
}
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).
txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);
msdn:
There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.
You could break after the setting line and check the value of IsKeyboardFocused
property. Also check if you really reach that line or maybe you set some other element to get focus after that.
The C# DLL is set up with platform target x86
Which is kind of the problem, a DLL doesn't actually get to choose what the bitness of the process will be. That's entirely determined by the EXE project, that's the first assembly that gets loaded so its Platform target setting is the one that counts and sets the bitness for the process.
The DLLs have no choice, they need to be compatible with the process bitness. If they are not then you'll get a big Kaboom with a BadImageFormatException when your code tries to use them.
So a good selection for the DLLs is AnyCPU so they work either way. That makes lots of sense for C# DLLs, they do work either way. But sure, not your C++/CLI mixed mode DLL, it contains unmanaged code that can only work well when the process runs in 32-bit mode. You can get the build system to generate warnings about that. Which is exactly what you got. Just warnings, it still builds properly.
Just punt the problem. Set the EXE project's Platform target to x86, it isn't going to work with any other setting. And just keep all the DLL projects at AnyCPU.
My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.
Why?
composer install
Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.
What's the correct way to deploy this without installing the -dev dependencies?
The command to use is
composer install --no-dev
This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.
The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.
If you don't mind deploying development software components on a production server, running composer install
would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.
I have written a program to iterate all Threads
created and printing getState()
of each Thread
import java.util.Set;
public class ThreadStatus {
public static void main(String args[]) throws Exception{
for ( int i=0; i< 5; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:"+threadCount);
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(2000);
}catch(Exception err){
err.printStackTrace();
}
}
}
Output:
java ThreadStatus
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6
If you remove below condition
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())
You will get below threads in output too, which have been started by system.
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer
.
You can just rewrite it as:
int qempty(){ return(f==r);}
Which does the same thing as said in the other answers.
Android Studio 3.5.3 It works with this configuration.
This is a very good interview question. Sometimes they might even ask you what is the difference between a final object and immutable object.
1) When someone mentions a final object, it means that the reference cannot be changed, but its state(instance variables) can be changed.
2) An immutable object is one whose state can not be changed, but its reference can be changed. Ex:
String x = new String("abc");
x = "BCG";
ref variable x can be changed to point a different string, but value of "abc" cannot be changed.
3) Instance variables(non static fields) are initialized when a constructor is called. So you can initialize values to you variables inside a constructor.
4) "But i see that you can change the value in the constructor/methods of the class". -- You cannot change it inside a method.
5) A static variable is initialized during class loading. So you cannot initialize inside a constructor, it has to be done even before it. So you need to assign values to a static variable during declaration itself.
One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available!
So android:screenOrientation="landscape"
will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:
android:screenOrientation="sensorLandscape"
Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow()
use this:
img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
The easy way is to annotate your getters and setters.
Here is the original example modified to exclude the plain text password, but then annotate a new method that just returns the password field as encrypted text.
class User {
private String password;
public void setPassword(String password) {
this.password = password;
}
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty("password")
public String getEncryptedPassword() {
// encryption logic
}
}
No rebuild or reinstall needed for my issue, and in my case the error appeared when trying to run the app on the iPhone. Simulator worked fine.
Solution: Delete app off phone, do a cold restart of phone and now all is well.
Whow are there lots of ways to get this error!.
I will add another given none of the others either applied or were the cause.
I forgot the 'public' in the declaration of my activity class! It was package private.
I had been writing so much Bluetooth code that habit caused me to create an activity class that was package private.
Says something about the obscurity of this error message.
It's a nightmare since each browser/device handles it differently.
Favicon generator helps me a lot for those applications where we need to cover the most possible scenarios.
https://realfavicongenerator.net/
You just need a png image 260px x 260px (at least) and from there the generator will create all references you need within your web page.
You just need to add this references and images to your application.
The exec
built-in command mirrors functions in the kernel, there are a family of them based on execve
, which is usually called from C.
exec
replaces the current program in the current process, without fork
ing a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;
We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile
, the last statement says something like:
exec appln-program
so now there is no shell to go back to. Even if appln-program
crashes, the end-user cannot get to a shell, because it is not there - the exec
replaced it.
We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh
, and everyone just put into their .login
(csh start-up file) a call to ksh
. While that worked, it left a stray csh
process running, and the logout was two stage which could get confusing. So we changed it to exec ksh
which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh
is not a login-shell).
Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4
etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.
You have obviously seen exec
used somewhere, perhaps if you showed the code that's bugging you we could justify its use.
Edit: I realised that my answer above is incomplete. There are two uses of exec
in shells like ksh
and bash
- used for opening file descriptors. Here are some examples:
exec 3< thisfile # open "thisfile" for reading on file descriptor 3
exec 4> thatfile # open "thatfile" for writing on file descriptor 4
exec 8<> tother # open "tother" for reading and writing on fd 8
exec 6>> other # open "other" for appending on file descriptor 6
exec 5<&0 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4 # copy write file descriptor 4 onto 7
exec 3<&- # close the read file descriptor 3
exec 6>&- # close the write file descriptor 6
Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec
reverts to the original meaning:
exec 3 < thisfile # oops, overwrite the current program with command "3"
There are several ways you can use these, on ksh use read -u
or print -u
, on bash
, for example:
read <&3
echo stuff >&4
TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);
I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.
Might be a little too late to the party, but hope this helps someone with similar issue.
The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.
Let me illustrate with an example.
This line means Laravel is generating a new Book instance, as specified in your model. The new Book
object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.
$book = new Book();
Now the following lines are setting up the values of each property of the Book
object. Same still, nothing is written on the database yet.
$book->author = 'Test'
$book->title = 'Test'
This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).
$book->save();
And thus, the default value will not pop up before you save it to the database.
But, that is not enough. If you try to access $book->price
, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.
So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the
Book::find($book->id);
Or, a more sophisticated way by refreshing the instance
$book->refresh();
And then, the next time you try to access the object, it will be filled with the default values.
The dot operator .
does not need to be escaped inside of a character class []
.
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
I found this very useful: create as many threads as cores and let them execute a (large) number of tasks (in this case, calling a shell program):
import Queue
import threading
import multiprocessing
import subprocess
q = Queue.Queue()
for i in range(30): # Put 30 tasks in the queue
q.put(i)
def worker():
while True:
item = q.get()
# Execute a task: call a shell program and wait until it completes
subprocess.call("echo " + str(item), shell=True)
q.task_done()
cpus = multiprocessing.cpu_count() # Detect number of cores
print("Creating %d threads" % cpus)
for i in range(cpus):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
q.join() # Block until all tasks are done
The two queries may not be semantically equivalent. If a employee works for more than one department (possible in the enterprise I work for; admittedly, this would imply your table is not fully normalized) then the first query would return duplicate rows whereas the second query would not. To make the queries equivalent in this case, the DISTINCT
keyword would have to be added to the SELECT
clause, which may have an impact on performance.
Note there is a design rule of thumb that states a table should model an entity/class or a relationship between entities/classes but not both. Therefore, I suggest you create a third table, say OrgChart
, to model the relationship between employees and departments.
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
MyMethod();
}, null, startTimeSpan, periodTimeSpan);
I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.
Give "write" permission to the directory you need to put the file. In your case it is the current directory.
Use "chmod" in linux.
Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.
It's been covered above; however, you can't use string
in reflection; you must use String
.
I believe the problem is that codecs.BOM_UTF8
is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"
Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:
import codecs
file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()
(That seems to give the right answer - a file with bytes EF BB BF.)
EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
Do that:
s = 'hello ' + my_name + ', how are you doing'
With ES6, you could also do this:
s = `hello ${my_name}, how are you doing`
Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.
Sometimes a prototype in some place add an extra element.
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
It may be time consuming to get all the application Ids from YARN and kill them one by one. You can use a Bash for loop to accomplish this repetitive task quickly and more efficiently as shown below:
Kill all applications on YARN which are in ACCEPTED state:
for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Kill all applications on YARN which are in RUNNING state:
for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
I had a horrible problem with this so I finally resorted to using LINQ to order the DataTable before assigning it to the view:
Dim lquery = From s In listToMap
Select s
Order By s.ACCT_Active Descending, s.ACCT_Name
In particular I really found the DataView.Sort and DataGrid.Sort methods unreliable when sorting a boolean field.
I hope this helps someone out there.
Every solution's are not working in my system.
I can get using
#include <time.h>
double difftime(time_t time1, time_t time0);
You can use print like the printf function in C.
e.g.
print "%s%s" % (x, y)
As per RFC2368 which defines mailto:
, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A
.
This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..
I found this solution very helpful in a clean way to remove xml configuration entirely.
Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/
By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.
select person, language
from table A
group by person, language
will return unique rows
See https://github.com/gaarf/XML-string-to-PHP-array/blob/master/xmlstr_to_array.php
<?php
/**
* convert xml string to php array - useful to get a serializable value
*
* @param string $xmlstr
* @return array
*
* @author Adrien aka Gaarf & contributors
* @see http://gaarf.info/2009/08/13/xml-string-to-php-array/
*/
function xmlstr_to_array($xmlstr) {
$doc = new DOMDocument();
$doc->loadXML($xmlstr);
$root = $doc->documentElement;
$output = domnode_to_array($root);
$output['@root'] = $root->tagName;
return $output;
}
function domnode_to_array($node) {
$output = array();
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
$child = $node->childNodes->item($i);
$v = domnode_to_array($child);
if(isset($child->tagName)) {
$t = $child->tagName;
if(!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
}
elseif($v || $v === '0') {
$output = (string) $v;
}
}
if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
$output = array('@content'=>$output); //Change output into an array.
}
if(is_array($output)) {
if($node->attributes->length) {
$a = array();
foreach($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
$output['@attributes'] = $a;
}
foreach ($output as $t => $v) {
if(is_array($v) && count($v)==1 && $t!='@attributes') {
$output[$t] = $v[0];
}
}
}
break;
}
return $output;
}
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
Here is all you need:
curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers
Use this line to get the division behavior you want:
from __future__ import division
Alternatively, you could use modulus:
if (a % b) == 0: #do something
There must be also an answer for people who want a hassle free https on ec2 for mainly demo and testing purposes, one way they can achieve that very fast is:
With my answer here which describes How you can achieve https for testing purposes in minutes with EC2 without the hassle of creating certificates
With gawk, you can use the match
function to capture parenthesized groups.
gawk 'match($0, pattern, ary) {print ary[1]}'
example:
echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}'
outputs cd
.
Note the specific use of gawk which implements the feature in question.
For a portable alternative you can achieve similar results with match()
and substr
.
example:
echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'
outputs cd
.
The above answers no longer work with ES 6.2.2 because of Strict Content-Type Checking for Elasticsearch REST Requests. The curl
command which I ended up using is this:
curl -H'Content-Type: application/json' -XPOST 'localhost:9200/yourindex/_doc/_delete_by_query?conflicts=proceed' -d' { "query": { "match_all": {} }}'
Further to Ryan's answer you will also need to set the DataColumn
's Ordinal
property if you are dealing with a table-valued parameter
with multiple columns whose ordinals are not in alphabetical order.
As an example, if you have the following table value that is used as a parameter in SQL:
CREATE TYPE NodeFilter AS TABLE (
ID int not null
Code nvarchar(10) not null,
);
You would need to order your columns as such in C#:
table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals
If you fail to do this you will get a parse error, failed to convert nvarchar to int.
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
We can create a tag for some past commit:
git tag [tag_name] [reference_of_commit]
eg:
git tag v1.0 5fcdb03
You could do something like this
class ExampleClass:
def __init__(self, **kwargs):
arguments = {'val':1, 'val2':2}
arguments.update(kwargs)
self.val = arguments['val']
self.val2 = arguments['val2']
I had something totally different than the other answers.
I ran tools/android.bat
and got
java.lang.NullPointerException
at java.io.File.<init>(File.java:251)
at com.android.sdklib.internal.avd.AvdManager.parseAvdInfo(AvdManager.java:1623)
at com.android.sdklib.internal.avd.AvdManager.buildAvdList(AvdManager.java:1584)
at com.android.sdklib.internal.avd.AvdManager.<init>(AvdManager.java:357)
at com.android.sdklib.internal.avd.AvdManager.getInstance(AvdManager.java:380)
at com.android.sdklib.internal.repository.updater.UpdaterData.initSdk(UpdaterData.java:259)
at com.android.sdklib.internal.repository.updater.UpdaterData.<init>(UpdaterData.java:127)
at com.android.sdkuilib.internal.repository.SwtUpdaterData.<init>(SwtUpdaterData.java:61)
at com.android.sdkuilib.internal.repository.ui.SdkUpdaterWindowImpl2.<init>(SdkUpdaterWindowImpl2.java:104)
at com.android.sdkuilib.repository.SdkUpdaterWindow.<init>(SdkUpdaterWindow.java:88)
at com.android.sdkmanager.Main.showSdkManagerWindow(Main.java:408)
at com.android.sdkmanager.Main.doAction(Main.java:391)
at com.android.sdkmanager.Main.run(Main.java:151)
at com.android.sdkmanager.Main.main(Main.java:117)
Basically it looked like I had a corrupt AVD configuration, so I went and cleared out my virtual devices and everything started working again! (Files in C:\Users\YourUser\.android\avd
for windows users)
Is it possible to list all of the possible goals (including, say, all the plugins) that it is possible to run?
Maven doesn't have anything built-in for that, although the list of phases is finite (the list of plugin goals isn't since the list of plugins isn't).
But you can make things easier and leverage the power of bash completion (using cygwin if you're under Windows) as described in the Guide to Maven 2.x auto completion using BASH (but before to choose the script from this guide, read further).
To get things working, first follow this guide to setup bash completion on your computer. Then, it's time to get a script for Maven2 and:
maven
in Ubuntu) that you can download from the HEAD. It's simply the best one.Below, here is what I get just to illustrate the result:
$ mvn [tab][tab] Display all 377 possibilities? (y or n) ant:ant ant:clean ant:help antrun:help antrun:run archetype:crawl archetype:create archetype:create-from-project archetype:generate archetype:help assembly:assembly assembly:directory assembly:directory-single assembly:help assembly:single ...
Of course, I never browse the 377 possibilities, I use completion. But this gives you an idea about the size of "a" list :)
Since 1.25.4, docker-compose supports the option --env-file
that enables you to specify a file containing variables.
Yours should look like this:
hostname=my-host-name
And the command:
docker-compose --env-file /path/to/my-env-file config
jar -xvf
to extract the files to a directory.jar -cvf
to create a new jar file.Before writing below queries first get into your cmd or PowerShell
TYPE:
mongo //To get into MongoDB shell
use <Your_dbName> //For Creating or making use of existing db
To List All Collection Names use any one from below options :-
show collections //output every collection
OR
show tables
OR
db.getCollectionNames() //shows all collections as a list
To show all collections content or data use below listed code which had been posted by Bruno_Ferreira.
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {
print('Collection: ' + collections[i]); // print the name of each collection
db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}
Depends on where the file you are trying to include from is located.
Example:
/rootdir/pages/file.php
/someotherDir/index.php
If you wrote the following in index.php:
include('/rootdir/pages/file.php');
it would error becuase it would try to get:
/someotherDir/rootdir/pages/file.php
Which of course doesn't exist...
So you would have to use include('../rootdir/pages/file.php');
Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):
$ sudo -upostgres psql postgres
postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE';
postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run:
$ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf
$ sudo service postgresql reload
There is a simple solution. If you use PDO connect to your DB like this:
try {
$handler = new PDO('mysql:host=localhost;dbname=name_of_your_db', 'your_login', 'your_password');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo $e->getMessage();
}
Then, the query to DB will be:
$query = $handler->query("SELECT id FROM your_table WHERE ...");
And finally, to count the rows matching your query write like this
$amountOfRows = $query->rowcount();
The major part is correctly answered by Thorbjørn Ravn Andersen.
This answer tries to shed light on the remaining question: how could the class file with errors end up in the jar?
Each build (mvn&javac or eclipse) signals in its specific way when it hits a compile error, and will refuse to create a Jar file from it (or at least prominently alert you). The most likely cause for silently getting class files with errors into a jar is by concurrent operation of Maven and Eclipse.
If you have Eclipse open while running a mvn build, you should disable Project > Build Automatically until mvn completes.
EDIT: Let's try to split the riddle into three parts:
(1) What is the meaning of "java.lang.Error: Unresolved compilation problem"
This has been explained by Thorbjørn Ravn Andersen. There is no doubt that Eclipse found an error at compile time.
(2) How can an eclipse-compiled class file end up in jar file created by maven (assuming maven is not configured to used ecj for compilation)?
This could happen either by invoking maven with no or incomplete cleaning. Or, an automatic Eclipse build could react to changes in the filesystem (done by maven) and re-compile a class, before maven proceeds to collect class files into the jar (this is what I meant by "concurrent operation" in my original answer).
(3) How come there is a compile error, but
mvn clean
succeeds?
Again several possibilities: (a) compilers don't agree whether or not the source code is legal, or (b) Eclipse compiles with broken settings like incomplete classpath, wrong Java compliance etc. Either way a sequence of refresh and clean build in Eclipse should surface the problem.
"NgModel doesn't work with new forms api".
That's not true. You just need to use it correctly. If you are using the reactive forms, the NgModel should be used in concert with the reactive directive. See the example in the source.
/*
* @Component({
* selector: "login-comp",
* directives: [REACTIVE_FORM_DIRECTIVES],
* template: `
* <form [formGroup]="myForm" (submit)='onLogIn()'>
* Login <input type='text' formControlName='login' [(ngModel)]="credentials.login">
* Password <input type='password' formControlName='password'
* [(ngModel)]="credentials.password">
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* credentials: {login:string, password:string};
* myForm = new FormGroup({
* login: new Control(this.credentials.login),
* password: new Control(this.credentials.password)
* });
*
* onLogIn(): void {
* // this.credentials.login === "some login"
* // this.credentials.password === "some password"
* }
* }
*/
Though it looks like from the TODO comments, this will likely be removed and replaced with a reactive API.
// TODO(kara): Replace ngModel with reactive API
@Input('ngModel') model: any;
Bootstrap version 3 has a .text-center class.
Just add this class:
text-center
It will simply load this style:
.text-center {
text-align: center;
}
Example:
<div class="container-fluid">
<div class="row text-center">
<div class="col-md-12">
Bootstrap 4 is coming....
</div>
</div>
</div>
One option is:
Object.keys(myObject).length
Sadly it not works under older IE versions (under 9).
If you need that compatibility, use the painful version:
var key, count = 0;
for(key in myObject) {
if(myObject.hasOwnProperty(key)) {
count++;
}
}
I would use the SYLK file format if performing diffs is important. It is a text-based format, which should make the comparisons easier and more compact than a binary format. It is compatible with Excel, Gnumeric, and OpenOffice.org as well, so all three tools should be able to work well together. SYLK Wikipedia Article
I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:
It's a real short VB.Net app: I can post code if any one is interested.
Basically it's a script that is launched before unversioned property is modified on the repository, so that you can manage more precisely what's happening on your repository.
There are templates in the SVN distrib for different hooks, located in the /hooks subdirectory (*.tmpl that you have to edit and rename depending on your OS, to activate).
To avoid adding extra div
s when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.
$('a.ajax').live('click', function() {
var url = this.href;
var dialog = $("#dialog");
if ($("#dialog").length == 0) {
dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
}
// load remote content
dialog.load(
url,
{},
function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser to follow the link
return false;
});`
directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button. instead of looping thru radio buttons to see which one is checked, i prefer to call an onclick
javascript function that sets a variable that can later be retrieved at will.
<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >
which calls:
var currentValue = 0;
function handleClick(myRadio) {
currentValue = myRadio.value;
document.getElementById("buttonSubmit").disabled = false;
}
additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).
For versions prior to 3.0 honeycomb: Yes, do call System.gc()
.
I tried to create Bitmaps, but was always getting "VM out of memory error". But, when I called System.gc()
first, it was OK.
When creating bitmaps, Android often fails with out of memory errors, and does not try to garbage collect first. Hence, call System.gc()
, and you have enough memory to create Bitmaps.
If creating Objects, I think System.gc
will be called automatically if needed,
but not for creating bitmaps. It just fails.
So I recommend manually calling System.gc()
before creating bitmaps.
Try:
from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;
What's the SQL query you want to translate into a Linq query?
If your goal is to put vertical lines in a container to separate side-by-side child elements (column elements), you could consider styling the container like this:
.container > *:not(:first-child) {
border-left: solid gray 2px;
}
This adds a left border to all child elements starting from the 2nd child. In other words, you get vertical borders between adjacent children.
>
is a child selector. It matches any child of the element(s) specified on the left.*
is a universal selector. It matches an element of any type.:not(:first-child)
means it's not the first child of its parent.Browser support: > * :first-child and :not()
I think this is better than a simple .child-except-first {border-left: ...}
rule, because it makes more sense to have the vertical lines come from the container's rules, not the different child elements' rules.
Whether this is better than using a makeshift vertical rule element (by styling a horizontal rule, etc.) will depend on your use case, but this is an alternative at least.
isset()
tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty()
can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
To demonstrate this, try the following code with $the_var unassigned, set to 0, and set to 1.
<?php
#$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
This code works for me:
Sub test()
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
MsgBox NumRows
End Sub
Use this:
"$computer, $Speed, $Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.
Define variable with var
outside the function (and of course before it) and then assign 10
to it inside function:
var value;
$(function() {
value = "10";
});
console.log(value); // 10
Note that you shouldn't omit the first line in this code (var value;
), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;
) and assigning value to a variable (variable = value;
) are two different things. You can't assign value to variable that you haven't defined.
It might be irrelevant here, but $(function() {})
is a shortcut for $(document).ready(function() {})
, which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined
until it has loaded, so console.log(value);
placed right after $(function() {})
will return undefined
. In other words, it would execute in following order:
var value;
console.log(value);
value = "10";
See also:
I've seen your question and answers, and made a new responsive and flexible multi items carousel Gist. you can see it here:
https://gist.github.com/IVIR3zaM/d143a361e61459146ae7c68ce86b066e
I have created simple demo class for your better reference.
FirstActivity.java
public class FirstActivity extends AppCompatActivity {
private static final String TAG = FirstActivity.class.getSimpleName();
private static final int REQUEST_CODE = 101;
private Button btnMoveToNextScreen;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMoveToNextScreen = (Button) findViewById(R.id.btnMoveToNext);
btnMoveToNextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(mIntent, REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE && data !=null) {
String strMessage = data.getStringExtra("keyName");
Log.i(TAG, "onActivityResult: message >>" + strMessage);
}
}
}
}
And here is SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final String TAG = SecondActivity.class.getSimpleName();
private Button btnMoveToPrevious;
private EditText editText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText = (EditText) findViewById(R.id.editText);
btnMoveToPrevious = (Button) findViewById(R.id.btnMoveToPrevious);
btnMoveToPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = editText.getEditableText().toString();
Intent mIntent = new Intent();
mIntent.putExtra("keyName", message);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
}
alias mycommand = 'verylongcommand -with -a -lot -of -parameters'
alias grep='grep --color'
find more than one word with grep :
netstat -c |grep 'msn\|skype\|icq'
Extract Day, Month and Year
The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.
@echo off
::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion
:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do (
:: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"
:: Now assign the date values to the new vars
for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)
:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values --^> Day: %d%, Month:%m%, Year: %y%.
echo.
endlocal
Extract only the Year
For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.
@echo off
setlocal EnableExtensions
for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )
echo And the year is... %_YEAR%.
echo.
endlocal
This is a common but poorly documented Excel COM Error. I've seen it documented as "NAME_NOT_FOUND", meaning that Excel's COM layer is disabled, and can't find the COM property or method name.
I get this error consistently when running the COM code while Excel is 'busy', for example if you set a timer that will start the code, and the code starts running while the user is editing a cell or pressing down their mouse button, then you'll always get this error. This error only happens when the code runs on the main Excel thread, but seems to be the equivalent of error VBA_E_IGNORE = 0x800AC472, which you get when calling the Excel COM object model from another thread, while Excel is 'busy'.
The only workaround seems to be to retry (with some small delay) the COM call until it succeeds - when Excel is no longer 'busy'.
This is the solution that I came up with for this problem which works for me.
library used: momentjs with plain javascript Date class.
Step 1.
Convert String date to moment object (PS: moment retains the original date and time as long as toDate()
method is not called):
const dateMoment = moment("2005-07-08T11:22:33+0000");
Step 2.
Extract hours
and minutes
values from the previously created moment object:
const hours = dateMoment.hours();
const mins = dateMoment.minutes();
Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):
const dateObj = dateMoment.toDate();
Step 4. Manually set the hours and minutes extracted in Step 2.
dateObj.setHours(hours);
dateObj.setMinutes(mins);
Step 5.
dateObj
will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.
Hope this helps.
Simple solution, I've tested is
webBrowser1.Refresh();
var str = "<html><head></head><body>" + sender.ToString() + "</body></html>";
webBrowser1.DocumentText = str;
Expanding a bit on Fredrik's answer, if you want to set the column's auto-resize width on the fly for example: setting the first column's auto-size width to 70:
myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.None);
myListView.Columns[0].Width = 70;
myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
Check the wiki: http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
I get the same error when I run Oracle XE instance on the same machine. As my database is Oracle, I preferred changing Glassfish's default port:
<network-listener port="9090" protocol="http-listener-1" transport="tcp" name="http-listener-1" thread-pool="http-thread-pool"></network-listener>_x000D_
_x000D_
If you're using jQuery, it's as simple as this:
$('#mySelect').change(function()
{
$('#myForm').submit();
});
Just do the following change
echo off
cls
echo Would you like to do a backup?
pause
copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
pause
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
Using AJAX Modal Popup and creating a Message Box Class:
Messsage Box Class:
public class MessageBox
{
ModalPopupExtender _modalPop;
Page _page;
object _sender;
Panel _pnl;
public enum Buttons
{
AbortRetryIgnore,
OK,
OKCancel,
RetryCancel,
YesNo,
YesNoCancel
}
public enum DefaultButton
{
Button1,
Button2,
Button3
}
public enum MessageBoxIcon
{
Asterisk,
Exclamation,
Hand,
Information,
None,
Question,
Warning
}
public MessageBox(Page page, object sender, Panel pnl)
{
_page = page;
_sender = sender;
_pnl = pnl;
_modalPop = new ModalPopupExtender();
_modalPop.ID = "popUp";
_modalPop.PopupControlID = "ModalPanel";
}
public void Show(String strTitle, string strMessage, Buttons buttons, DefaultButton defaultbutton, MessageBoxIcon msbi)
{
MasterPage mPage = _page.Master;
Label lblTitle = null;
Label lblError = null;
Button btn1 = null;
Button btn2 = null;
Button btn3 = null;
Image imgIcon = null;
lblTitle = ((Default)_page.Master).messageBoxTitle;
lblError = ((Default)_page.Master).messageBoxMsg;
btn1 = ((Default)_page.Master).button1;
btn2 = ((Default)_page.Master).button2;
btn3 = ((Default)_page.Master).button3;
imgIcon = ((Default)_page.Master).messageBoxIcon;
lblTitle.Text = strTitle;
lblError.Text = strMessage;
btn1.CssClass = "btn btn-default";
btn2.CssClass = "btn btn-default";
btn3.CssClass = "btn btn-default";
switch (msbi)
{
case MessageBoxIcon.Asterisk:
//imgIcon.ImageUrl = "~/img/asterisk.jpg";
break;
case MessageBoxIcon.Exclamation:
//imgIcon.ImageUrl = "~/img/exclamation.jpg";
break;
case MessageBoxIcon.Hand:
break;
case MessageBoxIcon.Information:
break;
case MessageBoxIcon.None:
break;
case MessageBoxIcon.Question:
break;
case MessageBoxIcon.Warning:
break;
}
switch (buttons)
{
case Buttons.AbortRetryIgnore:
btn1.Text = "Abort";
btn2.Text = "Retry";
btn3.Text = "Ignore";
btn1.Visible = true;
btn2.Visible = true;
btn3.Visible = true;
break;
case Buttons.OK:
btn1.Text = "OK";
btn1.Visible = true;
btn2.Visible = false;
btn3.Visible = false;
break;
case Buttons.OKCancel:
btn1.Text = "OK";
btn2.Text = "Cancel";
btn1.Visible = true;
btn2.Visible = true;
btn3.Visible = false;
break;
case Buttons.RetryCancel:
btn1.Text = "Retry";
btn2.Text = "Cancel";
btn1.Visible = true;
btn2.Visible = true;
btn3.Visible = false;
break;
case Buttons.YesNo:
btn1.Text = "No";
btn2.Text = "Yes";
btn1.Visible = true;
btn2.Visible = true;
btn3.Visible = false;
break;
case Buttons.YesNoCancel:
btn1.Text = "Yes";
btn2.Text = "No";
btn3.Text = "Cancel";
btn1.Visible = true;
btn2.Visible = true;
btn3.Visible = true;
break;
}
if (defaultbutton == DefaultButton.Button1)
{
btn1.CssClass = "btn btn-primary";
btn2.CssClass = "btn btn-default";
btn3.CssClass = "btn btn-default";
}
else if (defaultbutton == DefaultButton.Button2)
{
btn1.CssClass = "btn btn-default";
btn2.CssClass = "btn btn-primary";
btn3.CssClass = "btn btn-default";
}
else if (defaultbutton == DefaultButton.Button3)
{
btn1.CssClass = "btn btn-default";
btn2.CssClass = "btn btn-default";
btn3.CssClass = "btn btn-primary";
}
FirePopUp();
}
private void FirePopUp()
{
_modalPop.TargetControlID = ((Button)_sender).ID;
_modalPop.DropShadow = true;
_modalPop.OkControlID = //btn 1 / 2 / 3;
_modalPop.CancelControlID = //btn 1 / 2 / 3;
_modalPop.BackgroundCssClass = "modalBackground";
_pnl.Controls.Add(_modalPop);
_modalPop.Show();
}
In my MasterPage code:
#region AlertBox
public Button button1
{
get
{ return this.btn1; }
}
public Button button2
{
get
{ return this.btn2; }
}
public Button button3
{
get
{ return this.btn1; }
}
public Label messageBoxTitle
{
get
{ return this.lblMessageBoxTitle; }
}
public Label messageBoxMsg
{
get
{ return this.lblMessage; }
}
public Image messageBoxIcon
{
get
{ return this.img; }
}
public DialogResult res
{
get { return res; }
set { res = value; }
}
#endregion
In my MasterPage aspx:
On the header add reference (just for some style)
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
On the Content:
<asp:Panel ID="ModalPanel" runat="server" style="display: none; position: absolute; top:0;">
<asp:Panel ID="pnlAlertBox" runat="server" >
<div class="modal-dialog" >
<div ID="modalContent" runat="server" class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">
<asp:Label ID="lblMessageBoxTitle" runat="server" Text="This is the MessageBox Caption"></asp:Label>
</h4>
</div>
<div ID="modalbody" class="modal-body" style="width:800px; height:600px">
<asp:Image ID="img" runat="server" Height="20px" Width="20px"/>
<asp:Label ID="lblMessage" runat="server" Text="Here Goes My Message"></asp:Label>
</div>
<div class="modal-footer">
<asp:Button ID="btn1" runat="server" OnClick="btn_Click" CssClass="btn btn-default" Text="Another Button" />
<asp:Button ID="btn2" runat="server" OnClick="btn_Click" CssClass="btn btn-default" Text="Cancel" />
<asp:Button ID="btn3" runat="server" OnClick="btn_Click" CssClass="btn btn-primary" Text="Ok" />
</div>
</div>
</div>
</asp:Panel>
</asp:Panel>
And to call it from a button, button code:
protected void btnTest_Click(object sender, EventArgs e)
{
MessageBox msgBox = new MessageBox(this, sender, aPanel);
msgBox.Show("This is my Caption", "this is my message", MessageBox.Buttons.AbortRetryIgnore, MessageBox.DefaultButton.Button1, MessageBox.MessageBoxIcon.Asterisk);
}
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
What others have forgotten is Ctrl+Shift+L for easy text search. It searches everywhere and it is fast and efficient. This might be a Sprint tool suit which is an extension of eclipse (and it might be available in newer versions)
find . -print0|while read -d $'\0' file; do echo "$file"; done
As @Steven points out, a better way would be:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
As this handles the line separator for you, and handles closing the writer as well
(and doesn't open and close the file each time you write a line, which could be slow in your original version)
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.
In case if you don't have a fixed format for the address as mentioned above, I would use regex expression just to eliminate the symbols which are not used in the address (like specialized sybmols - &(%#$^). Result would be:
[A-Za-z0-9'\.\-\s\,]
If you want that in Angular 2 or Angular 4 and also want to keep inline CSS then you can use
<div [innerHTML]="theHtmlString | keepHtml"></div>
If you only want to upgrade one specific package called somepackage
, the command you should use in recent versions of pip is
pip install --upgrade --upgrade-strategy only-if-needed somepackage
This is very useful when you develop an application in Django that currently will only work with a specific version of Django (say Django=1.9.x) and want to upgrade some dependent package with a bug-fix/new feature and the upgraded package depends on Django (but it works with, say, any version of Django after 1.5).
The default behavior of pip install --upgrade django-some-package
would be to upgrade Django to the latest version available which could otherwise break your application, though with the --upgrade-strategy only-if-needed
dependent packages will now only be upgraded as necessary.
If you are trying to force a floating div to match another to create a column effect, this is what I do. I like it because it's simple and clean.
<div style="background-color: #CCC; width:300px; overflow:hidden; ">
<!-- Padding-Bottom is equal to 100% of the container's size, Margin-bottom hides everything beyond
the container equal to the container size. This allows the column to grow with the largest
column. -->
<div style="float: left;width: 100px; background:yellow; padding-bottom:100%; margin-bottom:-100%;">column a</div>
<div style="float: left;width: 100px; background:#09F;">column b<br />Line 2<br />Line 3<br />Line 4<br />Line 5</div>
<div style="float:left; width:100px; background: yellow; padding-bottom:100%; margin-bottom:-100%;">Column C</div>
<div style="clear: both;"></div>
</div>
I think this makes sense. It seems to work well even with dynamic content.
this is a programatical approach:
view.setVisibility(View.GONE); //For GONE
view.setVisibility(View.INVISIBLE); //For INVISIBLE
view.setVisibility(View.VISIBLE); //For VISIBLE
/**
* Method that checks if all tables exist
* If a table doesnt exist it creates the table
*/
public void checkTables() {
try {
startConn();// method that connects with mysql database
String useDatabase = "USE " + getDatabase() + ";";
stmt.executeUpdate(useDatabase);
String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
DatabaseMetaData metadata = conn.getMetaData();
for(int i=0; i< tables.length; i++) {
ResultSet rs = metadata.getTables(null, null, tables[i], null);
if(!rs.next()) {
createTable(tables[i]);
System.out.println("Table " + tables[i] + " created");
}
}
} catch(SQLException e) {
System.out.println("checkTables() " + e.getMessage());
}
closeConn();// Close connection with mysql database
}
You could extend the Number
object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
I’ve created a new SOAP client for the Android platform, it is use a JAX-WS generated interfaces, but it is only a proof-of-concept yet.
If you are interested, please try the example and/or watch the source: http://wiki.javaforum.hu/display/ANDROIDSOAP/Home
Update: the version 0.0.4 is out with tutorial:
http://wiki.javaforum.hu/display/ANDROIDSOAP/2012/04/16/Version+0.0.4+released
http://wiki.javaforum.hu/display/ANDROIDSOAP/Step+by+step+tutorial
To close the current cmd windows immediately, just add as the last command/line:
move nul 2>&0
Try move nul
to nowhere and redirect the stderr to stdin
will result in the current window cmd.exe being closed
This is different from closing a bat, or exiting it using goto :EOF
or Exit /b
You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:
.col {
padding-right:7px;
padding-left:7px;
}
Demo: http://bootply.com/93473
EDIT If you only want the spacing between columns you can select all cols except first and last like this..
.col:not(:first-child,:last-child) {
padding-right:7px;
padding-left:7px;
}
For Bootstrap 4 see: Remove gutter space for a specific div only
$('.mybtn').on('click',_x000D_
function(){_x000D_
$('#myinput').attr('value', '');_x000D_
}_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="mybtn">CLEAR</button>_x000D_
<input type="text" id="myinput" name="myinput" value="?????????">
_x000D_
On Android 6+ follow this path: Settings -> Google -> Security -> Verify Apps Uncheck them all! Now you're good to GO!!!
Sorry, if this is irelevant, but will return list with matches using FindAll() in case you need this:
private bool IsContain(string cont)
{
List<string> ListToMatch= new List<string>() {"string1","string2"};
if (ListToMatch.ToArray().Any(cont.Contains))
{
return false;
}
else
return true;
}
And usage:
List<string> ListToCheck = new List<string>() {"string1","string2","string3","string4"};
List<string> FinalList = ListToCheck.FindAll(IsContain);
The final list contains only the matched elements string1 and string2 from list to check. Can easy be switched to int List.
foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}
same work you also can do with Contains
secondly Where
is give you new list of values.
thirdly using Exist
is not a good practice, you can achieve your target from Any
and contains
like
EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();
Hope this will clear your confusion.
On iOS 9.2 Profiles
renamed to Device Management
.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.
YES, python have a ternary operator, here is the syntax and an example code to demonstrate the same :)
#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false
a= input("Enter the First Number ")
b= input("Enter the Second Number ")
print("A is Bigger") if a>b else print("B is Bigger")
You can use forEach method to iterate over array of objects.
data.messages.forEach(function(message){
console.log(message)
});
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]
I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.
The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.
Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid
parts.
If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray()
and encode it. You'll need to Array.Reverse
the first three parts (Data1-3).
I do it this way:
var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);
See this answer for the specific .NET implementation details.
Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray()
.
Prior to running python, type cd
in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py
needs to be in this directory, so you can move hello.py
from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py
is.
Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p
In JavaScript, a variable can be defined, but hold the value undefined
, so the most common answer is not technically correct, and instead performs the following:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
This, of course, assumes you are running in a browser (where window
is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window
is stylistically consistent with using window.name
to refer to globals. Accessing globals as properties of window
rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.
This is a solution which uses only sys-tables.
It lists all the primary keys in the database. It returns schema, table name, column name and the correct column sort order for each primary key.
If you want to get the primary key for a specific table, then you need to filter on SchemaName
and TableName
.
IMHO, this solution is very generic and does not use any string literals, so it will run on any machine.
select
s.name as SchemaName,
t.name as TableName,
tc.name as ColumnName,
ic.key_ordinal as KeyOrderNr
from
sys.schemas s
inner join sys.tables t on s.schema_id=t.schema_id
inner join sys.indexes i on t.object_id=i.object_id
inner join sys.index_columns ic on i.object_id=ic.object_id
and i.index_id=ic.index_id
inner join sys.columns tc on ic.object_id=tc.object_id
and ic.column_id=tc.column_id
where i.is_primary_key=1
order by t.name, ic.key_ordinal ;
Your else statement should look like this (note the ^
):
{{^avatar}}
...
{{/avatar}}
In mustache this is called 'Inverted sections'.
To position block elements to the center (works in IE9 and above), needs a wrapper div
:
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
In Eclipse, go to Build Path, click "Add Library", select JRE System Library, click "Next", select option "Workspace default JRE(i)", and click "Finish".
This worked for me.
In the service.ts file -
a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
@Injectable()
export class ClientListService {
private clientList;
constructor() {
this.clientList = [
{name: 'abc', address: 'Railpar'},
{name: 'def', address: 'Railpar 2'},
{name: 'ghi', address: 'Panagarh'},
{name: 'jkl', address: 'Panagarh 2'},
];
}
getClientList () {
return Observable.of(this.clientList);
}
};
In the component where we are calling the get function of the service -
this.clientListService.getClientList().subscribe(res => this.clientList = res);
NOTE: onKeyListener
doesn't work for soft keyboards.
You can set OnKeyListener
for you editText
so you can detect any key press
EDIT: A common mistake we are checking KeyEvent.KEYCODE_BACK
for backspace
, but really it is KeyEvent.KEYCODE_DEL
(Really that name is very confusing! )
editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
if(keyCode == KeyEvent.KEYCODE_DEL) {
//this is for backspace
}
return false;
}
});
I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds()
at the wrong time may leave you with a result like in the Q.
The best way I found is to place the call in an idle handler like this:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds(markerBounds);
});
Additionally, you can use Google CityHash:
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <byteswap.h>
#include "city.h"
void swap(uint32* a, uint32* b) {
int temp = *a;
*a = *b;
*b = temp;
}
#define PERMUTE3(a, b, c) swap(&a, &b); swap(&a, &c);
// Magic numbers for 32-bit hashing. Copied from Murmur3.
static const uint32 c1 = 0xcc9e2d51;
static const uint32 c2 = 0x1b873593;
static uint32 UNALIGNED_LOAD32(const char *p) {
uint32 result;
memcpy(&result, p, sizeof(result));
return result;
}
static uint32 Fetch32(const char *p) {
return UNALIGNED_LOAD32(p);
}
// A 32-bit to 32-bit integer hash copied from Murmur3.
static uint32 fmix(uint32 h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
static uint32 Rotate32(uint32 val, int shift) {
// Avoid shifting by 32: doing so yields an undefined result.
return shift == 0 ? val : ((val >> shift) | (val << (32 - shift)));
}
static uint32 Mur(uint32 a, uint32 h) {
// Helper from Murmur3 for combining two 32-bit values.
a *= c1;
a = Rotate32(a, 17);
a *= c2;
h ^= a;
h = Rotate32(h, 19);
return h * 5 + 0xe6546b64;
}
static uint32 Hash32Len13to24(const char *s, size_t len) {
uint32 a = Fetch32(s - 4 + (len >> 1));
uint32 b = Fetch32(s + 4);
uint32 c = Fetch32(s + len - 8);
uint32 d = Fetch32(s + (len >> 1));
uint32 e = Fetch32(s);
uint32 f = Fetch32(s + len - 4);
uint32 h = len;
return fmix(Mur(f, Mur(e, Mur(d, Mur(c, Mur(b, Mur(a, h)))))));
}
static uint32 Hash32Len0to4(const char *s, size_t len) {
uint32 b = 0;
uint32 c = 9;
for (size_t i = 0; i < len; i++) {
signed char v = s[i];
b = b * c1 + v;
c ^= b;
}
return fmix(Mur(b, Mur(len, c)));
}
static uint32 Hash32Len5to12(const char *s, size_t len) {
uint32 a = len, b = len * 5, c = 9, d = b;
a += Fetch32(s);
b += Fetch32(s + len - 4);
c += Fetch32(s + ((len >> 1) & 4));
return fmix(Mur(c, Mur(b, Mur(a, d))));
}
uint32 CityHash32(const char *s, size_t len) {
if (len <= 24) {
return len <= 12 ?
(len <= 4 ? Hash32Len0to4(s, len) : Hash32Len5to12(s, len)) :
Hash32Len13to24(s, len);
}
// len > 24
uint32 h = len, g = c1 * len, f = g;
uint32 a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2;
uint32 a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2;
uint32 a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2;
uint32 a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2;
uint32 a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2;
h ^= a0;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
h ^= a2;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a1;
g = Rotate32(g, 19);
g = g * 5 + 0xe6546b64;
g ^= a3;
g = Rotate32(g, 19);
g = g * 5 + 0xe6546b64;
f += a4;
f = Rotate32(f, 19);
f = f * 5 + 0xe6546b64;
size_t iters = (len - 1) / 20;
do {
uint32 a0 = Rotate32(Fetch32(s) * c1, 17) * c2;
uint32 a1 = Fetch32(s + 4);
uint32 a2 = Rotate32(Fetch32(s + 8) * c1, 17) * c2;
uint32 a3 = Rotate32(Fetch32(s + 12) * c1, 17) * c2;
uint32 a4 = Fetch32(s + 16);
h ^= a0;
h = Rotate32(h, 18);
h = h * 5 + 0xe6546b64;
f += a1;
f = Rotate32(f, 19);
f = f * c1;
g += a2;
g = Rotate32(g, 18);
g = g * 5 + 0xe6546b64;
h ^= a3 + a1;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a4;
g = bswap_32(g) * 5;
h += a4 * 5;
h = bswap_32(h);
f += a0;
PERMUTE3(f, h, g);
s += 20;
} while (--iters != 0);
g = Rotate32(g, 11) * c1;
g = Rotate32(g, 17) * c1;
f = Rotate32(f, 11) * c1;
f = Rotate32(f, 17) * c1;
h = Rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = Rotate32(h, 17) * c1;
h = Rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = Rotate32(h, 17) * c1;
return h;
}
next((x for x in test_list if x.value == value), None)
This gets the first item from the list that matches the condition, and returns None
if no item matches. It's my preferred single-expression form.
However,
for x in test_list:
if x.value == value:
print("i found it!")
break
The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:
for x in test_list:
if x.value == value:
print("i found it!")
break
else:
x = None
This will assign None
to x
if you don't break
out of the loop.
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt","someotherfile.txt"
)
) ELSE (
CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF
Is this feasible?
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
SET var="somefile.txt"
IF EXIST "someotherfile.txt" (
SET var=!var!,"someotherfile.txt"
)
) ELSE (
IF EXIST "someotherfile.txt" (
SET var="someotherfile.txt"
) ELSE (
GOTO:EOF
)
)
This is fairly easy to answer from the internet. Set system properties http.proxyHost
and http.proxyPort
. You can do this with System.setProperty()
, or from the command line with the -D
syntax.
Instead of giving access to all IIS users like IIS_IUSRS
you can also give access only to the Application Pool Identity using the site. This is the recommended approach by Microsoft and more information can be found here:
https://support.microsoft.com/en-za/help/4466942/understanding-identities-in-iis
https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities
Fix:
Start by looking at Config File parameter above to determine the location that needs access. The entire publish
folder in this case needs access. Right click on the folder and select properties and then the Security tab.
Click on Edit...
and then Add...
.
Now look at Internet Information Services (IIS) Manager and Application Pools:
In my case my site runs under LocalTest Application Pool and then I enter the name IIS AppPool\LocalTest
Press Check Names
and the user should be found.
Give the user the needed access (Default: Read & Execute, List folder contents and Read) and everything should work.
One case where you can be unable to debug an application in Android Studio is when you have the "release" build variant selected. Happened to me - Gradle builds a release version of the app (which is not debuggable) and then Android Studio fails at trying to connect the debugger.
One other significant point if you're using C# 6:
'=>' can be used instead of 'get' and is only for 'get only' methods - it can't be used with a 'set'.
For C# 7, see the comment from @avenmore below - it can now be used in more places. Here's a good reference - https://csharp.christiannagel.com/2017/01/25/expressionbodiedmembers/
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);
A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.
You can modify cookies using document.cookie
.
You can easily find many examples how to modify cookies.
If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://stackoverflow.com/a/16231859/910764.
JavaScript
angular.module('myApp').directive('bsNavbar', ['$location', function ($location) {
return {
restrict: 'A',
link: function postLink(scope, element) {
scope.$watch(function () {
return $location.path();
}, function (path) {
angular.forEach(element.children(), (function (li) {
var $li = angular.element(li),
regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
isActive = regex.test(path);
$li.toggleClass('active', isActive);
}));
});
}
};
}]);
HTML
<ul class="nav navbar-nav" bs-navbar>
<li data-match-route="/home"><a href="#/home">Home</a></li>
<li data-match-route="/about"><a href="#/about">About</a></li>
</ul>
Note: The above HTML classes assume you are using Bootstrap 3.x
Use data option of ajax. You can send data object to server by data
option in ajax and the type
which defines how you are sending it (either POST
or GET
). The default type is GET
method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
LOAD DATA INFILE 'file.csv'
INTO TABLE t1
(column1, @dummy, column2, @dummy, column3, ...)
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';
Just replace the column1, column2, etc.. with your column names, and put @dummy anwhere there's a column in the CSV you want to ignore.
Full details here.
Here is one-line list-comprehension variant of Pat's answer (which also includes that you wanted to glob in a specific project directory):
import os, glob
exts = ['*.txt', '*.mdown', '*.markdown']
files = [f for ext in exts for f in glob.glob(os.path.join(project_dir, ext))]
You loop over the extensions (for ext in exts
), and then for each extension you take each file matching the glob pattern (for f in glob.glob(os.path.join(project_dir, ext)
).
This solution is short, and without any unnecessary for-loops, nested list-comprehensions, or functions to clutter the code. Just pure, expressive, pythonic Zen.
This solution allows you to have a custom list of exts
that can be changed without having to update your code. (This is always a good practice!)
The list-comprehension is the same used in Laurent's solution (which I've voted for). But I would argue that it is usually unnecessary to factor out a single line to a separate function, which is why I'm providing this as an alternative solution.
Bonus:
If you need to search not just a single directory, but also all sub-directories, you can pass recursive=True
and use the multi-directory glob symbol **
1:
files = [f for ext in exts
for f in glob.glob(os.path.join(project_dir, '**', ext), recursive=True)]
This will invoke glob.glob('<project_dir>/**/*.txt', recursive=True)
and so on for each extension.
1 Technically, the **
glob symbol simply matches one or more characters including forward-slash /
(unlike the singular *
glob symbol). In practice, you just need to remember that as long as you surround **
with forward slashes (path separators), it matches zero or more directories.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
Yes VBA is the way to go.
But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.
Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.
This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.
I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowException
s. For instance, if I had these objects
public class A{
Long id;
String name;
List<B> children;
}
public class B{
Long id;
A parent;
}
I would want to programmatically ignore the parent
field in B if I were looking at A, and ignore the children
field in A if I were looking at B.
I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.
It allows you programmatically specify what fields to ignore:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(B.class, match()
.exclude("parent")));
It also lets you easily specify very simplified views through wildcard matchers:
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(A.class, match()
.exclude("*")
.include("id", "name")));
In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.
All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:
@Controller
public class JsonController {
private JsonResult json = JsonResult.instance();
@Autowired
private TestObjectService service;
@RequestMapping(method = RequestMethod.GET, value = "/bean")
@ResponseBody
public List<TestObject> getTestObject() {
List<TestObject> list = service.list();
return json.use(JsonView.with(list)
.onClass(TestObject.class, Match.match()
.exclude("int1")
.include("ignoredDirect")))
.returnValue();
}
}
Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.
If you want to keep order of the original list, just use OrderedDict with None
as values.
In Python2:
from collections import OrderedDict
from itertools import izip, repeat
unique_list = list(OrderedDict(izip(my_list, repeat(None))))
In Python3 it's even simpler:
from collections import OrderedDict
from itertools import repeat
unique_list = list(OrderedDict(zip(my_list, repeat(None))))
If you don't like iterators (zip and repeat) you can use a generator (works both in 2 & 3):
from collections import OrderedDict
unique_list = list(OrderedDict((element, None) for element in my_list))
You can also check this out. If you are using this method, then use the parse function to get values from Mongo Database:
db.getCollection('user').find({
createdOn: {
$gt: ISODate("2020-01-01T00:00:00.000Z"),
$lt: ISODate("2020-03-01T00:00:00.000Z")
}
})
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
You need to append your variables to the echoed string. For example:
echo 'This is a string '.$PHPvariable.' and this is more string';
@mywolfe02 gives a static range code so his inRange works fine but if you want to add dynamic range then use this one with inRange function of him.this works better with when you want to populate data to fix starting cell and last column is also fixed.
Sub DynamicRange()
Dim sht As Worksheet
Dim LastRow As Long
Dim StartCell As Range
Dim rng As Range
Set sht = Worksheets("xyz")
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Set rng = Workbooks("Record.xlsm").Worksheets("xyz").Range(Cells(12, 2), Cells(LastRow, 12))
Debug.Print LastRow
If InRange(ActiveCell, rng) Then
' MsgBox "Active Cell In Range!"
Else
MsgBox "Please select the cell within the range!"
End If
End Sub
Hope this help
private bool isDate(Range cell)
{
if (cell.NumberFormat.ToString().Contains("/yy"))
{
return true;
}
return false;
}
isDate(worksheet.Cells[irow, icol])
This is the way I solved my problem:
Pull
from master.UPDATE:
As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.
You can also create a varible and then assign it for a text. It is cool because you can assign it two or more texts.
To assign a variable do that
public partial class Sayfa1 : Form
Font Normal = new Font("Segoe UI", 9, FontStyle.Bold);
public Sayfa1()
This varible is not assigned to any text yet.To do it write the name of the text(Look proporties -> (Name)) then write ".Font" then call the name of your font variable.
lupusToolStripMenuItem.Font = Normal;
Now you have a text assigned to a Normal font. I hope I could be helpful.
If you want result to be stored in another dataset:
df.drop_duplicates(keep=False)
or
df.drop_duplicates(keep=False, inplace=False)
If same dataset needs to be updated:
df.drop_duplicates(keep=False, inplace=True)
Above examples will remove all duplicates and keep one, similar to DISTINCT *
in SQL
In Xcode > 4.3:
You click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column.
Good Luck !!!
There is no native solution that I'm aware of. Dojo has a built-in unserialization method if you use that framework by chance.
Otherwise you can implement it yourself rather simply:
function unserialize(str) {
str = decodeURIComponent(str);
var chunks = str.split('&'),
obj = {};
for(var c=0; c < chunks.length; c++) {
var split = chunks[c].split('=', 2);
obj[split[0]] = split[1];
}
return obj;
}
edit: added decodeURIComponent()
Use smem, which is an alternative to ps which calculates the USS and PSS per process. You probably want the PSS.
USS - Unique Set Size. This is the amount of unshared memory unique to that process (think of it as U for unique memory). It does not include shared memory. Thus this will under-report the amount of memory a process uses, but it is helpful when you want to ignore shared memory.
PSS - Proportional Set Size. This is what you want. It adds together the unique memory (USS), along with a proportion of its shared memory divided by the number of processes sharing that memory. Thus it will give you an accurate representation of how much actual physical memory is being used per process - with shared memory truly represented as shared. Think of the P being for physical memory.
How this compares to RSS as reported by ps and other utilities:
Notice: smem can also (optionally) output graphs such as pie charts and the like. IMO you don't need any of that. If you just want to use it from the command line like you might use ps -A v
, then you don't need to install the Python and Matplotlib recommended dependency.
I had this issue after upgrading the Git client, and suddenly my repository could not push.
I found that some old remote had the wrong value of url
, even through my currently active remote had the same value for url
and was working fine.
But there was also the pushurl
param, so adding it for the old remote worked for me:
Before:
[remote "origin"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
pushurl = [email protected]:user/repo.git
NOTE: This part of file "config" was unused for ages, but the new client complained about the wrong URL:
[remote "composer"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/composer/*
So I added the pushurl
param to the old remote:
[remote "composer"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/composer/*
pushurl = [email protected]:user/repo.git
Raw t-sql is limited to CHARINDEX(), PATINDEX(), REPLACE(), and SUBSTRING() for string manipulation. But with sql server 2005 and later you can set up user defined functions that run in .Net, which means setting up a string.format() UDF shouldn't be too tough.
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
When you say visualize the database schema, are you referring to a text-document of all your tables, sprocs, etc., or are you referring to a visual representation of your schema and dependencies?
I know you mentioned MySQL (and it is very possible that it is supported now, but I am not sure), but RedGate has a number of tools that make that pretty simple. It's SQL Doc program can take your entire database and create full-blown database documentation for it. SQL Dependency Tracker can give you a visual representation of all your tables and show their linkings, or you can load in just certain tables or sprocs to show what is using them or what they are using themselves.
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}?
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
A somewhat belated update, to use addEventListener()
(as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
Because the event-handling is attached to the body
element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction
) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName
of a
, the click-handling is passed to the reallySure()
function.
References:
Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:
Properties
.C/C++
folder.Precompiled Headers
node.Create/Use Precompiled Header
, and then click Not Using Precompiled Headers
.Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.
module.exports = Component
should become export default Component
.
CommonJS uses module.exports
as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports
, exoprts
or exprots
). There are no runtime or compile-time checks to tell you that you've messed up.
If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component
then it will give you a compile error to let you know.
In your case, you can simplify the Speaker component.
import React from 'react';
export default React.createClass({
render() {
return (
<h1>Speaker</h1>
)
}
});
Actually I merged all your answers to my own solution how to solve the above problem:
The result is like that:
msbuild /t:restore /t:build /p:WebPublishMethod=FileSystem /p:publishUrl=C:\builds\MyProject\ /p:DeleteExistingFiles=True /p:LastUsedPlatform="Any CPU" /p:Configuration=Release
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.
The solution was to start the main text elements with an opacity of 0 and use addClass
to inject and transition to an opacity of 1. Then removeClass
when clicked on again.
I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)
So in it's most basic form...
.slideDown().addClass("load");
.slideUp().removeClass("load");
Thanks for the help everyone.
Enter in sqlplus (you'll see the version number)
# su - oracle
oracle# sqlplus
OR
echo $ORAHOME
Will give you the path where Oracle installed and path will include version number.
OR
Connect to Oracle DB and run
select * from v$version where banner like 'oracle%';
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
I know that people will probably find this very obvious at first, but really think about this. This can often happen if you've done something wrong.
For instance, I've had this problem because I didn't add a host entry to my hosts file. The real problem was DNS resolution. Or I just got the base URL wrong.
Sometimes I get this error if the identity token came from one server, but I'm trying to use it on another.
Sometimes you'll get this error if you've got the resource wrong.
You might get this if you put the CORS middleware too late in the chain.
The simplest approach would be to use LINQ:
var count = text.TakeWhile(c => c == '$').Count();
There are certainly more efficient approaches, but that's probably the simplest.
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Just want to add Matas' answer. Maybe it's obvious, but I've searched for a long time to figure out that the variable is accessible only inside the BEGIN-END construction, so if you need to use it in some code later, you need to put this code inside the BEGIN-END block.
Note that these blocks can be nested:
DECLARE x NUMBER;
BEGIN
SELECT PK INTO x FROM table1 WHERE col1 = 'test';
DECLARE y NUMBER;
BEGIN
SELECT PK INTO y FROM table2 WHERE col2 = x;
INSERT INTO table2 (col1, col2)
SELECT y,'text'
FROM dual
WHERE exists(SELECT * FROM table2);
COMMIT;
END;
END;
Anyone looking for a quick Vue file component, here you go:
// WindowUrl.vue
<template>
<a :href="url" :class="classes" @click="open">
<slot></slot>
</a>
</template>
<script>
export default {
props: {
url: String,
width: String,
height: String,
classes: String,
},
methods: {
open(e) {
// Prevent the link from opening on the parent page.
e.preventDefault();
window.open(
this.url,
'targetWindow',
`toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
);
}
}
}
</script>
Usage:
<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
Print Shipping Label
</window-url>
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
You should use get_fields()
:
[f.name for f in MyModel._meta.get_fields()]
The get_all_field_names()
method is deprecated starting from Django
1.8 and will be removed in 1.10.
The documentation page linked above provides a fully backwards-compatible implementation of get_all_field_names()
, but for most purposes the previous example should work just fine.
model._meta.get_all_field_names()
That should do the trick.
That requires an actual model instance. If all you have is a subclass of django.db.models.Model
, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()
You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.
For me the problem was a wrong copy/paste of the public key into Gitlab. The copy generated an extra return. Make sure what you paste is a one-line key.
Officially not.
But here's a patch: http://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest
This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.
In curl "url" | grep -qs foo
, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.
A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.
E.g.
curl "url" | tac | tac | grep -qs foo
tac
is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {_x000D_
this.setAttribute(_x000D_
"data-date",_x000D_
moment(this.value, "YYYY-MM-DD")_x000D_
.format( this.getAttribute("data-date-format") )_x000D_
)_x000D_
}).trigger("change")
_x000D_
input {_x000D_
position: relative;_x000D_
width: 150px; height: 20px;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input:before {_x000D_
position: absolute;_x000D_
top: 3px; left: 3px;_x000D_
content: attr(data-date);_x000D_
display: inline-block;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
input::-webkit-calendar-picker-indicator {_x000D_
position: absolute;_x000D_
top: 3px;_x000D_
right: 0;_x000D_
color: black;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>_x000D_
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
_x000D_
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn't check for others, but don't expect to fail on any Webkit.
For nested JSON plain text
db.model.findAll({
raw : true ,
nest : true
})