You can not specify the password from the command line but you can do either using ssh keys or using sshpass
as suggested by John C. or using a expect
script.
To use sshpass, you need to install it first. Then
sshpass -f <(printf '%s\n' your_password) ssh user@hostname
instead of using sshpass -p your_password
. As mentioned by Charles Duffy
in the comments, it is safer to supply the password from a file or from a variable instead of from command line.
BTW, a little explanation for the <(command)
syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe
Piping to another process (Although this WON'T accomplish what you said you are trying to do):
command1 | command2
This will send the output of command1 as the input of command2
-exec
on a find
(this will do what you are wanting to do -- but is specific to find
)
find . -name '*.foo' -exec cat {} \;
(Everything between find
and -exec
are the find predicates you were already using. {}
will substitute the particular file you found into the command (cat {}
in this case); the \;
is to end the -exec
command.)
send output of one process as command line arguments to another process
command2 `command1`
for example:
cat `find . -name '*.foo' -print`
(Note these are BACK-QUOTES not regular quotes (under the tilde ~ on my keyboard).)
This will send the output of command1
into command2
as command line arguments. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.
int main()
{
char buff[1024] = {0};
FILE* cvt;
int status;
/* Launch converter and open a pipe through which the parent will write to it */
cvt = popen("converter", "w");
if (!cvt)
{
printf("couldn't open a pipe; quitting\n");
exit(1)
}
printf("enter Fahrenheit degrees: " );
fgets(buff, sizeof (buff), stdin); /*read user's input */
/* Send expression to converter for evaluation */
fprintf(cvt, "%s\n", buff);
fflush(cvt);
/* Close pipe to converter and wait for it to exit */
status=pclose(cvt);
/* Check the exit status of pclose() */
if (!WIFEXITED(status))
printf("error on closing the pipe\n");
return 0;
}
The important steps in this program are:
popen()
call which establishes the association between a child process and a pipe in the parent.fprintf()
call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.pclose()
call that closes the pipe and causes the child process to terminate.You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...
C:\>PowerShell -Command "temperature | prismcom.exe usb"
Please read up on Understanding the Windows PowerShell Pipeline
You can also type in C:\>PowerShell
at the command-line and it'll put you in PS C:\>
mode instanctly, where you can directly start writing PS.
Instead of doing all these greps and stuff, I'd advise you to use ps capabilities of changing output format.
ps -o cmd= -p 12345
You get the cmmand line of a process with the pid specified and nothing else.
This is POSIX-conformant and may be thus considered portable.
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
you must use [ngModel] instead of two way model binding with [(ngModel)]. then use manual change event with (ngModelChange). this is public rule for all two way input in components.
because pipe on event emitter is wrong.
Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1
is specified AFTER the 1>
redirect, otherwise it will not work.
REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt
This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.
Situation:
someprog | filter
you want the exit status from someprog
and the output from filter
.
Here is my solution:
((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1
echo $?
See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.
You can actually just use os module to do both:
import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria
for file in os.listdir(location):
try:
if file.endswith(".csv"):
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello"):
print "hello files found: \t", file
filebeginwithhello.append(file)
counter = counter+1
else:
otherfiles.append(file)
counter = counter+1
except Exception as e:
raise e
print "No files found here!"
print "Total files found:\t", counter
Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.
In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
then get() method should like this-
get (): FirebaseListObservable<any[]>{
return this.db.list('/movies');
}
this get() method will return FirebaseListObervable of movies list
In your MoviesComponent should look like this
export class MoviesComponent implements OnInit {
movies: any[];
constructor(private moviesDb: MoviesService) { }
ngOnInit() {
this.moviesDb.get().subscribe((snaps) => {
this.movies = snaps;
});
}
}
Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this
ul
li(*ngFor='let movie of movies')
{{ movie.title }}
if you declear movies as a
movies: FirebaseListObservable<any[]>;
then you should simply call
movies: FirebaseListObservable<any[]>;
ngOnInit() {
this.movies = this.moviesDb.get();
}
and your html should be this
ul
li(*ngFor='let movie of movies | async')
{{ movie.title }}
Because I fall for it, I would like to drop a note. I found this thread, because I have to rewrite an old sh script to be POSIX compatible. This basically means to circumvent the pipe/subshell problem introduced by POSIX by rewriting code like this:
some_command | read a b c
into:
read a b c << EOF
$(some_command)
EOF
And code like this:
some_command |
while read a b c; do
# something
done
into:
while read a b c; do
# something
done << EOF
$(some_command)
EOF
But the latter does not behave the same on empty input. With the old notation the while loop is not entered on empty input, but in POSIX notation it is! I think it's due to the newline before EOF, which cannot be ommitted. The POSIX code which behaves more like the old notation looks like this:
while read a b c; do
case $a in ("") break; esac
# something
done << EOF
$(some_command)
EOF
In most cases this should be good enough. But unfortunately this still behaves not exactly like the old notation if some_command prints an empty line. In the old notation the while body is executed and in POSIX notation we break in front of the body.
An approach to fix this might look like this:
while read a b c; do
case $a in ("something_guaranteed_not_to_be_printed_by_some_command") break; esac
# something
done << EOF
$(some_command)
echo "something_guaranteed_not_to_be_printed_by_some_command"
EOF
I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:
import shlex
from subprocess import Popen, PIPE
def get_exitcode_stdout_stderr(cmd):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
#
return exitcode, out, err
cmd = "..." # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)
I also have a blog post on it here.
Edit: the solution was updated to a newer one that doesn't need to write to temp. files.
Linux Pipes
First In First Out (FIFO) interproccess communication mechanism.
Unnamed Pipes
On the command line, represented by a "|" between two commands.
Named Pipes
A FIFO special file. Once created, you can use the pipe just like a normal file(open, close, write, read, etc).
To create a named pipe, called "myPipe", from the command line (man page):
mkfifo myPipe
To create a named pipe from c, where "pathname" is the name you would like the pipe to have and "mode" contains the permissions you want the pipe to have (man page):
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
Or to swap the output from standard error and standard output over, use:
command 3>&1 1>&2 2>&3
This creates a new file descriptor (3) and assigns it to the same place as 1 (standard output), then assigns fd 1 (standard output) to the same place as fd 2 (standard error) and finally assigns fd 2 (standard error) to the same place as fd 3 (standard output).
Standard error is now available as standard output and the old standard output is preserved in standard error. This may be overkill, but it hopefully gives more details on Bash file descriptors (there are nine available to each process).
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
To get the output of ls
, use stdout=subprocess.PIPE
.
>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo
The command cdrecord --help
outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True
argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
As mentioned by Chris Morgan, you should be using proc.communicate()
instead of proc.read()
.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout:
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
Another possibility, if using the -o
(output file) option - the destination directory does not exist.
eg. if you have -o /tmp/download/abc.txt
and /tmp/download does not exist.
Hence, ensure any required directories are created/exist beforehand, use the --create-dirs
option as well as -o
if necessary
Currency pipe uses the number
one internally for number formatting. So you can use it like this:
{{ number | number : '1.2-2'}}
After Python 3.5 you can also use:
import subprocess
f = open('test.txt', 'w')
process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
f.write(process.stdout)
f.close()
The execution of the command is blocking and the output will be in process.stdout.
Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;
public class Network {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
System.out.println(response.getStatusCode());
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
}
The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.
You may wish to review a simple example at:
There is a simpler way in Android
DateFormat.getInstance().format(currentTimeMillis);
Moreover, Date is deprecated, so use DateFormat class.
DateFormat.getDateInstance().format(new Date(0));
DateFormat.getDateTimeInstance().format(new Date(0));
DateFormat.getTimeInstance().format(new Date(0));
The above three lines will give:
Dec 31, 1969
Dec 31, 1969 4:00:00 PM
4:00:00 PM 12:00:00 AM
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
If your array of objects are complex like:
$scope.friends = [{ name: John , uuid: 1234}, {name: Joe, uuid, 5678}];
And your current model was set to something like:
$scope.user.friend = {name:John, uuid: 1234};
It helped to use the track by
function on uuid (or any unique field), as long as the ng-model="user.friend" also has a uuid:
<select ng-model="user.friend"
ng-options="friend as friend.name for friend in friends track by friend.uuid">
</select>
None of the answers given so far is safe in the face of concurrent accesses, as pointed out in Tim Sylvester's comment, and will raise exceptions in case of races. To fix that, the insert/update combo must be wrapped in some kind of loop statement, so that in case of an exception the whole thing is retried.
As an example, here's how Grommit's code can be wrapped in a loop to make it safe when run concurrently:
PROCEDURE MyProc (
...
) IS
BEGIN
LOOP
BEGIN
MERGE INTO Employee USING dual ON ( "id"=2097153 )
WHEN MATCHED THEN UPDATE SET "last"="smith" , "name"="john"
WHEN NOT MATCHED THEN INSERT ("id","last","name")
VALUES ( 2097153,"smith", "john" );
EXIT; -- success? -> exit loop
EXCEPTION
WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted
NULL; -- exception? -> no op, i.e. continue looping
WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted
NULL; -- exception? -> no op, i.e. continue looping
END;
END LOOP;
END;
N.B. In transaction mode SERIALIZABLE
, which I don't recommend btw, you might run into
ORA-08177: can't serialize access for this transaction exceptions instead.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
Slightly changed to David Murdoch's code for generic library
Function HasByName(cSheetName As String, _
Optional oWorkBook As Excel.Workbook) As Boolean
HasByName = False
Dim wb
If oWorkBook Is Nothing Then
Set oWorkBook = ThisWorkbook
End If
For Each wb In oWorkBook.Worksheets
If wb.Name = cSheetName Then
HasByName = True
Exit Function
End If
Next wb
End Function
Are you parsing that string as ObjectId
?
Here in my application, what I do is:
ObjectId.fromString( myObjectIdString );
When you ask the question, "Can the scroll-bars of a browser be removed in some way, rather than simply hidden or camouflaged", everyone will say "Not possible" because it is not possible to remove the scrollbars from all browsers in a compliant and cross-compatible way, and then there's the whole argument of usability.
However, it is possible to prevent the browser from ever having the need to generate and display scrollbars if you do not allow your webpage to overflow.
This just means that we have to proactively substitute the same behavior that the browser would typically do for us and tell the browser thanks but no thanks buddy. Rather than try to remove scrollbars (which we all know is not possible) we can avoid scrolling (perfectly feasible) and scroll within the elements that we make and have more control over.
Create a div with overflow hidden. Detect when the user attempts to scroll, but is unable to because we've disabled the browsers ability to scroll with overflow: hidden.. and instead move the content up using JavaScript when this occurs. Thereby creating our own scrolling without the browsers default scrolling or use a plugin like iScroll.
For the sake of being thorough; all the vendor specific ways of manipulating scroll-bars:
*These properties were never part of the CSS specification, nor were they ever approved or vendor prefixed, but they work in Internet Explorer and Konqueror. These can also be set locally in the user style sheet for each application. In Internet Explorer you find it under the "Accessibility" tab, in Konqueror under the "Stylesheets" tab.
body, html { /* These are defaults and can be replaced by hexadecimal color values */
scrollbar-base-color: aqua;
scrollbar-face-color: ThreeDFace;
scrollbar-highlight-color: ThreeDHighlight;
scrollbar-3dlight-color: ThreeDLightShadow;
scrollbar-shadow-color: ThreeDDarkShadow;
scrollbar-darkshadow-color: ThreeDDarkShadow;
scrollbar-track-color: Scrollbar;
scrollbar-arrow-color: ButtonText;
}
As of Internet Explorer 8 these properties were vendor prefixed by Microsoft, but they were still never approved by W3C.
-ms-scrollbar-base-color
-ms-scrollbar-face-color
-ms-scrollbar-highlight-color
-ms-scrollbar-3dlight-color
-ms-scrollbar-shadow-color
-ms-scrollbar-darkshadow-color
-ms-scrollbar-base-color
-ms-scrollbar-track-color
Internet Explorer makes scroll
available which sets whether or not to disable or enable scroll bars; it can also be used to get the value of the position of the scroll bars.
With Microsoft Internet Explorer 6 and later, when you use the !DOCTYPE
declaration to specify standards-compliant mode, this attribute applies to the HTML element. When standards-compliant mode is not specified, as with earlier versions of Internet Explorer, this attribute applies to the BODY
element, NOT the HTML
element.
It's also worth noting that when working with .NET the ScrollBar class in System.Windows.Controls.Primitives
in the Presentation framework is responsible for rendering the scrollbars.
http://msdn.microsoft.com/en-us/library/ie/ms534393(v=vs.85).aspx
WebKit extensions related to scroll-bar customization are:
::-webkit-scrollbar {} /* 1 */
::-webkit-scrollbar-button {} /* 2 */
::-webkit-scrollbar-track {} /* 3 */
::-webkit-scrollbar-track-piece {} /* 4 */
::-webkit-scrollbar-thumb {} /* 5 */
::-webkit-scrollbar-corner {} /* 6 */
::-webkit-resizer {} /* 7 */
These can each be combined with additional pseudo-selectors:
:horizontal
– The horizontal pseudo-class applies to any scrollbar pieces that have a horizontal orientation.:vertical
– The vertical pseudo-class applies to any scrollbar pieces that have a vertical orientation.:decrement
– The decrement pseudo-class applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view’s position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).:increment
– The increment pseudo-class applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view’s position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).:start
– The start pseudo-class applies to buttons and track pieces. It indicates whether the object is placed before the thumb.:end
– The end pseudo-class applies to buttons and track pieces. It indicates whether the object is placed after the thumb.:double-button
– The double-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.:single-button
– The single-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.:no-button
– Applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.:corner-present
– Applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.:window-inactive
– Applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)Examples of these combinations
::-webkit-scrollbar-track-piece:start { /* Select the top half (or left half) or scrollbar track individually */ }
::-webkit-scrollbar-thumb:window-inactive { /* Select the thumb when the browser window isn't in focus */ }
::-webkit-scrollbar-button:horizontal:decrement:hover { /* Select the down or left scroll button when it's being hovered by the mouse */ }
addWindowScrollHandler public static HandlerRegistration addWindowScrollHandler(Window.ScrollHandler handler)
Adds a Window.ScrollEvent handler Parameters: handler - the handler Returns: returns the handler registration [source](http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/Window.html#addWindowScrollHandler(com.google.gwt.user.client.Window.ScrollHandler) )
Mozilla does have some extensions for manipulating the scroll-bars, but they are all recommended not to be used.
-moz-scrollbars-none
They recommend using overflow:hidden in place of this.-moz-scrollbars-horizontal
Similar to overflow-x-moz-scrollbars-vertical
Similar to overflow-y-moz-hidden-unscrollable
Only works internally within a users profile settings. Disables scrolling XML root elements and disables using arrow keys and mouse wheel to scroll web pages.
This is not really useful as far as I know, but it's worth noting that the attribute which controls whether or not scrollbars are displayed in Firefox is (reference link):
As has been previously mentioned in some other answers, here is an illustration which is sufficiently self-explanatory.
Just because I'm curious, I wanted to learn about the origin of scrollbars, and these are the best references I found.
In an HTML5 specification draft, the seamless
attribute was defined to prevent scroll-bars from appearing in iFrames so that they could be blended with surrounding content on a page. Though this element does not appear in the latest revision.
The scrollbar
BarProp object is a child of the window
object and represents the user interface element that contains a scrolling mechanism, or some similar interface concept. window.scrollbars.visible
will return true
if the scroll bars are visible.
interface Window {
// The current browsing context
readonly attribute WindowProxy window;
readonly attribute WindowProxy self;
attribute DOMString name;
[PutForwards=href] readonly attribute Location location;
readonly attribute History history;
readonly attribute UndoManager undoManager;
Selection getSelection();
[Replaceable] readonly attribute BarProp locationbar;
[Replaceable] readonly attribute BarProp menubar;
[Replaceable] readonly attribute BarProp personalbar;
[Replaceable] readonly attribute BarProp scrollbars;
[Replaceable] readonly attribute BarProp statusbar;
[Replaceable] readonly attribute BarProp toolbar;
void close();
void focus();
void blur();
// Truncated
The History API also includes features for scroll restoration on page navigation to persist the scroll position on page load.
window.history.scrollRestoration
can be used to check the status of scrollrestoration or change its status (appending ="auto"/"manual"
. Auto is the default value. Changing it to manual means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app's history. If you need to, you can keep track of the scroll position as you push history entries with history.pushState().
$_SERVER['HTTP_REFERER'];
But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.
Notice: Undefined index: HTTP_REFERER
I've tried the all solutions in here and didn't work in my case. But using
will-change: transform;
fixes the jagge issue.
I know this is an older thread, but I figure it might be worthwhile for me to put in my implementation since I found this thread trying to do the same thing as OP, except with Root level access, but didn't really find a solution I was looking for. The below method creates a static Root level shell that is used for just executing commands without regard to error checking or even if the command executed successfully.
I use it an Android flashlight app I've created that allows setting the LED to different level of brightness. By removing all the error checking and other fluff I can get the LED to switch to a specified brightness level in as little as 3ms, which opens the door to LightTones (RingTones with light). More details on the app itself can be found here: http://forum.xda-developers.com/showthread.php?t=2659842
Below is the class in its entirety.
public class Shell {
private static Shell rootShell = null;
private final Process proc;
private final OutputStreamWriter writer;
private Shell(String cmd) throws IOException {
this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
}
public void cmd(String command) {
try {
writer.write(command+'\n');
writer.flush();
} catch (IOException e) { }
}
public void close() {
try {
if (writer != null) { writer.close();
if(proc != null) { proc.destroy(); }
}
} catch (IOException ignore) {}
}
public static void exec(String command) { Shell.get().cmd(command); }
public static Shell get() {
if (Shell.rootShell == null) {
while (Shell.rootShell == null) {
try { Shell.rootShell = new Shell("su"); //Open with Root Privileges
} catch (IOException e) { }
}
}
return Shell.rootShell;
}
}
Then anywhere in my app to run a command, for instance changing the LED brightness, I just call:
Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);
_.unique
no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique
was splitted into _.uniq
, _.sortedUniq
, _.sortedUniqBy
, and _.uniqBy
.
You could use _.uniqBy
like this:
_.uniqBy(data, function (e) {
return e.id;
});
...or like this:
_.uniqBy(data, 'id');
Documentation: https://lodash.com/docs#uniqBy
For older versions of Lodash (< 4.0.0 ):
Assuming that the data should be uniqued by each object's id
property and your data is stored in data
variable, you can use the _.unique()
function like this:
_.unique(data, function (e) {
return e.id;
});
Or simply like this:
_.uniq(data, 'id');
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
You can do it by using GeometryReader
struct ContentView : View {
var body: some View {
GeometryReader { geometry in
VStack {
Text("Turtle Rock").frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading).background(Color.red)
}
}
}
}
Your output like:
Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.
// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});
// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});
// async/await
async function auth() {
const doc = await Auth.findOne({nick: 'noname'}).exec();
return doc;
}
auth();
See the docs if you would like to use a third party promise library.
From the Twitter FAQ:
Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.
It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.
Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):
SELECT f.value
FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
AND f.otherid = 17
UNION
SELECT NULL AS value
FROM period as p
WHERE p.companyid = 100
AND NOT EXISTS (
SELECT *
FROM facts AS f
WHERE p.id = f.periodid
AND f.otherid = 17
);
So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).
However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.
As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.
ie:
public class Museo500TextView extends TextView {
public Museo500TextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
}
}
and
<my.package.views.Museo900TextView
android:id="@+id/dialog_error_text_header"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="12sp" />
If you need a simple working solution, try using DefaultTableModel.
If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.
For example, if you have used Vector, then it may be something like this:
public class SimpleTableModel extends AbstractTableModel {
private Vector<String> columnNames = new Vector<String>();
// Each value in the vector is a row; String[] - row data;
private Vector<String[]> data = new Vector<String[]>();
...
public String getValueAt(int row, int col) {
return data.get(row)[col];
}
...
public void removeRow(int row) {
data.removeElementAt(row);
}
}
If you have used List, then it would be very much alike:
// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();
public void removeRow(int row) {
data.remove(row);
}
HashMap:
//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();
public void removeRow(Integer row) {
data.remove(row);
}
And if you are using arrays like this one
String[][] data = { { "a", "b" }, { "c", "d" } };
then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.
For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.
I find git stash very useful for temporal handling of all 'dirty' states.
For Genymotion 2.12.2 you can find GApps added in all their virtual devices. Run any virtual device by Genymotion and then you can find on the top right corner which says Open GApps. Press it and it will automatically install GApps.
If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.
scp user@host:/path/file /localpath/file
Wild card characters are supported, so
scp user@host:/path/folder/* /localpath/folder
will copy all of the remote files in that folder.If copying more then one directory.
note -r will copy all sub-folders and content too.
You may drag'n'drop your folder to Side bar. To enable Side bar you should do View -> Side bar -> show opened files. You'll got opened files (tabs) tree and folder structure at Side bar.
You can use following commands to extract public/private key from a PKCS#12 container:
PKCS#1 Private key
openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
Certificates:
openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.
Alternatively:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
You can use online converter, developed by me at N'counter.
This is the easiest way to open SPSS file in Excel.
1) You just have to upload your file to SPSS coN'verter at https://secure.ncounter.de/SpssConverter
2) Select some options
3) And your converted Excel file will be downloaded
No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don't peer into your data at any time!
tmtheme-editor.herokuapp.com seems pretty nice.
On the mac, the default theme files are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Color\ Scheme\ -\ Default
On Win7, the default theme files are in %appdata%\Sublime Text 2\Packages\Color Scheme - Default
Here is how to increase the Paging size
In addition to first answer, remember to change string selectionstart index to the end of the word or you will get reverse order of letters in the string.
s.SelectionStart=s.Length;
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
I had the same problem several times. The following solutions are solved my problem. I have listed out them according to complexity.
Restart the computer and see whether the problem is out
If it still exists, try to kill the process on running port usually 8080
netstat -ano | findstr 8080
taskkill /F /PID <PID>
If it still exists, go to 'android' directory as follow and go further
cd android
./gradlew clean
and start node
npm start
then run npx react-native run android
or expo stat
and press 'a'
Hope you will OK with the above issues.
Replace the string
value = value.replace(/'/g, "\\'");
where value is your string which is going to store in your Database.
Further,
NPM package for this, you can have look into it
I solved this problem by uninstalling flutter from the Plugins. After restarting Android Studio, I opened the plugins, and then it shows that my Dart plugin is not compatible with my Android Studio (v3.6). I updated Dart, restart android studio, then reinstall Flutter again. After that, I have to set the SDK path for the Flutter and voila everything works now :D
Webkit scrollbar doesnt support on most of the browers.
Supports on CHROME
Here is a demo for webkit scrollbar Webkit Scrollbar DEMO
If you are looking for more examples Check this More Examples
Another Method is Jquery Scroll Bar Plugin
It supports on all browsers and easy to apply
Download the plugin from Download Here
How to use and for more options CHECK THIS
If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print
will work fine, but substr
throws an error when multibyte characters are present.
find_offending_character <- function(x, maxStringLength=256){
print(x)
for (c in 1:maxStringLength){
offendingChar <- substr(x,c,c)
#print(offendingChar) #uncomment if you want the indiv characters printed
#the next character is the offending multibyte Character
}
}
string_vector <- c("test", "Se\x96ora", "works fine")
lapply(string_vector, find_offending_character)
I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string
error.
Set height and width parameters in CSS file
.ImageStyle{_x000D_
_x000D_
max-height: 17vw;_x000D_
min-height: 17vw;_x000D_
max-width:17vw;_x000D_
min-width: 17vw;_x000D_
_x000D_
}
_x000D_
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
A major thing to watch out for is whether a button is Enabled or not. You can still click them and nothing will fall over and the element is there but it is not ready to be clicked on so just doesnt do anything.
I've been using webdriver and its taken me most of the day to figure this out!
The following method seems to work reliably (in my environment for one button!)
private void TryClick(By selector)
{
var wait = WaitUpTo(TimeSpan.FromSeconds(10));
var element = wait.Until(ExpectedConditions.ElementIsVisible((selector)));
//really important bit!
WaitUpTo(TimeSpan.FromSeconds(5))
.Until(d => element.Enabled);
element.Click();
}
you use it something like
TryClick(By.XPath("//button[contains(.//*,'Some Text')]"));
Write the table name in the query editor select the name and press Alt+F1 and it will bring all the information of the table.
Perhaps not the most efficient solution, but certainly short & simple:
def repstr(string, length):
return (string * length)[0:length]
repstr("foobar", 14)
Gives "foobarfoobarfo". One thing about this version is that if length < len(string) then the output string will be truncated. For example:
repstr("foobar", 3)
Gives "foo".
Edit: actually to my surprise, this is faster than the currently accepted solution (the 'repeat_to_length' function), at least on short strings:
from timeit import Timer
t1 = Timer("repstr('foofoo', 30)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo', 30)", 'from __main__ import repeat_to_length')
t1.timeit() # gives ~0.35 secs
t2.timeit() # gives ~0.43 secs
Presumably if the string was long, or length was very high (that is, if the wastefulness of the string * length
part was high) then it would perform poorly. And in fact we can modify the above to verify this:
from timeit import Timer
t1 = Timer("repstr('foofoo' * 10, 3000)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo' * 10, 3000)", 'from __main__ import repeat_to_length')
t1.timeit() # gives ~18.85 secs
t2.timeit() # gives ~1.13 secs
Try this
<a href="javascript:window.open('','_self').close();">close</a>
Callable and Runnable both is similar to each other and can use in implementing thread. In case of implementing Runnable you must implement run() method but in case of callable you must need to implement call() method, both method works in similar ways but callable call() method have more flexibility.There is some differences between them.
Difference between Runnable and callable as below--
1) The run() method of runnable returns void, means if you want your thread return something which you can use further then you have no choice with Runnable run() method. There is a solution 'Callable', If you want to return any thing in form of object then you should use Callable instead of Runnable. Callable interface have method 'call()' which returns Object.
Method signature - Runnable->
public void run(){}
Callable->
public Object call(){}
2) In case of Runnable run() method if any checked exception arises then you must need to handled with try catch block, but in case of Callable call() method you can throw checked exception as below
public Object call() throws Exception {}
3) Runnable comes from legacy java 1.0 version, but callable came in Java 1.5 version with Executer framework.
If you are familiar with Executers then you should use Callable instead of Runnable.
Hope you understand.
Make sure you have settings.xml. I had the same problem when I've deleted it by mistake.
The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...
df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ]
Use java.time.Instant
class to parse text in standard ISO 8601 format, representing a moment in UTC.
Instant.parse( "2010-10-02T12:23:23Z" )
That format is defined by the ISO 8601 standard for date-time string formats.
Both:
…use ISO 8601 formats by default for parsing and generating strings.
You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.
Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Instant instant = Instant.parse( "2010-10-02T12:23:23Z" ); // `Instant` is always in UTC.
Convert to the old class.
java.util.Date date = java.util.Date.from( instant ); // Pass an `Instant` to the `from` method.
Time Zone
If needed, you can assign a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); // Assign a time zone adjustment from UTC.
Convert.
java.util.Date date = java.util.Date.from( zdt.toInstant() ); // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
Here is some example code in Joda-Time 2.8.
org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC ); // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.
Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.
java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.
Time Zone
If needed, you can assign a time zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE()
-- Write Your Query
SELECT @EndTime=GETDATE()
--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]
Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.
if (_remoteDevices.Contains(rDevice))
_remoteDevices.Add(rDevice);
Performing List.Contains() on a custom class/object requires implementing IEquatable<T>
on the custom class or overriding the Equals
. It's a good idea to also implement GetHashCode
in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx
public class RemoteDevice: IEquatable<RemoteDevice>
{
private readonly int id;
public RemoteDevice(int uuid)
{
id = id
}
public int GetId
{
get { return id; }
}
// ...
public bool Equals(RemoteDevice other)
{
if (this.GetId == other.GetId)
return true;
else
return false;
}
public override int GetHashCode()
{
return id;
}
}
The method signature for addMarker
is:
public final Marker addMarker (MarkerOptions options)
So when you add a marker to a GoogleMap
by specifying the options for the marker, you should save the Marker
object that is returned (instead of the MarkerOptions
object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove()
to remove it from the map.
As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean)
.
Based on zenpoy's answer:
import Image
import numpy
def image2pixelarray(filepath):
"""
Parameters
----------
filepath : str
Path to an image file
Returns
-------
list
A list of lists which make it simple to access the greyscale value by
im[y][x]
"""
im = Image.open(filepath).convert('L')
(width, height) = im.size
greyscale_map = list(im.getdata())
greyscale_map = numpy.array(greyscale_map)
greyscale_map = greyscale_map.reshape((height, width))
return greyscale_map
If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.
Open:
Close:
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
For my case, I had to right click the solution and click "Retarget Projects".
In my case I retargetted to Windows SDK version 10.0.1777.0 and Platform Toolset v142. I also had to change "Windows.h"
to<windows.h>
I am running Visual Studio 2019 version 16.25 on a windows 10 machine
I got this error when I forgot to add new form fields/database columns to the $fillable
array in the Laravel model - the model was stripping them out.
Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ class
ses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.
What you need is look around assertion like .+? (?=abc)
.
See: Lookahead and Lookbehind Zero-Length Assertions
Be aware that [abc]
isn't the same as abc
. Inside brackets it's not a string - each character is just one of the possibilities. Outside the brackets it becomes the string.
Clean up in dealloc.
This is one of the easiest things to forget - esp. when coding at 150mph. Always, always, always clean up your attributes/member variables in dealloc.
I like to use Objc 2 attributes - with the new dot notation - so this makes the cleanup painless. Often as simple as:
- (void)dealloc
{
self.someAttribute = NULL;
[super dealloc];
}
This will take care of the release for you and set the attribute to NULL (which I consider defensive programming - in case another method further down in dealloc accesses the member variable again - rare but could happen).
With GC turned on in 10.5, this isn't needed so much any more - but you might still need to clean up others resources you create, you can do that in the finalize method instead.
Using NOT EXISTS
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
WHERE NOT EXISTS(SELECT id
FROM TABLE_2 t2
WHERE t2.id = t1.id)
Using NOT IN
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
WHERE t1.id NOT IN (SELECT id
FROM TABLE_2)
Using LEFT JOIN/IS NULL
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
WHERE t2.id IS NULL
Of the three options, the LEFT JOIN/IS NULL
is less efficient. See this link for more details.
In my case, I had the whole variable for JAVA_HOME in quotes. I just had to remove the quotes and then it worked fine.
package com.java.exercise;
public class RemoveCharacter {
/**
* @param args
*/
public static void main(String[] args) {
RemoveCharacter rem = new RemoveCharacter();
char[] ch=rem.GetDuplicates("JavavNNNNNNC".toCharArray());
char[] desiredString="JavavNNNNNNC".toCharArray();
System.out.println(rem.RemoveDuplicates(desiredString, ch));
}
char[] GetDuplicates(char[] input)
{
int ctr=0;
char[] charDupl=new char[20];
for (int i = 0; i <input.length; i++)
{
char tem=input[i];
for (int j= 0; j < i; j++)
{
if (tem == input[j])
{
charDupl[ctr++] = input[j];
}
}
}
return charDupl;
}
public char[] RemoveDuplicates(char[] input1, char []input2)
{
int coutn =0;
char[] out2 = new char[10];
boolean flag = false;
for (int i = 0; i < input1.length; i++)
{
for (int j = 0; j < input2.length; j++)
{
if (input1[i] == input2[j])
{
flag = false;
break;
}
else
{
flag = true;
}
}
if (flag)
{
out2[coutn++]=input1[i];
flag = false;
}
}
return out2;
}
}
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...
I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.
ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).
I'm still trying to find a way around this. If anyone has any input, it's most welcome.
If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.
To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().
As like below example:
SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
SELECT DISTINCT <column names>...
) AS tbl
You could also use ld
option -Bdynamic
gcc <objectfiles> -static -lstatic1 -lstatic2 -Wl,-Bdynamic -ldynamic1 -ldynamic2
All libraries after it (including system ones linked by gcc automatically) will be linked dynamically.
In terms of speed: #1 and #4, but not by much in most instances.
You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_
is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)
#5 might be similar.
In terms memory usage: They're all the same except for #5.
for (@a)
is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.
In terms of readability: #1.
In terms of flexibility: #1/#4 and #5.
#2 does not support elements that are false. #2 and #3 are destructive.
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
With enumerate(alist) you can store the first element (n) that is the index of the list when the element x is equal to what you look for.
>>> alist = ['foo', 'spam', 'egg', 'foo']
>>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
>>> foo_indexes
[0, 3]
>>>
This function takes the item and the list as arguments and return the position of the item in the list, like we saw before.
def indexlist(item2find, list_or_string):
"Returns all indexes of an item in a list or a string"
return [n for n,item in enumerate(list_or_string) if item==item2find]
print(indexlist("1", "010101010"))
Output
[1, 3, 5, 7]
for n, i in enumerate([1, 2, 3, 4, 1]):
if i == 1:
print(n)
Output:
0
4
The actual Apple reference documentation is quite comprehensive
Scroll down until you see this part
You should actually return "200 OK" and in the response body include a message about what happened with the posted data. Then it's up to your application to understand the message.
The thing is, HTTP status codes are exactly that - HTTP status codes. And those are meant to have meaning only at the transportation layer, not at the application layer. The application layer should really never even know that HTTP is being used. If you switched your transportation layer from HTTP to Homing Pigeons, it should not affect your application layer in any way.
Let me give you a non-virtual example. Let's say you fall in love with a girl and she loves you back but her family moves to a completely different country. She gives you her new snail-mail address. Naturally, you decide to send her a love letter. So you write your letter, put it into an envelope, write her address on the envelope, put a stamp on it and send it. Now let's consider these scenarios
In short: Returning "200 OK" doesn't mean that the server app has good news for you. It only means that it has some news.
PS: The 422 status code has a meaning only in the context of WebDAV. If you're not working with WebDAV, then 422 has exactly the same standard meaning as any other non-standard code = which is none.
It cant find the entry point for your program, in this case main()
. Your linker settings are likely incorrect.
See this post here
If your data is in a Pandas DataFrame, you can use Seaborn's heatmap
function to create your desired plot.
import seaborn as sns
Var_Corr = df.corr()
# plot the heatmap and annotation on it
sns.heatmap(Var_Corr, xticklabels=Var_Corr.columns, yticklabels=Var_Corr.columns, annot=True)
From the question, it looks like the data is in a NumPy array. If that array has the name numpy_data
, before you can use the step above, you would want to put it into a Pandas DataFrame using the following:
import pandas as pd
df = pd.DataFrame(numpy_data)
The following line will make your script to sleep for 5 mins.
WScript.Sleep 5*60*1000
Note that the value passed to sleep call is in milli seconds.
partial answer: pear HTTP_UPLOAD can be usefull http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
If the column is a timestamp you can do the following:
if(fromDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
}
if(toDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
}
resultDB = criteria.list();
Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?
If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--
My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.
You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.
The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.
edit: Just to help you get started you can look here:
1.a. Add following in applicationContext-mvc.xml
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.
If you are using ES5 -
backgroundImage: "url(" + Background + ")"
If you are using ES6 -
backgroundImage: `url(${Background})`
Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
You should also be able to accomplish a similar thing using the premain method of a Java agent.
The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.
They are completely equivalent when used with printf()
. Personally, I prefer %d
, it's used more often (should I say "it's the idiomatic conversion specifier for int
"?).
(One difference between %i
and %d
is that when used with scanf()
, then %d
always expects a decimal integer, whereas %i
recognizes the 0
and 0x
prefixes as octal and hexadecimal, but no sane programmer uses scanf()
anyway so this should not be a concern.)
A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.
cd / <-- Goto root directory
find . -print| grep -i dbm*.sql
Result varies on how you installed Oracle but mine displays this
/db/oracle
Goto the folder
less /db/oracle/db1/sqlplus/doc/README.htm
scroll down and you should see something like this
SQL*Plus Release Notes - Release 11.2.0.2
I encountered this issue while trying to fix $_SESSION's blocking behavior.
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
The session file remains locked until the script completes or the session is manually closed.
So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.
const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;
/**
* Open _SESSION read-only
*/
function OpenSessionReadOnly() {
session_start([
'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
'read_and_close' => true, // READ ACCESS FAST
]);
// $_SESSION is now defined. Call WriteSessionValues() to write out values
}
/**
* _SESSION is read-only by default. Call this function to save a new value
* call this function like `WriteSessionValues(["username"=>$login_user]);`
* to set $_SESSION["username"]
*
* @param array $values_assoc_array
*/
function WriteSessionValues($values_assoc_array) {
// this is required to close the read-only session and
// not get a warning on the next line.
session_abort();
// now open the session with write access
session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);
foreach ($values_assoc_array as $key => $value) {
$_SESSION[ $key ] = $value;
}
session_write_close(); // Write session data and end session
OpenSessionReadOnly(); // now reopen the session in read-only mode.
}
OpenSessionReadOnly(); // start the session for this page
Then when you go to write some value:
WriteSessionValues(["username"=>$login_user]);
The function takes an array of key=>value pairs to make it even more efficient.
A good way is to define a string your self.
#include <stdio.h>
typedef char string[]
int main() {
string test = "string";
return 0;
}
It's really that simple.
ArrayList check = new ArrayList();
for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
check.Add(iValue);
}
Please remove . from your target it should be a id
<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>
Also you have to give your modal id like below
<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">
Successfully installed it on OSX using homebrew:
brew install sip
brew install pyqt
which (currently) installs PyQt4. Anaconda is the main python on the machine (OSX 10.8.5).
If you have only one checkbox, you can do this easily with just ng-model:
<input type="checkbox" ng-model="checked"/>
<button ng-disabled="!checked"> Next </button>
And initialize $scope.checked in your Controller (default=false). The official doc discourages the use of ng-init in that case.
// where clause DBObject
DBObject query = new BasicDBObject("_id", new ObjectId(id));
// modifications to be applied
DBObject update = new BasicDBObject();
// set new values
update.put("$set", new BasicDBObject("param2","value2"));
// update the document
collection.update(query, update, true, false); //3rd param->upsertFlag, 4th param->updateMultiFlag
If you have multiple fields to be updated
Document doc = new Document();
doc.put("param2","value2");
doc.put("param3","value3");
update.put("$set", doc);
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
Python 3.x:
small greek letters are coded from 945 to 969
so,alpha is chr(945)
, omega is chr(969)
so just type
print(chr(945))
the list of small greek letters in a list:
greek_letterz=[chr(code) for code in range(945,970)]
print(greek_letterz)
And now, alpha is greek_letterz[0]
, beta is greek_letterz[1]
, a.s.o
aws s3 ls s3://mybucket/ --recursive | wc -l
or
aws cloudwatch get-metric-statistics \
--namespace AWS/S3 --metric-name NumberOfObjects \
--dimensions Name=BucketName,Value=BUCKETNAME \
Name=StorageType,Value=AllStorageTypes \
--start-time 2016-11-05T00:00 --end-time 2016-11-05T00:10 \
--period 60 --statistic Average
Note: The above cloudwatch command seems to work for some while not for others. Discussed here: https://forums.aws.amazon.com/thread.jspa?threadID=217050
You can look at cloudwatch's metric section to get approx number of objects stored.
I have approx 50 Million products and it took more than an hour to count using aws s3 ls
Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"
range()
can only work with integers, but dividing with the /
operator always results in a float value:
>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Make the value an integer again:
for i in range(int(c / 10)):
or use the //
floor division operator:
for i in range(c // 10):
Since this is the de facto answer when dealing with quotes in bash
, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.
The bash
shell supports two ways do arithmetic operation, one defined by the built-in let
command and the $((..))
operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.
It is important to understand that the arithmetic expression used with let
undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.
See this example when using let
let 'foo = 2 + 1'
echo $foo
3
Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of
bar=1
let 'foo = $bar + 1'
would fail miserably, as the $bar
under single quotes would not expand and needs to be double-quoted as
let 'foo = '"$bar"' + 1'
This should be one of the reasons, the $((..))
should always be considered over using let
. Because inside it, the contents aren't subject to word-splitting. The previous example using let
can be simply written as
(( bar=1, foo = bar + 1 ))
$((..))
without single quotesThough the $((..))
can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.
printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2
May be in some special cases of using the $((..))
operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl
statement to pass a counter every time a request is made, do
curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'
Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++))
is passed to requestCounter
field.
Step by step:
In the new window you should see your connected phone.
I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:
var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();
I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.
add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..
add new tomcat for each new workspace.
I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.
Looking at the class in edit #2, I would make it look like this:
class XmlController extends Controller
{
public function index()
{
$content = Request::all();
return Response::json($content);
}
}
Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.
More information on Laravel responses here:
Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe
The code is simple, just type:
import pyarrow.parquet as pq
df = pq.read_table(source=your_file_path).to_pandas()
For more information, see the document from Apache pyarrow Reading and Writing Single Files
There are several ways I can think of to do this.
Use a callback:
function FunctInit(someVarible){
//init and fill screen
AndroidCallGetResult(); // Enables Android button.
}
function getResult(){ // Called from Android button only after button is enabled
//return some variables
}
Use a Timeout (this would probably be my preference):
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
if (inited) {
//return some variables
} else {
setTimeout(getResult, 250);
}
}
Wait for the initialization to occur:
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
var a = 1;
do { a=1; }
while(!inited);
//return some variables
}
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
Coming on this old thread i wanted to stress that
1°) utility functions may (should?) be added to the rootscope via module.run. There is no need to instanciate a specific root level controller for this purpose.
angular.module('myApp').run(function($rootScope){
$rootScope.isNotString = function(str) {
return (typeof str !== "string");
}
});
2°) If you organize your code into separate modules you should use angular services or factory and then inject them into the function passed to the run block, as follow:
angular.module('myApp').factory('myHelperMethods', function(){
return {
isNotString: function(str) {
return (typeof str !== 'string');
}
}
});
angular.module('myApp').run(function($rootScope, myHelperMethods){
$rootScope.helpers = myHelperMethods;
});
3°) My understanding is that in views, for most of the cases you need these helper functions to apply some kind of formatting to strings you display. What you need in this last case is to use angular filters
And if you have structured some low level helper methods into angular services or factory, just inject them within your filter constructor :
angular.module('myApp').filter('myFilter', function(myHelperMethods){
return function(aString){
if (myHelperMethods.isNotString(aString)){
return
}
else{
// something else
}
}
);
And in your view :
{{ aString | myFilter }}
you can try this query.
select listagg(country_name,',') within group (order by country_name) cnt
from countries;
Find last time of update on a table
SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()
http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html
I've found that there are some files that may affect the $PATH
variable in macOS (works for me, 10.11 El Capitan), listed below:
As the top voted answer said, vi /etc/paths
, which is recommended from my point of view.
Also don't forget the /etc/paths.d
directory, which contains files may affect the $PATH
variable, set the git
and mono-command
path in my case. You can ls -l /etc/paths.d
to list items and rm /etc/paths.d/path_you_dislike
to remove items.
If you're using a "bash" environment (the default Terminal.app
, for example), you should check out ~/.bash_profile
or ~/.bashrc
. There may be not that file yet, but these two files have effects on the $PATH
.
If you're using a "zsh" environment (Oh-My-Zsh, for example), you should check out ~./zshrc
instead of ~/.bash*
thing.
And don't forget to restart all the terminal windows, then echo $PATH
. The $PATH
string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2
.
Noticed that the first two ways (/etc/paths
and /etc/path.d
) is in /
directory which will affect all the accounts in your computer while the last two ways (~/.bash*
or ~/.zsh*
) is in ~/
directory (aka, /Users/yourusername/
) which will only affect your account settings.
umount -f -t cifs -l /mnt &
Be careful of &
, let umount
run in background.
umount
will detach filesystem first, so you will find nothing abount /mnt
. If you run df
command, then it will umount /mnt
forcibly.
docker stop $(docker ps -a | grep "zalenium")
docker rm $(docker ps -a | grep "zalenium")
This should be enough.
You need to use %2.6f
instead of %f
in your printf statement
I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).
Done! The margin-left and margin-right AUTO for your .divtagABS will now work.
I just tried the first answer from Brad Rem and came to this setting in the web.config under BasicHttpBinding:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding bypassProxyOnLocal="False" useDefaultWebProxy="false" proxyAddress="http://127.0.0.1:8888" ...
...
</basicHttpBinding>
</bindings>
...
<system.serviceModel>
Hope this helps someone.
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}
.
But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.
You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
For transparency, this is also mandatory: renderer = new THREE.WebGLRenderer( { alpha: true } )
via Transparent background with three.js
What is row?
Either of these could be correct.
1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.
var result=row.split('|');
alert(result[2]);
otherwise
2) Use this where $(row)
is a jQuery
object.
var result=$(row).val().split('|');
alert(result[2]);
[As mentioned in the other answer, you may have to use $(row).val()
or $(row).text()
or $(row).html()
etc. depending on what $(row) is.]
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").
Simple and neat with fontawesome
input[type=radio] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
outline: none;
content: none;
margin-left: 5px;
}
input[type=radio]:before {
font-family: "FontAwesome";
content: "\f00c";
font-size: 25px;
color: transparent !important;
background: #fff;
width: 25px;
height: 25px;
border: 2px solid black;
margin-right: 5px;
}
input[type=radio]:checked:before {
color: black !important;
}
Ok, so here was my process:
keytool -list -v -keystore permanent.jks
- got me the alias.
keytool -export -alias alias_name -file certificate_name -keystore permanent.jks
- got me the certificate to import.
Then I could import it with the keytool:
keytool -import -alias alias_name -file certificate_name -keystore keystore location
As @Christian Bongiorno says the alias can't already exist in your keystore.
Here is a simple example:
EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;
Your call will be something like this
EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
Just to add onto the answer from Sarfraz, suprised nobody made it into a function yet.
Use the answer from ddagsan using the .filter method if you have the same value more than once in your array.
function arrayRemoveVal(array, removeValue){_x000D_
var newArray = jQuery.grep(array, function(value) {return value != removeValue;});_x000D_
return newArray;_x000D_
}_x000D_
var promoItems = [1,2,3,4]; _x000D_
promoItems = arrayRemoveVal(promoItems, 3);// removes 3_x000D_
console.log(promoItems);_x000D_
promoItems = arrayRemoveVal(promoItems, 3);// removes nothing_x000D_
console.log(promoItems);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
_x000D_
This is hard to answer without more detail about the network architecture. Some things to investigate are:
you need to add padding-top to "fill" element, plus add box-sizing:border-box - sample here bootply
curl
doesn't have an option to that (without also specifying the filename), but wget
does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.
wget -P relative/dir "$url"
wget -P /absolute/dir "$url"
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
You can use a concept that is frequently referred to as 'calendar tables'. Here is a good guide on how to create calendar tables in MySql:
-- create some infrastructure
CREATE TABLE ints (i INTEGER);
INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
-- only works for 100 days, add more ints joins for more
SELECT cal.date, tbl.data
FROM (
SELECT '2009-06-25' + INTERVAL a.i * 10 + b.i DAY as date
FROM ints a JOIN ints b
ORDER BY a.i * 10 + b.i
) cal LEFT JOIN tbl ON cal.date = tbl.date
WHERE cal.date BETWEEN '2009-06-25' AND '2009-07-01';
You might want to create table cal
instead of the subselect.
foreach(DataRow row in dataTable.Rows)
{
if(row.IsNull("myColumn"))
throw new Exception("Empty value!")
}
Runtime version:
View dividerView = new View(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, UIUtils.dpToPix(getContext(), 1));
dividerView.setLayoutParams(lp);
TypedArray array = getContext().getTheme()
.obtainStyledAttributes(new int[] {android.R.attr.listDivider});
Drawable draw = array.getDrawable(0);
array.recycle();
dividerView.setBackgroundDrawable(draw);
mParentLayout.addView(dividerView);
Write below function to get date in string, convert and return in string format.
getParsedDate(strDate){
var strSplitDate = String(strDate).split(' ');
var date = new Date(strSplitDate[0]);
// alert(date);
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
date = dd + "-" + mm + "-" + yyyy;
return date.toString();
}
Print it where you required: Date : {this.getParsedDate(stringDate)}
After several attempts this works for me on Windows 7 env.:
Initially directory to which you have copied all MongDB sources has such view:
bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe
All you need is to add data directory and db directory nested( data/db ) Final view should look like this:
data
bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe
Than simply type in directory where MongoDB sources and data/db dirs exist this command:
C:\my_mongo_dir\bin>mongod --dbpath .\data\db
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
There is also a different approach.. and this would work for tables that aren't static... basically use <th>
instead of <td>
for that column:
<style type="text/css">
table td { border: 1px solid black; }
table th { border: 0px; }
<style>
<table>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<th>Five</th>
</tr>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<th>Five</th>
</tr>
</tbody>
</table>
For me the problem was that there was a div above it (which of course shouldn't have been in the head, but it happens). Firefox didn't mind, but Chrome did.
Trac - by default - uses HTTP Authentication as well. Logout does not work and can not be fixed:
- This is an issue with the HTTP authentication scheme itself, and there's nothing we can do in Trac to fix it properly.
- There is currently no workaround (JavaScript or other) that works with all major browsers.
From: http://trac.edgewall.org/ticket/791#comment:103
Looks like that there is no working answer to the question, that issue has been reported seven years ago and it makes perfect sense: HTTP is stateless. Either a request is done with authentication credentials or not. But that's a matter of the client sending the request, not the server receiving it. The server can only say if a request URI needs authorization or not.
I'd explain parsing as the process of turning some kind of data into another kind of data.
In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.
For example, turning
":Nick!User@Host PRIVMSG #channel :Hello!"
into (C)
struct irc_line {
char *nick;
char *user;
char *host;
char *command;
char **arguments;
char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }
It looks like the github.com
host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts
. Jenkins runs on most distros as the user jenkins
and hence has its own .ssh
directory to store the list of public keys and known_hosts
.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
You just need to convert your set
to a list
import pandas as pd
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
my_cols = set(df.columns)
my_cols.remove('B')
my_cols.remove('D')
my_cols = list(my_cols)
df2 = df[my_cols]
I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler
(pretty sure some of the web devs already know about this tool)
Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder
PS. I would rather have it implemented in Chrome as a flag preserve after reload
, cannot do this now, forums and discussion groups blocked on corporate network :)
$('td:first-child')
will return a collection of the elements that you want.
var text = $('td:first-child').map(function() {
return $(this).html();
}).get();
This is what worked for me.
$(window).bind("pageshow", function() {
$("#id").val('');
$("#another_id").val('');
});
I initially had this in the $(document).ready
section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready
on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.
Use a lambda function.
Let's say you have an array:
nums = [0,1,5]
Check whether 5 is in nums
in Python 3.X:
(len(list(filter (lambda x : x == 5, nums))) > 0)
Check whether 5 is in nums
in Python 2.7:
(len(filter (lambda x : x == 5, nums)) > 0)
This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums
.
For example, check whether any number that is greater than or equal to 5 exists in nums
:
(len(filter (lambda x : x >= 5, nums)) > 0)
Note: This was for Bootstrap 2 (relevant when the question was asked).
You can accomplish this by using row-fluid
to make a fluid (percentage) based row inside an existing block
.
<div class="row">
<div class="span5">span5</div>
<div class="span3">span3</div>
<div class="span2">
<div class="row-fluid">
<div class="span12">span2</div>
<div class="span12">span2</div>
</div>
</div>
<div class="span2">span2</div>
</div>
<div class="row">
<div class="span6">
<div class="row-fluid">
<div class="span12">span6</div>
<div class="span12">span6</div>
</div>
</div>
<div class="span6">span6</div>
</div>
Here's a JSFiddle example.
I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid
after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):
.row-fluid [class*="span"] {
margin-left: 0;
}
Perhaps $('#fruit').val();
is not returning an array and you need something like:
$("#fruit").val() || []
My best solution for Swift 3+ without subclassing.
extension UIButton {
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
color.setFill()
UIRectFill(rect)
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
setBackgroundImage(colorImage, for: state)
}
}
With this extension it's easy to manage colors for different states and it will fade your normal color automatically in case highlighted color is not provided.
button.setBackgroundColor(.red, for: .normal)
The name
of the Series becomes the index
of the row in the DataFrame:
In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
In [100]: s = df.xs(3)
In [101]: s.name = 10
In [102]: df.append(s)
Out[102]:
A B C D
0 -2.083321 -0.153749 0.174436 1.081056
1 -1.026692 1.495850 -0.025245 -0.171046
2 0.072272 1.218376 1.433281 0.747815
3 -0.940552 0.853073 -0.134842 -0.277135
4 0.478302 -0.599752 -0.080577 0.468618
5 2.609004 -1.679299 -1.593016 1.172298
6 -0.201605 0.406925 1.983177 0.012030
7 1.158530 -2.240124 0.851323 -0.240378
10 -0.940552 0.853073 -0.134842 -0.277135
Direct value
should work just fine:
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex
returns -1 and the code breaks.
In my experience the pythonw.exe is faster at least with using pygame.
You can add days to a date like this:
// add days to current **DateTime**
var addedDateTime = DateTime.Now.AddDays(10);
// add days to current **Date**
var addedDate = DateTime.Now.Date.AddDays(10);
// add days to any DateTime variable
var addedDateTime = anyDate.AddDay(10);
you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.
using Ionic.Zip;
you can download it here, its free. http://dotnetzip.codeplex.com/
You can use a TextView or your custom TextView. The latter is when the textview cannot get focus all the time.
First, you can use a TextView or a custom TextView as the scrolling text view in your layout .xml file like this:
<com.example.myapplication.CustomTextView
android:id="@+id/tvScrollingMessage"
android:text="@string/scrolling_message_main_wish_list"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/black"
android:gravity="center"
android:textColor="@color/white"
android:textSize="15dp"
android:freezesText="true"/>
NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.
Then in case of using CustomTextView, you should define the CustomTextView class:
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
Hope it will be helpful to you. Cheers!
This is not a full answer, but the below code should help you:
function myFunction() {
var str = "https://www.123rf.com/photo_10965738_lots-oop.html";
matches = str.split('/');
return matches[2];
}
I would like some one to create code faster than mine. It help to improve my-self also.
Response.Write('... javascript that opens a window...')
For short arrays I suggest using np.argsort()
by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:
In [37]: temp = np.random.randint(1,10, 10)
In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop
In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop
CREATE PROCEDURE UpdateTables
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @RowCount1 INTEGER
DECLARE @RowCount2 INTEGER
DECLARE @RowCount3 INTEGER
DECLARE @RowCount4 INTEGER
UPDATE Table1 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount1 = @@ROWCOUNT
UPDATE Table2 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount2 = @@ROWCOUNT
UPDATE Table3 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount3 = @@ROWCOUNT
UPDATE Table4 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount4 = @@ROWCOUNT
SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END
Including the jQuery Library
That is jQuery code. You'll first need to make sure the jQuery library is loaded. If you don't host the library file yourself, you can hotlink one from the jQuery CDN:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
You can do this within the <head>
section, but it's fine as long as it's loaded before your jQuery code.
Further reading:
Placing Your Code in the Page
Place your code inside <script>
tags. It can be inserted anywhere within either <head>
or <body>
. If you place it before the <input>
and <tr>
tags (as referenced in your code), you have to use $(document).ready()
to make sure those elements are present before the code is run:
$(document).ready(function() {
// put your jQuery code here.
});
If you want your page content to be loaded as soon as possible, you might want to place it as close as the </body>
close tag as possible. But another common practice is to place all JavaScript code in the <head>
section. This is your choice, based on your coding style and needs.
Suggestion: Instead of embedding JS/jQuery code directly into an HTML page, consider placing the code in a separate .js file. This will allow you to reuse the same code on other pages:
<script src="/path/to/your/code.js"></script>
Further reading:
Simple and precise (Source: Socket.IO google group):
socket.emit
allows you to emit custom events on the server and client
socket.send
sends messages which are received with the 'message'
event
I've had a similar issue which boiled down to removing files under "unmerged paths"
Those files had to be removed using git rm
A stack pointer is a small register that stores the address of the top of stack. It is used for the purpose of pointing address of the top of the stack.
This Android WiFi ADB plugin doesn't work in 4.1.1 (anymore)
But there is much more simple solution: If you have an Android 11 (api30) device you should use Android Studio 2020.3.1 (Canary) to connect. It's super easy
Then you go to developer settings and scan QR code. That's it. You can use connected device in other (older) Android Studio version now as well
Check the android path of the emulator.
I had to change the registry in here:
HKEY_LOCAL_MACHINE > SOFTWARE > WOW6432Node > Android SDK Tools
to the actual path of the sdk location (which can be found in android studio: settings-> System Settings -> Android SDK)
All the credit goes to the author of this blogpost www.clearlyagileinc.com/
In a column with blanks, you can get the last value with
=+sort(G:G,row(G:G)*(G:G<>""),)
you can use guava
's Multimaps
@Canonical
class Persion {
String name
Integer age
}
List<Persion> list = [
new Persion("qianzi", 100),
new Persion("qianzi", 99),
new Persion("zhijia", 99)
]
println Multimaps.index(list, { Persion p -> return p.name })
it print:
[qianzi:[com.ctcf.message.Persion(qianzi, 100),com.ctcf.message.Persion(qianzi, 88)],zhijia:[com.ctcf.message.Persion(zhijia, 99)]]
In Java 8 with Stream API, you can do this.
IntStream.rangeClosed('A', 'Z').mapToObj(var -> (char) var).forEach(System.out::println);
As the error states, it can't bind - which typically means it's in use by another process. From a command line run:
netstat -a -n -o
Interrogate the output for port 9999 in use in the left hand column.
For more information: http://www.zdnetasia.com/see-what-process-is-using-a-tcp-port-62047950.htm
It was helpful for me: link
function hoverTouchUnstick() {
// Check if the device supports touch events
if('ontouchstart' in document.documentElement) {
// Loop through each stylesheet
for(var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
// Verify if cssRules exists in sheet
if(sheet.cssRules) {
// Loop through each rule in sheet
for(var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
// Verify rule has selector text
if(rule.selectorText) {
// Replace hover psuedo-class with active psuedo-class
rule.selectorText = rule.selectorText.replace(":hover", ":active");
}
}
}
}
}
}
\n --> newline character is not working for inserting a new line.
str="Hello!!";
document.write(str);
document.write("\n");
document.write(str);
But if we use below code then it works fine and it gives new line.
document.write(str);
document.write("<br>");
document.write(str);
Note:: I tried in Visual Studio Code.
A regular for each will do:
foreach (var item in collection)
{
// do your stuff
}
Use access modifier before the member definition:
private $connection;
As you cannot use function call in member definition in PHP, do it in constructor:
public function __construct() {
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:
Parent:
.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';
Child:
require: {
myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';
I modified @JayRiggs' answer, and this works. You need the if
because sometimes the SelectedRows may be empty, so the index operation will throw a exception.
if (yourDGV.SelectedRows.Count>0){
int index = yourDGV.SelectedRows[0].Index;
}
Angular 2 completely ignores type=date
. If you change type to text
you'll see that your input
has two-way binding.
<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>
Here is pretty bad advise with better one to follow:
My project originally used jQuery
. So, I'm using jQuery datepicker
for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date
doesn't work in Firefox.
Good advise: There are few pretty good Angular2 datepickers
:
What about using idate()? idate()
$integer = idate('w', $timestamp);
Add some code to the Form Load event:
me.maximumsize = new size(Width, Height)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false
Example: For a Form height and width of 50 pixels each:
me.maximumsize = new size(50, 50)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false
Note that setting maximumsize
and minimumsize
to the same size as shown here prevents resizing the Form.
A composer dump-autoload
should fix it.
extension String {
//Fucntion to get the index of a particular string
func index(of target: String) -> Int? {
if let range = self.range(of: target) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
//Fucntion to get the last index of occurence of a given string
func lastIndex(of target: String) -> Int? {
if let range = self.range(of: target, options: .backwards) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
}
Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?" Yes, it is.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])
plt.show()
You'll get:
Most modern browser support console.dir(obj)
, which will return all the properties of an object that it inherited through its constructor. See Mozilla's documentation for more info and current browser support.
console.dir(Math)
=> MathConstructor
E: 2.718281828459045
LN2: 0.6931471805599453
...
tan: function tan() { [native code] }
__proto__: Object
For Debian 9 I found mine using Franke Heikens answer - $ /etc/postgresql/9.6/main/postgresql.conf
You can do that in several ways:
<<
but that is not the usual wayWith string interpolation
source = "#{ROOT_DIR}/#{project}/App.config"
with +
source = "#{ROOT_DIR}/" + project + "/App.config"
The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.
When dealing with pathnames, you may want to use File.join
to avoid messing up with pathname separator.
In the end, it is a matter of taste.
You can use inline css :
<td style = "text-align: center;">
You can use this to get remaining charged in percentage.
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
batterLevel.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
I solved same issue by adding polyfill following:
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
Hope someone find this helpful.
com.sun.mail.util.MailLogger
is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.
If you're using maven add the following dependency (you might want to change version):
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
This might be useful for someone.
Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.
To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.
def compute_PMF(data):
import numpy as np
from collections import Counter
_, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
h = Counter(np.digitize(data,bins) - 1)
weights = np.asarray(list(h.values()))
weights = weights / weights.sum()
values = np.asarray(list(h.keys()))
return weights, values
####
Refs:
[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.
If you are running the script through browser, then set the set_time_limit
to zero for infinite seconds.
set_time_limit(0);
Increase the curl's operation time limit using this option CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds
It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.